utils.go 20 KB

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