helpers.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. package cwhub
  2. // Install, upgrade and remove items from the hub to the local configuration
  3. // XXX: this file could use a better name
  4. import (
  5. "bytes"
  6. "crypto/sha256"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "github.com/enescakir/emoji"
  14. log "github.com/sirupsen/logrus"
  15. )
  16. // InstallItem installs an item from the hub
  17. func (h *Hub) InstallItem(name string, itemType string, force bool, downloadOnly bool) error {
  18. item := h.GetItem(itemType, name)
  19. if item == nil {
  20. return fmt.Errorf("unable to retrieve item: %s", name)
  21. }
  22. if downloadOnly && item.Downloaded && item.UpToDate {
  23. log.Warningf("%s is already downloaded and up-to-date", item.Name)
  24. if !force {
  25. return nil
  26. }
  27. }
  28. err := h.DownloadLatest(item, force, true)
  29. if err != nil {
  30. return fmt.Errorf("while downloading %s: %w", item.Name, err)
  31. }
  32. if err = h.AddItem(*item); err != nil {
  33. return fmt.Errorf("while adding %s: %w", item.Name, err)
  34. }
  35. if downloadOnly {
  36. log.Infof("Downloaded %s to %s", item.Name, filepath.Join(h.cfg.HubDir, item.RemotePath))
  37. return nil
  38. }
  39. err = h.EnableItem(item)
  40. if err != nil {
  41. return fmt.Errorf("while enabling %s: %w", item.Name, err)
  42. }
  43. if err := h.AddItem(*item); err != nil {
  44. return fmt.Errorf("while adding %s: %w", item.Name, err)
  45. }
  46. log.Infof("Enabled %s", item.Name)
  47. return nil
  48. }
  49. // RemoveItem removes one - or all - the items from the hub
  50. func (h *Hub) RemoveMany(itemType string, name string, all bool, purge bool, forceAction bool) error {
  51. if name != "" {
  52. item := h.GetItem(itemType, name)
  53. if item == nil {
  54. return fmt.Errorf("can't find '%s' in %s", name, itemType)
  55. }
  56. err := h.DisableItem(item, purge, forceAction)
  57. if err != nil {
  58. return fmt.Errorf("unable to disable %s: %w", item.Name, err)
  59. }
  60. if err = h.AddItem(*item); err != nil {
  61. return fmt.Errorf("unable to add %s: %w", item.Name, err)
  62. }
  63. return nil
  64. }
  65. if !all {
  66. return fmt.Errorf("removing item: no item specified")
  67. }
  68. disabled := 0
  69. // remove all
  70. for _, v := range h.GetItemMap(itemType) {
  71. if !v.Installed {
  72. continue
  73. }
  74. err := h.DisableItem(&v, purge, forceAction)
  75. if err != nil {
  76. return fmt.Errorf("unable to disable %s: %w", v.Name, err)
  77. }
  78. if err := h.AddItem(v); err != nil {
  79. return fmt.Errorf("unable to add %s: %w", v.Name, err)
  80. }
  81. disabled++
  82. }
  83. log.Infof("Disabled %d items", disabled)
  84. return nil
  85. }
  86. // UpgradeConfig upgrades an item from the hub
  87. func (h *Hub) UpgradeConfig(itemType string, name string, force bool) error {
  88. updated := 0
  89. found := false
  90. for _, v := range h.GetItemMap(itemType) {
  91. if name != "" && name != v.Name {
  92. continue
  93. }
  94. if !v.Installed {
  95. log.Tracef("skip %s, not installed", v.Name)
  96. continue
  97. }
  98. if !v.Downloaded {
  99. log.Warningf("%s: not downloaded, please install.", v.Name)
  100. continue
  101. }
  102. found = true
  103. if v.UpToDate {
  104. log.Infof("%s: up-to-date", v.Name)
  105. if err := h.DownloadDataIfNeeded(v, force); err != nil {
  106. return fmt.Errorf("%s: download failed: %w", v.Name, err)
  107. }
  108. if !force {
  109. continue
  110. }
  111. }
  112. if err := h.DownloadLatest(&v, force, true); err != nil {
  113. return fmt.Errorf("%s: download failed: %w", v.Name, err)
  114. }
  115. if !v.UpToDate {
  116. if v.Tainted {
  117. log.Infof("%v %s is tainted, --force to overwrite", emoji.Warning, v.Name)
  118. } else if v.Local {
  119. log.Infof("%v %s is local", emoji.Prohibited, v.Name)
  120. }
  121. } else {
  122. // this is used while scripting to know if the hub has been upgraded
  123. // and a configuration reload is required
  124. fmt.Printf("updated %s\n", v.Name)
  125. log.Infof("%v %s : updated", emoji.Package, v.Name)
  126. updated++
  127. }
  128. if err := h.AddItem(v); err != nil {
  129. return fmt.Errorf("unable to add %s: %w", v.Name, err)
  130. }
  131. }
  132. if !found && name == "" {
  133. log.Infof("No %s installed, nothing to upgrade", itemType)
  134. } else if !found {
  135. log.Errorf("can't find '%s' in %s", name, itemType)
  136. } else if updated == 0 && found {
  137. if name == "" {
  138. log.Infof("All %s are already up-to-date", itemType)
  139. } else {
  140. log.Infof("Item '%s' is up-to-date", name)
  141. }
  142. } else if updated != 0 {
  143. log.Infof("Upgraded %d items", updated)
  144. }
  145. return nil
  146. }
  147. // DownloadLatest will download the latest version of Item to the tdir directory
  148. func (h *Hub) DownloadLatest(target *Item, overwrite bool, updateOnly bool) error {
  149. var err error
  150. log.Debugf("Downloading %s %s", target.Type, target.Name)
  151. if target.Type != COLLECTIONS {
  152. if !target.Installed && updateOnly && target.Downloaded {
  153. log.Debugf("skipping upgrade of %s : not installed", target.Name)
  154. return nil
  155. }
  156. return h.DownloadItem(target, overwrite)
  157. }
  158. // collection
  159. for _, sub := range target.SubItems() {
  160. val, ok := h.Items[sub.Type][sub.Name]
  161. if !ok {
  162. return fmt.Errorf("required %s %s of %s doesn't exist, abort", sub.Type, sub.Name, target.Name)
  163. }
  164. if !val.Installed && updateOnly && val.Downloaded {
  165. log.Debugf("skipping upgrade of %s : not installed", target.Name)
  166. continue
  167. }
  168. log.Debugf("Download %s sub-item : %s %s (%t -> %t)", target.Name, sub.Type, sub.Name, target.Installed, updateOnly)
  169. //recurse as it's a collection
  170. if sub.Type == COLLECTIONS {
  171. log.Tracef("collection, recurse")
  172. err = h.DownloadLatest(&val, overwrite, updateOnly)
  173. if err != nil {
  174. return fmt.Errorf("while downloading %s: %w", val.Name, err)
  175. }
  176. }
  177. downloaded := val.Downloaded
  178. err = h.DownloadItem(&val, overwrite)
  179. if err != nil {
  180. return fmt.Errorf("while downloading %s: %w", val.Name, err)
  181. }
  182. // We need to enable an item when it has been added to a collection since latest release of the collection.
  183. // We check if val.Downloaded is false because maybe the item has been disabled by the user.
  184. if !val.Installed && !downloaded {
  185. if err = h.EnableItem(&val); err != nil {
  186. return fmt.Errorf("enabling '%s': %w", val.Name, err)
  187. }
  188. }
  189. h.Items[sub.Type][sub.Name] = val
  190. }
  191. err = h.DownloadItem(target, overwrite)
  192. if err != nil {
  193. return fmt.Errorf("failed to download item: %w", err)
  194. }
  195. return nil
  196. }
  197. func (h *Hub) DownloadItem(target *Item, overwrite bool) error {
  198. tdir := h.cfg.HubDir
  199. // if user didn't --force, don't overwrite local, tainted, up-to-date files
  200. if !overwrite {
  201. if target.Tainted {
  202. log.Debugf("%s : tainted, not updated", target.Name)
  203. return nil
  204. }
  205. if target.UpToDate {
  206. // We still have to check if data files are present
  207. log.Debugf("%s : up-to-date, not updated", target.Name)
  208. }
  209. }
  210. req, err := http.NewRequest(http.MethodGet, fmt.Sprintf(RawFileURLTemplate, HubBranch, target.RemotePath), nil)
  211. if err != nil {
  212. return fmt.Errorf("while downloading %s: %w", req.URL.String(), err)
  213. }
  214. resp, err := http.DefaultClient.Do(req)
  215. if err != nil {
  216. return fmt.Errorf("while downloading %s: %w", req.URL.String(), err)
  217. }
  218. if resp.StatusCode != http.StatusOK {
  219. return fmt.Errorf("bad http code %d for %s", resp.StatusCode, req.URL.String())
  220. }
  221. defer resp.Body.Close()
  222. body, err := io.ReadAll(resp.Body)
  223. if err != nil {
  224. return fmt.Errorf("while reading %s: %w", req.URL.String(), err)
  225. }
  226. hash := sha256.New()
  227. if _, err = hash.Write(body); err != nil {
  228. return fmt.Errorf("while hashing %s: %w", target.Name, err)
  229. }
  230. meow := fmt.Sprintf("%x", hash.Sum(nil))
  231. if meow != target.Versions[target.Version].Digest {
  232. log.Errorf("Downloaded version doesn't match index, please 'hub update'")
  233. log.Debugf("got %s, expected %s", meow, target.Versions[target.Version].Digest)
  234. return fmt.Errorf("invalid download hash for %s", target.Name)
  235. }
  236. //all good, install
  237. //check if parent dir exists
  238. tmpdirs := strings.Split(tdir+"/"+target.RemotePath, "/")
  239. parentDir := strings.Join(tmpdirs[:len(tmpdirs)-1], "/")
  240. // ensure that target file is within target dir
  241. finalPath, err := filepath.Abs(tdir + "/" + target.RemotePath)
  242. if err != nil {
  243. return fmt.Errorf("filepath.Abs error on %s: %w", tdir+"/"+target.RemotePath, err)
  244. }
  245. if !strings.HasPrefix(finalPath, tdir) {
  246. return fmt.Errorf("path %s escapes %s, abort", target.RemotePath, tdir)
  247. }
  248. // check dir
  249. if _, err = os.Stat(parentDir); os.IsNotExist(err) {
  250. log.Debugf("%s doesn't exist, create", parentDir)
  251. if err = os.MkdirAll(parentDir, os.ModePerm); err != nil {
  252. return fmt.Errorf("while creating parent directories: %w", err)
  253. }
  254. }
  255. // check actual file
  256. if _, err = os.Stat(finalPath); !os.IsNotExist(err) {
  257. log.Warningf("%s : overwrite", target.Name)
  258. log.Debugf("target: %s/%s", tdir, target.RemotePath)
  259. } else {
  260. log.Infof("%s : OK", target.Name)
  261. }
  262. f, err := os.OpenFile(tdir+"/"+target.RemotePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
  263. if err != nil {
  264. return fmt.Errorf("while opening file: %w", err)
  265. }
  266. defer f.Close()
  267. _, err = f.Write(body)
  268. if err != nil {
  269. return fmt.Errorf("while writing file: %w", err)
  270. }
  271. target.Downloaded = true
  272. target.Tainted = false
  273. target.UpToDate = true
  274. if err = downloadData(h.cfg.InstallDataDir, overwrite, bytes.NewReader(body)); err != nil {
  275. return fmt.Errorf("while downloading data for %s: %w", target.FileName, err)
  276. }
  277. h.Items[target.Type][target.Name] = *target
  278. return nil
  279. }
  280. // DownloadDataIfNeeded downloads the data files for an item
  281. func (h *Hub) DownloadDataIfNeeded(target Item, force bool) error {
  282. itemFilePath := fmt.Sprintf("%s/%s/%s/%s", h.cfg.InstallDir, target.Type, target.Stage, target.FileName)
  283. itemFile, err := os.Open(itemFilePath)
  284. if err != nil {
  285. return fmt.Errorf("while opening %s: %w", itemFilePath, err)
  286. }
  287. defer itemFile.Close()
  288. if err = downloadData(h.cfg.InstallDataDir, force, itemFile); err != nil {
  289. return fmt.Errorf("while downloading data for %s: %w", itemFilePath, err)
  290. }
  291. return nil
  292. }