utils.go 20 KB

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