utils.go 22 KB

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