utils.go 22 KB

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