utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  13. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  14. "github.com/crowdsecurity/crowdsec/pkg/types"
  15. "github.com/enescakir/emoji"
  16. "github.com/olekukonko/tablewriter"
  17. dto "github.com/prometheus/client_model/go"
  18. "github.com/prometheus/prom2json"
  19. log "github.com/sirupsen/logrus"
  20. "golang.org/x/mod/semver"
  21. "gopkg.in/yaml.v2"
  22. )
  23. func inSlice(s string, slice []string) bool {
  24. for _, str := range slice {
  25. if s == str {
  26. return true
  27. }
  28. }
  29. return false
  30. }
  31. func indexOf(s string, slice []string) int {
  32. for i, elem := range slice {
  33. if s == elem {
  34. return i
  35. }
  36. }
  37. return -1
  38. }
  39. func manageCliDecisionAlerts(ip *string, ipRange *string, scope *string, value *string) error {
  40. /*if a range is provided, change the scope*/
  41. if *ipRange != "" {
  42. _, _, err := net.ParseCIDR(*ipRange)
  43. if err != nil {
  44. return fmt.Errorf("%s isn't a valid range", *ipRange)
  45. }
  46. }
  47. if *ip != "" {
  48. ipRepr := net.ParseIP(*ip)
  49. if ipRepr == nil {
  50. return fmt.Errorf("%s isn't a valid ip", *ip)
  51. }
  52. }
  53. //avoid confusion on scope (ip vs Ip and range vs Range)
  54. switch strings.ToLower(*scope) {
  55. case "ip":
  56. *scope = types.Ip
  57. case "range":
  58. *scope = types.Range
  59. }
  60. return nil
  61. }
  62. func setHubBranch() error {
  63. /*
  64. if no branch has been specified in flags for the hub, then use the one corresponding to crowdsec version
  65. */
  66. if cwhub.HubBranch == "" {
  67. latest, err := cwversion.Latest()
  68. if err != nil {
  69. cwhub.HubBranch = "master"
  70. return err
  71. }
  72. if cwversion.Version == latest {
  73. cwhub.HubBranch = "master"
  74. } else if semver.Compare(cwversion.Version, latest) == 1 { // if current version is greater than the latest we are in pre-release
  75. log.Debugf("Your current crowdsec version seems to be a pre-release (%s)", cwversion.Version)
  76. cwhub.HubBranch = "master"
  77. } else {
  78. log.Warnf("Crowdsec is not the latest version. Current version is '%s' and latest version is '%s'. Please update it!", cwversion.Version, latest)
  79. log.Warnf("As a result, you will not be able to use parsers/scenarios/collections added to Crowdsec Hub after CrowdSec %s", latest)
  80. cwhub.HubBranch = cwversion.Version
  81. }
  82. log.Debugf("Using branch '%s' for the hub", cwhub.HubBranch)
  83. }
  84. return nil
  85. }
  86. func ListItem(itemType string, args []string) {
  87. var hubStatus []map[string]string
  88. if len(args) == 1 {
  89. hubStatus = cwhub.HubStatus(itemType, args[0], all)
  90. } else {
  91. hubStatus = cwhub.HubStatus(itemType, "", all)
  92. }
  93. if csConfig.Cscli.Output == "human" {
  94. table := tablewriter.NewWriter(os.Stdout)
  95. table.SetCenterSeparator("")
  96. table.SetColumnSeparator("")
  97. table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
  98. table.SetAlignment(tablewriter.ALIGN_LEFT)
  99. table.SetHeader([]string{"Name", fmt.Sprintf("%v Status", emoji.Package), "Version", "Local Path"})
  100. for _, v := range hubStatus {
  101. table.Append([]string{v["name"], v["utf8_status"], v["local_version"], v["local_path"]})
  102. }
  103. table.Render()
  104. } else if csConfig.Cscli.Output == "json" {
  105. x, err := json.MarshalIndent(hubStatus, "", " ")
  106. if err != nil {
  107. log.Fatalf("failed to unmarshal")
  108. }
  109. fmt.Printf("%s", string(x))
  110. } else if csConfig.Cscli.Output == "raw" {
  111. for _, v := range hubStatus {
  112. fmt.Printf("%s %s\n", v["name"], v["description"])
  113. }
  114. }
  115. }
  116. func InstallItem(name string, obtype string, force bool) {
  117. it := cwhub.GetItem(obtype, name)
  118. if it == nil {
  119. log.Fatalf("unable to retrive item : %s", name)
  120. }
  121. item := *it
  122. if downloadOnly && item.Downloaded && item.UpToDate {
  123. log.Warningf("%s is already downloaded and up-to-date", item.Name)
  124. if !force {
  125. return
  126. }
  127. }
  128. item, err := cwhub.DownloadLatest(csConfig.Cscli, item, force)
  129. if err != nil {
  130. log.Fatalf("error while downloading %s : %v", item.Name, err)
  131. }
  132. cwhub.AddItem(obtype, item)
  133. if downloadOnly {
  134. log.Infof("Downloaded %s to %s", item.Name, csConfig.Cscli.HubDir+"/"+item.RemotePath)
  135. return
  136. }
  137. item, err = cwhub.EnableItem(csConfig.Cscli, item)
  138. if err != nil {
  139. log.Fatalf("error while enabled %s : %v.", item.Name, err)
  140. }
  141. cwhub.AddItem(obtype, item)
  142. log.Infof("Enabled %s", item.Name)
  143. return
  144. }
  145. func RemoveMany(itemType string, name string) {
  146. var err error
  147. var disabled int
  148. if name != "" {
  149. it := cwhub.GetItem(itemType, name)
  150. if it == nil {
  151. log.Fatalf("unable to retrieve: %s", name)
  152. }
  153. item := *it
  154. item, err = cwhub.DisableItem(csConfig.Cscli, item, purge, forceAction)
  155. if err != nil {
  156. log.Fatalf("unable to disable %s : %v", item.Name, err)
  157. }
  158. cwhub.AddItem(itemType, item)
  159. return
  160. } else if name == "" && all {
  161. for _, v := range cwhub.GetItemMap(itemType) {
  162. v, err = cwhub.DisableItem(csConfig.Cscli, v, purge, forceAction)
  163. if err != nil {
  164. log.Fatalf("unable to disable %s : %v", v.Name, err)
  165. }
  166. cwhub.AddItem(itemType, v)
  167. disabled++
  168. }
  169. }
  170. if name != "" && !all {
  171. log.Errorf("%s not found", name)
  172. return
  173. }
  174. log.Infof("Disabled %d items", disabled)
  175. }
  176. func UpgradeConfig(itemType string, name string, force bool) {
  177. var err error
  178. var updated int
  179. var found bool
  180. for _, v := range cwhub.GetItemMap(itemType) {
  181. if name != "" && name != v.Name {
  182. continue
  183. }
  184. if !v.Installed {
  185. log.Tracef("skip %s, not installed", v.Name)
  186. if !force {
  187. continue
  188. }
  189. }
  190. if !v.Downloaded {
  191. log.Warningf("%s : not downloaded, please install.", v.Name)
  192. if !force {
  193. continue
  194. }
  195. }
  196. found = true
  197. if v.UpToDate {
  198. log.Infof("%s : up-to-date", v.Name)
  199. if !force {
  200. continue
  201. }
  202. }
  203. v, err = cwhub.DownloadLatest(csConfig.Cscli, v, force)
  204. if err != nil {
  205. log.Fatalf("%s : download failed : %v", v.Name, err)
  206. }
  207. if !v.UpToDate {
  208. if v.Tainted {
  209. log.Infof("%v %s is tainted, --force to overwrite", emoji.Warning, v.Name)
  210. } else if v.Local {
  211. log.Infof("%v %s is local", emoji.Prohibited, v.Name)
  212. }
  213. } else {
  214. log.Infof("%v %s : updated", emoji.Package, v.Name)
  215. updated++
  216. }
  217. cwhub.AddItem(itemType, v)
  218. }
  219. if !found && name == "" {
  220. log.Infof("No %s installed, nothing to upgrade", itemType)
  221. } else if !found {
  222. log.Errorf("Item '%s' not found in hub", name)
  223. } else if updated == 0 && found {
  224. if name == "" {
  225. log.Infof("All %s are already up-to-date", itemType)
  226. } else {
  227. log.Infof("Item '%s' is up-to-date", name)
  228. }
  229. } else if updated != 0 {
  230. log.Infof("Upgraded %d items", updated)
  231. }
  232. }
  233. func InspectItem(name string, objecitemType string) {
  234. hubItem := cwhub.GetItem(objecitemType, name)
  235. if hubItem == nil {
  236. log.Fatalf("unable to retrieve item.")
  237. }
  238. buff, err := yaml.Marshal(*hubItem)
  239. if err != nil {
  240. log.Fatalf("unable to marshal item : %s", err)
  241. }
  242. fmt.Printf("%s", string(buff))
  243. if csConfig.Prometheus.Enabled {
  244. if csConfig.Prometheus.ListenAddr == "" || csConfig.Prometheus.ListenPort == 0 {
  245. log.Warningf("No prometheus address or port specified in '%s', can't show metrics", *csConfig.Self)
  246. return
  247. }
  248. if prometheusURL == "" {
  249. log.Debugf("No prometheus URL provided using: %s:%d", csConfig.Prometheus.ListenAddr, csConfig.Prometheus.ListenPort)
  250. prometheusURL = fmt.Sprintf("http://%s:%d/metrics", csConfig.Prometheus.ListenAddr, csConfig.Prometheus.ListenPort)
  251. }
  252. fmt.Printf("\nCurrent metrics : \n\n")
  253. ShowMetrics(hubItem)
  254. }
  255. }
  256. func ShowMetrics(hubItem *cwhub.Item) {
  257. switch hubItem.Type {
  258. case cwhub.PARSERS:
  259. metrics := GetParserMetric(prometheusURL, hubItem.Name)
  260. ShowParserMetric(hubItem.Name, metrics)
  261. case cwhub.SCENARIOS:
  262. metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
  263. ShowScenarioMetric(hubItem.Name, metrics)
  264. case cwhub.COLLECTIONS:
  265. for _, item := range hubItem.Parsers {
  266. metrics := GetParserMetric(prometheusURL, item)
  267. ShowParserMetric(item, metrics)
  268. }
  269. for _, item := range hubItem.Scenarios {
  270. metrics := GetScenarioMetric(prometheusURL, item)
  271. ShowScenarioMetric(item, metrics)
  272. }
  273. for _, item := range hubItem.Collections {
  274. hubItem := cwhub.GetItem(cwhub.COLLECTIONS, item)
  275. if hubItem == nil {
  276. log.Fatalf("unable to retrieve item '%s' from collection '%s'", item, hubItem.Name)
  277. }
  278. ShowMetrics(hubItem)
  279. }
  280. default:
  281. log.Errorf("item of type '%s' is unknown", hubItem.Type)
  282. }
  283. }
  284. /*This is a complete rip from prom2json*/
  285. func GetParserMetric(url string, itemName string) map[string]map[string]int {
  286. stats := make(map[string]map[string]int)
  287. result := GetPrometheusMetric(url)
  288. for idx, fam := range result {
  289. if !strings.HasPrefix(fam.Name, "cs_") {
  290. continue
  291. }
  292. log.Tracef("round %d", idx)
  293. for _, m := range fam.Metrics {
  294. metric := m.(prom2json.Metric)
  295. name, ok := metric.Labels["name"]
  296. if !ok {
  297. log.Debugf("no name in Metric %v", metric.Labels)
  298. }
  299. if name != itemName {
  300. continue
  301. }
  302. source, ok := metric.Labels["source"]
  303. if !ok {
  304. log.Debugf("no source in Metric %v", metric.Labels)
  305. }
  306. value := m.(prom2json.Metric).Value
  307. fval, err := strconv.ParseFloat(value, 32)
  308. if err != nil {
  309. log.Errorf("Unexpected int value %s : %s", value, err)
  310. continue
  311. }
  312. ival := int(fval)
  313. switch fam.Name {
  314. case "cs_reader_hits_total":
  315. if _, ok := stats[source]; !ok {
  316. stats[source] = make(map[string]int)
  317. stats[source]["parsed"] = 0
  318. stats[source]["reads"] = 0
  319. stats[source]["unparsed"] = 0
  320. stats[source]["hits"] = 0
  321. }
  322. stats[source]["reads"] += ival
  323. case "cs_parser_hits_ok_total":
  324. if _, ok := stats[source]; !ok {
  325. stats[source] = make(map[string]int)
  326. }
  327. stats[source]["parsed"] += ival
  328. case "cs_parser_hits_ko_total":
  329. if _, ok := stats[source]; !ok {
  330. stats[source] = make(map[string]int)
  331. }
  332. stats[source]["unparsed"] += ival
  333. case "cs_node_hits_total":
  334. if _, ok := stats[source]; !ok {
  335. stats[source] = make(map[string]int)
  336. }
  337. stats[source]["hits"] += ival
  338. case "cs_node_hits_ok_total":
  339. if _, ok := stats[source]; !ok {
  340. stats[source] = make(map[string]int)
  341. }
  342. stats[source]["parsed"] += ival
  343. case "cs_node_hits_ko_total":
  344. if _, ok := stats[source]; !ok {
  345. stats[source] = make(map[string]int)
  346. }
  347. stats[source]["unparsed"] += ival
  348. default:
  349. continue
  350. }
  351. }
  352. }
  353. return stats
  354. }
  355. func GetScenarioMetric(url string, itemName string) map[string]int {
  356. stats := make(map[string]int)
  357. stats["instanciation"] = 0
  358. stats["curr_count"] = 0
  359. stats["overflow"] = 0
  360. stats["pour"] = 0
  361. stats["underflow"] = 0
  362. result := GetPrometheusMetric(url)
  363. for idx, fam := range result {
  364. if !strings.HasPrefix(fam.Name, "cs_") {
  365. continue
  366. }
  367. log.Tracef("round %d", idx)
  368. for _, m := range fam.Metrics {
  369. metric := m.(prom2json.Metric)
  370. name, ok := metric.Labels["name"]
  371. if !ok {
  372. log.Debugf("no name in Metric %v", metric.Labels)
  373. }
  374. if name != itemName {
  375. continue
  376. }
  377. value := m.(prom2json.Metric).Value
  378. fval, err := strconv.ParseFloat(value, 32)
  379. if err != nil {
  380. log.Errorf("Unexpected int value %s : %s", value, err)
  381. continue
  382. }
  383. ival := int(fval)
  384. switch fam.Name {
  385. case "cs_bucket_created_total":
  386. stats["instanciation"] += ival
  387. case "cs_buckets":
  388. stats["curr_count"] += ival
  389. case "cs_bucket_overflowed_total":
  390. stats["overflow"] += ival
  391. case "cs_bucket_poured_total":
  392. stats["pour"] += ival
  393. case "cs_bucket_underflowed_total":
  394. stats["underflow"] += ival
  395. default:
  396. continue
  397. }
  398. }
  399. }
  400. return stats
  401. }
  402. func GetPrometheusMetric(url string) []*prom2json.Family {
  403. mfChan := make(chan *dto.MetricFamily, 1024)
  404. // Start with the DefaultTransport for sane defaults.
  405. transport := http.DefaultTransport.(*http.Transport).Clone()
  406. // Conservatively disable HTTP keep-alives as this program will only
  407. // ever need a single HTTP request.
  408. transport.DisableKeepAlives = true
  409. // Timeout early if the server doesn't even return the headers.
  410. transport.ResponseHeaderTimeout = time.Minute
  411. go func() {
  412. defer types.CatchPanic("crowdsec/GetPrometheusMetric")
  413. err := prom2json.FetchMetricFamilies(url, mfChan, transport)
  414. if err != nil {
  415. log.Fatalf("failed to fetch prometheus metrics : %v", err)
  416. }
  417. }()
  418. result := []*prom2json.Family{}
  419. for mf := range mfChan {
  420. result = append(result, prom2json.NewFamily(mf))
  421. }
  422. log.Debugf("Finished reading prometheus output, %d entries", len(result))
  423. return result
  424. }
  425. func ShowScenarioMetric(itemName string, metrics map[string]int) {
  426. if metrics["instanciation"] == 0 {
  427. return
  428. }
  429. table := tablewriter.NewWriter(os.Stdout)
  430. table.SetHeader([]string{"Current Count", "Overflows", "Instanciated", "Poured", "Expired"})
  431. table.Append([]string{fmt.Sprintf("%d", metrics["curr_count"]), fmt.Sprintf("%d", metrics["overflow"]), fmt.Sprintf("%d", metrics["instanciation"]), fmt.Sprintf("%d", metrics["pour"]), fmt.Sprintf("%d", metrics["underflow"])})
  432. fmt.Printf(" - (Scenario) %s: \n", itemName)
  433. table.Render()
  434. fmt.Println()
  435. }
  436. func ShowParserMetric(itemName string, metrics map[string]map[string]int) {
  437. skip := true
  438. table := tablewriter.NewWriter(os.Stdout)
  439. table.SetHeader([]string{"Parsers", "Hits", "Parsed", "Unparsed"})
  440. for source, stats := range metrics {
  441. if stats["hits"] > 0 {
  442. table.Append([]string{source, fmt.Sprintf("%d", stats["hits"]), fmt.Sprintf("%d", stats["parsed"]), fmt.Sprintf("%d", stats["unparsed"])})
  443. skip = false
  444. }
  445. }
  446. if !skip {
  447. fmt.Printf(" - (Parser) %s: \n", itemName)
  448. table.Render()
  449. fmt.Println()
  450. }
  451. }
  452. //it's a rip of the cli version, but in silent-mode
  453. func silenceInstallItem(name string, obtype string) (string, error) {
  454. var item *cwhub.Item
  455. item = cwhub.GetItem(obtype, name)
  456. if item == nil {
  457. return "", fmt.Errorf("error retrieving item")
  458. }
  459. it := *item
  460. if downloadOnly && it.Downloaded && it.UpToDate {
  461. return fmt.Sprintf("%s is already downloaded and up-to-date", it.Name), nil
  462. }
  463. it, err := cwhub.DownloadLatest(csConfig.Cscli, it, forceAction)
  464. if err != nil {
  465. return "", fmt.Errorf("error while downloading %s : %v", it.Name, err)
  466. }
  467. if err := cwhub.AddItem(obtype, it); err != nil {
  468. return "", err
  469. }
  470. if downloadOnly {
  471. return fmt.Sprintf("Downloaded %s to %s", it.Name, csConfig.Cscli.HubDir+"/"+it.RemotePath), nil
  472. }
  473. it, err = cwhub.EnableItem(csConfig.Cscli, it)
  474. if err != nil {
  475. return "", fmt.Errorf("error while enabled %s : %v", it.Name, err)
  476. }
  477. if err := cwhub.AddItem(obtype, it); err != nil {
  478. return "", err
  479. }
  480. return fmt.Sprintf("Enabled %s", it.Name), nil
  481. }
  482. func RestoreHub(dirPath string) error {
  483. var err error
  484. for _, itype := range cwhub.ItemTypes {
  485. itemDirectory := fmt.Sprintf("%s/%s/", dirPath, itype)
  486. if _, err = os.Stat(itemDirectory); err != nil {
  487. log.Infof("no %s in backup", itype)
  488. continue
  489. }
  490. /*restore the upstream items*/
  491. upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
  492. file, err := ioutil.ReadFile(upstreamListFN)
  493. if err != nil {
  494. return fmt.Errorf("error while opening %s : %s", upstreamListFN, err)
  495. }
  496. var upstreamList []string
  497. err = json.Unmarshal([]byte(file), &upstreamList)
  498. if err != nil {
  499. return fmt.Errorf("error unmarshaling %s : %s", upstreamListFN, err)
  500. }
  501. for _, toinstall := range upstreamList {
  502. label, err := silenceInstallItem(toinstall, itype)
  503. if err != nil {
  504. log.Errorf("Error while installing %s : %s", toinstall, err)
  505. } else if label != "" {
  506. log.Infof("Installed %s : %s", toinstall, label)
  507. } else {
  508. log.Printf("Installed %s : ok", toinstall)
  509. }
  510. }
  511. /*restore the local and tainted items*/
  512. files, err := ioutil.ReadDir(itemDirectory)
  513. if err != nil {
  514. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err)
  515. }
  516. for _, file := range files {
  517. //this was the upstream data
  518. if file.Name() == fmt.Sprintf("upstream-%s.json", itype) {
  519. continue
  520. }
  521. if itype == cwhub.PARSERS || itype == cwhub.PARSERS_OVFLW {
  522. //we expect a stage here
  523. if !file.IsDir() {
  524. continue
  525. }
  526. stage := file.Name()
  527. stagedir := fmt.Sprintf("%s/%s/%s/", csConfig.ConfigPaths.ConfigDir, itype, stage)
  528. log.Debugf("Found stage %s in %s, target directory : %s", stage, itype, stagedir)
  529. if err = os.MkdirAll(stagedir, os.ModePerm); err != nil {
  530. return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err)
  531. }
  532. /*find items*/
  533. ifiles, err := ioutil.ReadDir(itemDirectory + "/" + stage + "/")
  534. if err != nil {
  535. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err)
  536. }
  537. //finaly copy item
  538. for _, tfile := range ifiles {
  539. log.Infof("Going to restore local/tainted [%s]", tfile.Name())
  540. sourceFile := fmt.Sprintf("%s/%s/%s", itemDirectory, stage, tfile.Name())
  541. destinationFile := fmt.Sprintf("%s%s", stagedir, tfile.Name())
  542. if err = types.CopyFile(sourceFile, destinationFile); err != nil {
  543. return fmt.Errorf("failed copy %s %s to %s : %s", itype, sourceFile, destinationFile, err)
  544. }
  545. log.Infof("restored %s to %s", sourceFile, destinationFile)
  546. }
  547. } else {
  548. log.Infof("Going to restore local/tainted [%s]", file.Name())
  549. sourceFile := fmt.Sprintf("%s/%s", itemDirectory, file.Name())
  550. destinationFile := fmt.Sprintf("%s/%s/%s", csConfig.ConfigPaths.ConfigDir, itype, file.Name())
  551. if err = types.CopyFile(sourceFile, destinationFile); err != nil {
  552. return fmt.Errorf("failed copy %s %s to %s : %s", itype, sourceFile, destinationFile, err)
  553. }
  554. log.Infof("restored %s to %s", sourceFile, destinationFile)
  555. }
  556. }
  557. }
  558. return nil
  559. }
  560. func BackupHub(dirPath string) error {
  561. var err error
  562. var itemDirectory string
  563. var upstreamParsers []string
  564. for _, itemType := range cwhub.ItemTypes {
  565. clog := log.WithFields(log.Fields{
  566. "type": itemType,
  567. })
  568. itemMap := cwhub.GetItemMap(itemType)
  569. if itemMap != nil {
  570. itemDirectory = fmt.Sprintf("%s/%s/", dirPath, itemType)
  571. if err := os.MkdirAll(itemDirectory, os.ModePerm); err != nil {
  572. return fmt.Errorf("error while creating %s : %s", itemDirectory, err)
  573. }
  574. upstreamParsers = []string{}
  575. for k, v := range itemMap {
  576. clog = clog.WithFields(log.Fields{
  577. "file": v.Name,
  578. })
  579. if !v.Installed { //only backup installed ones
  580. clog.Debugf("[%s] : not installed", k)
  581. continue
  582. }
  583. //for the local/tainted ones, we backup the full file
  584. if v.Tainted || v.Local || !v.UpToDate {
  585. //we need to backup stages for parsers
  586. if itemType == cwhub.PARSERS || itemType == cwhub.PARSERS_OVFLW {
  587. fstagedir := fmt.Sprintf("%s%s", itemDirectory, v.Stage)
  588. if err := os.MkdirAll(fstagedir, os.ModePerm); err != nil {
  589. return fmt.Errorf("error while creating stage dir %s : %s", fstagedir, err)
  590. }
  591. }
  592. clog.Debugf("[%s] : backuping file (tainted:%t local:%t up-to-date:%t)", k, v.Tainted, v.Local, v.UpToDate)
  593. tfile := fmt.Sprintf("%s%s/%s", itemDirectory, v.Stage, v.FileName)
  594. if err = types.CopyFile(v.LocalPath, tfile); err != nil {
  595. return fmt.Errorf("failed copy %s %s to %s : %s", itemType, v.LocalPath, tfile, err)
  596. }
  597. clog.Infof("local/tainted saved %s to %s", v.LocalPath, tfile)
  598. continue
  599. }
  600. clog.Debugf("[%s] : from hub, just backup name (up-to-date:%t)", k, v.UpToDate)
  601. clog.Infof("saving, version:%s, up-to-date:%t", v.Version, v.UpToDate)
  602. upstreamParsers = append(upstreamParsers, v.Name)
  603. }
  604. //write the upstream items
  605. upstreamParsersFname := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itemType)
  606. upstreamParsersContent, err := json.MarshalIndent(upstreamParsers, "", " ")
  607. if err != nil {
  608. return fmt.Errorf("failed marshaling upstream parsers : %s", err)
  609. }
  610. err = ioutil.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
  611. if err != nil {
  612. return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
  613. }
  614. clog.Infof("Wrote %d entries for %s to %s", len(upstreamParsers), itemType, upstreamParsersFname)
  615. } else {
  616. clog.Infof("No %s to backup.", itemType)
  617. }
  618. }
  619. return nil
  620. }