utils.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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], listAll)
  90. } else {
  91. hubStatus = cwhub.HubStatus(itemType, "", listAll)
  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, forceInstall)
  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, purgeRemove)
  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 == "" && removeAll {
  161. for _, v := range cwhub.GetItemMap(itemType) {
  162. v, err = cwhub.DisableItem(csConfig.Cscli, v, purgeRemove)
  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 != "" && !removeAll {
  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, forceUpgrade)
  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 {
  220. log.Errorf("Didn't find %s", name)
  221. } else if updated == 0 && found {
  222. log.Errorf("Nothing to update")
  223. } else if updated != 0 {
  224. log.Infof("Upgraded %d items", updated)
  225. }
  226. }
  227. func InspectItem(name string, objecitemType string) {
  228. hubItem := cwhub.GetItem(objecitemType, name)
  229. if hubItem == nil {
  230. log.Fatalf("unable to retrieve item.")
  231. }
  232. buff, err := yaml.Marshal(*hubItem)
  233. if err != nil {
  234. log.Fatalf("unable to marshal item : %s", err)
  235. }
  236. fmt.Printf("%s", string(buff))
  237. fmt.Printf("\nCurrent metrics : \n\n")
  238. ShowMetrics(hubItem)
  239. }
  240. func ShowMetrics(hubItem *cwhub.Item) {
  241. switch hubItem.Type {
  242. case cwhub.PARSERS:
  243. metrics := GetParserMetric(prometheusURL, hubItem.Name)
  244. ShowParserMetric(hubItem.Name, metrics)
  245. case cwhub.SCENARIOS:
  246. metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
  247. ShowScenarioMetric(hubItem.Name, metrics)
  248. case cwhub.COLLECTIONS:
  249. for _, item := range hubItem.Parsers {
  250. metrics := GetParserMetric(prometheusURL, item)
  251. ShowParserMetric(item, metrics)
  252. }
  253. for _, item := range hubItem.Scenarios {
  254. metrics := GetScenarioMetric(prometheusURL, item)
  255. ShowScenarioMetric(item, metrics)
  256. }
  257. for _, item := range hubItem.Collections {
  258. hubItem := cwhub.GetItem(cwhub.COLLECTIONS, item)
  259. if hubItem == nil {
  260. log.Fatalf("unable to retrieve item '%s' from collection '%s'", item, hubItem.Name)
  261. }
  262. ShowMetrics(hubItem)
  263. }
  264. default:
  265. log.Errorf("item of type '%s' is unknown", hubItem.Type)
  266. }
  267. }
  268. /*This is a complete rip from prom2json*/
  269. func GetParserMetric(url string, itemName string) map[string]map[string]int {
  270. stats := make(map[string]map[string]int)
  271. result := GetPrometheusMetric(url)
  272. for idx, fam := range result {
  273. if !strings.HasPrefix(fam.Name, "cs_") {
  274. continue
  275. }
  276. log.Tracef("round %d", idx)
  277. for _, m := range fam.Metrics {
  278. metric := m.(prom2json.Metric)
  279. name, ok := metric.Labels["name"]
  280. if !ok {
  281. log.Debugf("no name in Metric %v", metric.Labels)
  282. }
  283. if name != itemName {
  284. continue
  285. }
  286. source, ok := metric.Labels["source"]
  287. if !ok {
  288. log.Debugf("no source in Metric %v", metric.Labels)
  289. }
  290. value := m.(prom2json.Metric).Value
  291. fval, err := strconv.ParseFloat(value, 32)
  292. if err != nil {
  293. log.Errorf("Unexpected int value %s : %s", value, err)
  294. continue
  295. }
  296. ival := int(fval)
  297. switch fam.Name {
  298. case "cs_reader_hits_total":
  299. if _, ok := stats[source]; !ok {
  300. stats[source] = make(map[string]int)
  301. stats[source]["parsed"] = 0
  302. stats[source]["reads"] = 0
  303. stats[source]["unparsed"] = 0
  304. stats[source]["hits"] = 0
  305. }
  306. stats[source]["reads"] += ival
  307. case "cs_parser_hits_ok_total":
  308. if _, ok := stats[source]; !ok {
  309. stats[source] = make(map[string]int)
  310. }
  311. stats[source]["parsed"] += ival
  312. case "cs_parser_hits_ko_total":
  313. if _, ok := stats[source]; !ok {
  314. stats[source] = make(map[string]int)
  315. }
  316. stats[source]["unparsed"] += ival
  317. case "cs_node_hits_total":
  318. if _, ok := stats[source]; !ok {
  319. stats[source] = make(map[string]int)
  320. }
  321. stats[source]["hits"] += ival
  322. case "cs_node_hits_ok_total":
  323. if _, ok := stats[source]; !ok {
  324. stats[source] = make(map[string]int)
  325. }
  326. stats[source]["parsed"] += ival
  327. case "cs_node_hits_ko_total":
  328. if _, ok := stats[source]; !ok {
  329. stats[source] = make(map[string]int)
  330. }
  331. stats[source]["unparsed"] += ival
  332. default:
  333. continue
  334. }
  335. }
  336. }
  337. return stats
  338. }
  339. func GetScenarioMetric(url string, itemName string) map[string]int {
  340. stats := make(map[string]int)
  341. stats["instanciation"] = 0
  342. stats["curr_count"] = 0
  343. stats["overflow"] = 0
  344. stats["pour"] = 0
  345. stats["underflow"] = 0
  346. result := GetPrometheusMetric(url)
  347. for idx, fam := range result {
  348. if !strings.HasPrefix(fam.Name, "cs_") {
  349. continue
  350. }
  351. log.Tracef("round %d", idx)
  352. for _, m := range fam.Metrics {
  353. metric := m.(prom2json.Metric)
  354. name, ok := metric.Labels["name"]
  355. if !ok {
  356. log.Debugf("no name in Metric %v", metric.Labels)
  357. }
  358. if name != itemName {
  359. continue
  360. }
  361. value := m.(prom2json.Metric).Value
  362. fval, err := strconv.ParseFloat(value, 32)
  363. if err != nil {
  364. log.Errorf("Unexpected int value %s : %s", value, err)
  365. continue
  366. }
  367. ival := int(fval)
  368. switch fam.Name {
  369. case "cs_bucket_created_total":
  370. stats["instanciation"] += ival
  371. case "cs_buckets":
  372. stats["curr_count"] += ival
  373. case "cs_bucket_overflowed_total":
  374. stats["overflow"] += ival
  375. case "cs_bucket_poured_total":
  376. stats["pour"] += ival
  377. case "cs_bucket_underflowed_total":
  378. stats["underflow"] += ival
  379. default:
  380. continue
  381. }
  382. }
  383. }
  384. return stats
  385. }
  386. func GetPrometheusMetric(url string) []*prom2json.Family {
  387. mfChan := make(chan *dto.MetricFamily, 1024)
  388. // Start with the DefaultTransport for sane defaults.
  389. transport := http.DefaultTransport.(*http.Transport).Clone()
  390. // Conservatively disable HTTP keep-alives as this program will only
  391. // ever need a single HTTP request.
  392. transport.DisableKeepAlives = true
  393. // Timeout early if the server doesn't even return the headers.
  394. transport.ResponseHeaderTimeout = time.Minute
  395. go func() {
  396. defer types.CatchPanic("crowdsec/GetPrometheusMetric")
  397. err := prom2json.FetchMetricFamilies(url, mfChan, transport)
  398. if err != nil {
  399. log.Fatalf("failed to fetch prometheus metrics : %v", err)
  400. }
  401. }()
  402. result := []*prom2json.Family{}
  403. for mf := range mfChan {
  404. result = append(result, prom2json.NewFamily(mf))
  405. }
  406. log.Debugf("Finished reading prometheus output, %d entries", len(result))
  407. return result
  408. }
  409. func ShowScenarioMetric(itemName string, metrics map[string]int) {
  410. if metrics["instanciation"] == 0 {
  411. return
  412. }
  413. table := tablewriter.NewWriter(os.Stdout)
  414. table.SetHeader([]string{"Current Count", "Overflows", "Instanciated", "Poured", "Expired"})
  415. 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"])})
  416. fmt.Printf(" - (Scenario) %s: \n", itemName)
  417. table.Render()
  418. fmt.Println()
  419. }
  420. func ShowParserMetric(itemName string, metrics map[string]map[string]int) {
  421. skip := true
  422. table := tablewriter.NewWriter(os.Stdout)
  423. table.SetHeader([]string{"Parsers", "Hits", "Parsed", "Unparsed"})
  424. for source, stats := range metrics {
  425. if stats["hits"] > 0 {
  426. table.Append([]string{source, fmt.Sprintf("%d", stats["hits"]), fmt.Sprintf("%d", stats["parsed"]), fmt.Sprintf("%d", stats["unparsed"])})
  427. skip = false
  428. }
  429. }
  430. if !skip {
  431. fmt.Printf(" - (Parser) %s: \n", itemName)
  432. table.Render()
  433. fmt.Println()
  434. }
  435. }
  436. //it's a rip of the cli version, but in silent-mode
  437. func silenceInstallItem(name string, obtype string) (string, error) {
  438. var item *cwhub.Item
  439. item = cwhub.GetItem(obtype, name)
  440. if item == nil {
  441. return "", fmt.Errorf("error retrieving item")
  442. }
  443. it := *item
  444. if downloadOnly && it.Downloaded && it.UpToDate {
  445. return fmt.Sprintf("%s is already downloaded and up-to-date", it.Name), nil
  446. }
  447. it, err := cwhub.DownloadLatest(csConfig.Cscli, it, forceInstall)
  448. if err != nil {
  449. return "", fmt.Errorf("error while downloading %s : %v", it.Name, err)
  450. }
  451. if err := cwhub.AddItem(obtype, it); err != nil {
  452. return "", err
  453. }
  454. if downloadOnly {
  455. return fmt.Sprintf("Downloaded %s to %s", it.Name, csConfig.Cscli.HubDir+"/"+it.RemotePath), nil
  456. }
  457. it, err = cwhub.EnableItem(csConfig.Cscli, it)
  458. if err != nil {
  459. return "", fmt.Errorf("error while enabled %s : %v", it.Name, err)
  460. }
  461. if err := cwhub.AddItem(obtype, it); err != nil {
  462. return "", err
  463. }
  464. return fmt.Sprintf("Enabled %s", it.Name), nil
  465. }
  466. func RestoreHub(dirPath string) error {
  467. var err error
  468. for _, itype := range cwhub.ItemTypes {
  469. itemDirectory := fmt.Sprintf("%s/%s/", dirPath, itype)
  470. if _, err = os.Stat(itemDirectory); err != nil {
  471. log.Infof("no %s in backup", itype)
  472. continue
  473. }
  474. /*restore the upstream items*/
  475. upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
  476. file, err := ioutil.ReadFile(upstreamListFN)
  477. if err != nil {
  478. return fmt.Errorf("error while opening %s : %s", upstreamListFN, err)
  479. }
  480. var upstreamList []string
  481. err = json.Unmarshal([]byte(file), &upstreamList)
  482. if err != nil {
  483. return fmt.Errorf("error unmarshaling %s : %s", upstreamListFN, err)
  484. }
  485. for _, toinstall := range upstreamList {
  486. label, err := silenceInstallItem(toinstall, itype)
  487. if err != nil {
  488. log.Errorf("Error while installing %s : %s", toinstall, err)
  489. } else if label != "" {
  490. log.Infof("Installed %s : %s", toinstall, label)
  491. } else {
  492. log.Printf("Installed %s : ok", toinstall)
  493. }
  494. }
  495. /*restore the local and tainted items*/
  496. files, err := ioutil.ReadDir(itemDirectory)
  497. if err != nil {
  498. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err)
  499. }
  500. for _, file := range files {
  501. //dir are stages, keep track
  502. if !file.IsDir() {
  503. continue
  504. }
  505. stage := file.Name()
  506. stagedir := fmt.Sprintf("%s/%s/%s/", csConfig.ConfigPaths.ConfigDir, itype, stage)
  507. log.Debugf("Found stage %s in %s, target directory : %s", stage, itype, stagedir)
  508. if err = os.MkdirAll(stagedir, os.ModePerm); err != nil {
  509. return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err)
  510. }
  511. /*find items*/
  512. ifiles, err := ioutil.ReadDir(itemDirectory + "/" + stage + "/")
  513. if err != nil {
  514. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err)
  515. }
  516. //finaly copy item
  517. for _, tfile := range ifiles {
  518. log.Infof("Going to restore local/tainted [%s]", tfile.Name())
  519. sourceFile := fmt.Sprintf("%s/%s/%s", itemDirectory, stage, tfile.Name())
  520. destinationFile := fmt.Sprintf("%s%s", stagedir, tfile.Name())
  521. if err = types.CopyFile(sourceFile, destinationFile); err != nil {
  522. return fmt.Errorf("failed copy %s %s to %s : %s", itype, sourceFile, destinationFile, err)
  523. }
  524. log.Infof("restored %s to %s", sourceFile, destinationFile)
  525. }
  526. }
  527. }
  528. return nil
  529. }
  530. func BackupHub(dirPath string) error {
  531. var err error
  532. var itemDirectory string
  533. var upstreamParsers []string
  534. for _, itemType := range cwhub.ItemTypes {
  535. clog := log.WithFields(log.Fields{
  536. "type": itemType,
  537. })
  538. itemMap := cwhub.GetItemMap(itemType)
  539. if itemMap != nil {
  540. itemDirectory = fmt.Sprintf("%s/%s/", dirPath, itemType)
  541. if err := os.MkdirAll(itemDirectory, os.ModePerm); err != nil {
  542. return fmt.Errorf("error while creating %s : %s", itemDirectory, err)
  543. }
  544. upstreamParsers = []string{}
  545. for k, v := range itemMap {
  546. clog = clog.WithFields(log.Fields{
  547. "file": v.Name,
  548. })
  549. if !v.Installed { //only backup installed ones
  550. clog.Debugf("[%s] : not installed", k)
  551. continue
  552. }
  553. //for the local/tainted ones, we backup the full file
  554. if v.Tainted || v.Local || !v.UpToDate {
  555. //we need to backup stages for parsers
  556. if itemType == cwhub.PARSERS || itemType == cwhub.PARSERS_OVFLW {
  557. fstagedir := fmt.Sprintf("%s%s", itemDirectory, v.Stage)
  558. if err := os.MkdirAll(fstagedir, os.ModePerm); err != nil {
  559. return fmt.Errorf("error while creating stage dir %s : %s", fstagedir, err)
  560. }
  561. }
  562. clog.Debugf("[%s] : backuping file (tainted:%t local:%t up-to-date:%t)", k, v.Tainted, v.Local, v.UpToDate)
  563. tfile := fmt.Sprintf("%s%s%s", itemDirectory, v.Stage, v.FileName)
  564. if err = types.CopyFile(v.LocalPath, tfile); err != nil {
  565. return fmt.Errorf("failed copy %s %s to %s : %s", itemType, v.LocalPath, tfile, err)
  566. }
  567. clog.Infof("local/tainted saved %s to %s", v.LocalPath, tfile)
  568. continue
  569. }
  570. clog.Debugf("[%s] : from hub, just backup name (up-to-date:%t)", k, v.UpToDate)
  571. clog.Infof("saving, version:%s, up-to-date:%t", v.Version, v.UpToDate)
  572. upstreamParsers = append(upstreamParsers, v.Name)
  573. }
  574. //write the upstream items
  575. upstreamParsersFname := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itemType)
  576. upstreamParsersContent, err := json.MarshalIndent(upstreamParsers, "", " ")
  577. if err != nil {
  578. return fmt.Errorf("failed marshaling upstream parsers : %s", err)
  579. }
  580. err = ioutil.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
  581. if err != nil {
  582. return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
  583. }
  584. clog.Infof("Wrote %d entries for %s to %s", len(upstreamParsers), itemType, upstreamParsersFname)
  585. } else {
  586. clog.Infof("No %s to backup.", itemType)
  587. }
  588. }
  589. return nil
  590. }