utils.go 20 KB

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