utils.go 21 KB

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