utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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. "github.com/fatih/color"
  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 prometheusURL == "" {
  231. //This is technically wrong to do this, as the prometheus section contains a listen address, not an URL to query prometheus
  232. //But for ease of use, we will use the listen address as the prometheus URL because it will be 127.0.0.1 in the default case
  233. listenAddr := csConfig.Prometheus.ListenAddr
  234. if listenAddr == "" {
  235. listenAddr = "127.0.0.1"
  236. }
  237. listenPort := csConfig.Prometheus.ListenPort
  238. if listenPort == 0 {
  239. listenPort = 6060
  240. }
  241. prometheusURL = fmt.Sprintf("http://%s:%d/metrics", listenAddr, listenPort)
  242. log.Debugf("No prometheus URL provided using: %s", prometheusURL)
  243. }
  244. fmt.Printf("\nCurrent metrics : \n")
  245. ShowMetrics(hubItem)
  246. }
  247. func manageCliDecisionAlerts(ip *string, ipRange *string, scope *string, value *string) error {
  248. /*if a range is provided, change the scope*/
  249. if *ipRange != "" {
  250. _, _, err := net.ParseCIDR(*ipRange)
  251. if err != nil {
  252. return fmt.Errorf("%s isn't a valid range", *ipRange)
  253. }
  254. }
  255. if *ip != "" {
  256. ipRepr := net.ParseIP(*ip)
  257. if ipRepr == nil {
  258. return fmt.Errorf("%s isn't a valid ip", *ip)
  259. }
  260. }
  261. //avoid confusion on scope (ip vs Ip and range vs Range)
  262. switch strings.ToLower(*scope) {
  263. case "ip":
  264. *scope = types.Ip
  265. case "range":
  266. *scope = types.Range
  267. case "country":
  268. *scope = types.Country
  269. case "as":
  270. *scope = types.AS
  271. }
  272. return nil
  273. }
  274. func ShowMetrics(hubItem *cwhub.Item) {
  275. switch hubItem.Type {
  276. case cwhub.PARSERS:
  277. metrics := GetParserMetric(prometheusURL, hubItem.Name)
  278. parserMetricsTable(color.Output, hubItem.Name, metrics)
  279. case cwhub.SCENARIOS:
  280. metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
  281. scenarioMetricsTable(color.Output, hubItem.Name, metrics)
  282. case cwhub.COLLECTIONS:
  283. for _, item := range hubItem.Parsers {
  284. metrics := GetParserMetric(prometheusURL, item)
  285. parserMetricsTable(color.Output, item, metrics)
  286. }
  287. for _, item := range hubItem.Scenarios {
  288. metrics := GetScenarioMetric(prometheusURL, item)
  289. scenarioMetricsTable(color.Output, item, metrics)
  290. }
  291. for _, item := range hubItem.Collections {
  292. hubItem = cwhub.GetItem(cwhub.COLLECTIONS, item)
  293. if hubItem == nil {
  294. log.Fatalf("unable to retrieve item '%s' from collection '%s'", item, hubItem.Name)
  295. }
  296. ShowMetrics(hubItem)
  297. }
  298. default:
  299. log.Errorf("item of type '%s' is unknown", hubItem.Type)
  300. }
  301. }
  302. // GetParserMetric is a complete rip from prom2json
  303. func GetParserMetric(url string, itemName string) map[string]map[string]int {
  304. stats := make(map[string]map[string]int)
  305. result := GetPrometheusMetric(url)
  306. for idx, fam := range result {
  307. if !strings.HasPrefix(fam.Name, "cs_") {
  308. continue
  309. }
  310. log.Tracef("round %d", idx)
  311. for _, m := range fam.Metrics {
  312. metric, ok := m.(prom2json.Metric)
  313. if !ok {
  314. log.Debugf("failed to convert metric to prom2json.Metric")
  315. continue
  316. }
  317. name, ok := metric.Labels["name"]
  318. if !ok {
  319. log.Debugf("no name in Metric %v", metric.Labels)
  320. }
  321. if name != itemName {
  322. continue
  323. }
  324. source, ok := metric.Labels["source"]
  325. if !ok {
  326. log.Debugf("no source in Metric %v", metric.Labels)
  327. } else {
  328. if srctype, ok := metric.Labels["type"]; ok {
  329. source = srctype + ":" + source
  330. }
  331. }
  332. value := m.(prom2json.Metric).Value
  333. fval, err := strconv.ParseFloat(value, 32)
  334. if err != nil {
  335. log.Errorf("Unexpected int value %s : %s", value, err)
  336. continue
  337. }
  338. ival := int(fval)
  339. switch fam.Name {
  340. case "cs_reader_hits_total":
  341. if _, ok := stats[source]; !ok {
  342. stats[source] = make(map[string]int)
  343. stats[source]["parsed"] = 0
  344. stats[source]["reads"] = 0
  345. stats[source]["unparsed"] = 0
  346. stats[source]["hits"] = 0
  347. }
  348. stats[source]["reads"] += ival
  349. case "cs_parser_hits_ok_total":
  350. if _, ok := stats[source]; !ok {
  351. stats[source] = make(map[string]int)
  352. }
  353. stats[source]["parsed"] += ival
  354. case "cs_parser_hits_ko_total":
  355. if _, ok := stats[source]; !ok {
  356. stats[source] = make(map[string]int)
  357. }
  358. stats[source]["unparsed"] += ival
  359. case "cs_node_hits_total":
  360. if _, ok := stats[source]; !ok {
  361. stats[source] = make(map[string]int)
  362. }
  363. stats[source]["hits"] += ival
  364. case "cs_node_hits_ok_total":
  365. if _, ok := stats[source]; !ok {
  366. stats[source] = make(map[string]int)
  367. }
  368. stats[source]["parsed"] += ival
  369. case "cs_node_hits_ko_total":
  370. if _, ok := stats[source]; !ok {
  371. stats[source] = make(map[string]int)
  372. }
  373. stats[source]["unparsed"] += ival
  374. default:
  375. continue
  376. }
  377. }
  378. }
  379. return stats
  380. }
  381. func GetScenarioMetric(url string, itemName string) map[string]int {
  382. stats := make(map[string]int)
  383. stats["instantiation"] = 0
  384. stats["curr_count"] = 0
  385. stats["overflow"] = 0
  386. stats["pour"] = 0
  387. stats["underflow"] = 0
  388. result := GetPrometheusMetric(url)
  389. for idx, fam := range result {
  390. if !strings.HasPrefix(fam.Name, "cs_") {
  391. continue
  392. }
  393. log.Tracef("round %d", idx)
  394. for _, m := range fam.Metrics {
  395. metric, ok := m.(prom2json.Metric)
  396. if !ok {
  397. log.Debugf("failed to convert metric to prom2json.Metric")
  398. continue
  399. }
  400. name, ok := metric.Labels["name"]
  401. if !ok {
  402. log.Debugf("no name in Metric %v", metric.Labels)
  403. }
  404. if name != itemName {
  405. continue
  406. }
  407. value := m.(prom2json.Metric).Value
  408. fval, err := strconv.ParseFloat(value, 32)
  409. if err != nil {
  410. log.Errorf("Unexpected int value %s : %s", value, err)
  411. continue
  412. }
  413. ival := int(fval)
  414. switch fam.Name {
  415. case "cs_bucket_created_total":
  416. stats["instantiation"] += ival
  417. case "cs_buckets":
  418. stats["curr_count"] += ival
  419. case "cs_bucket_overflowed_total":
  420. stats["overflow"] += ival
  421. case "cs_bucket_poured_total":
  422. stats["pour"] += ival
  423. case "cs_bucket_underflowed_total":
  424. stats["underflow"] += ival
  425. default:
  426. continue
  427. }
  428. }
  429. }
  430. return stats
  431. }
  432. // it's a rip of the cli version, but in silent-mode
  433. func silenceInstallItem(name string, obtype string) (string, error) {
  434. var item = cwhub.GetItem(obtype, name)
  435. if item == nil {
  436. return "", fmt.Errorf("error retrieving item")
  437. }
  438. it := *item
  439. if downloadOnly && it.Downloaded && it.UpToDate {
  440. return fmt.Sprintf("%s is already downloaded and up-to-date", it.Name), nil
  441. }
  442. it, err := cwhub.DownloadLatest(csConfig.Hub, it, forceAction, false)
  443. if err != nil {
  444. return "", fmt.Errorf("error while downloading %s : %v", it.Name, err)
  445. }
  446. if err := cwhub.AddItem(obtype, it); err != nil {
  447. return "", err
  448. }
  449. if downloadOnly {
  450. return fmt.Sprintf("Downloaded %s to %s", it.Name, csConfig.Cscli.HubDir+"/"+it.RemotePath), nil
  451. }
  452. it, err = cwhub.EnableItem(csConfig.Hub, it)
  453. if err != nil {
  454. return "", fmt.Errorf("error while enabling %s : %v", it.Name, err)
  455. }
  456. if err := cwhub.AddItem(obtype, it); err != nil {
  457. return "", err
  458. }
  459. return fmt.Sprintf("Enabled %s", it.Name), nil
  460. }
  461. func GetPrometheusMetric(url string) []*prom2json.Family {
  462. mfChan := make(chan *dto.MetricFamily, 1024)
  463. // Start with the DefaultTransport for sane defaults.
  464. transport := http.DefaultTransport.(*http.Transport).Clone()
  465. // Conservatively disable HTTP keep-alives as this program will only
  466. // ever need a single HTTP request.
  467. transport.DisableKeepAlives = true
  468. // Timeout early if the server doesn't even return the headers.
  469. transport.ResponseHeaderTimeout = time.Minute
  470. go func() {
  471. defer types.CatchPanic("crowdsec/GetPrometheusMetric")
  472. err := prom2json.FetchMetricFamilies(url, mfChan, transport)
  473. if err != nil {
  474. log.Fatalf("failed to fetch prometheus metrics : %v", err)
  475. }
  476. }()
  477. result := []*prom2json.Family{}
  478. for mf := range mfChan {
  479. result = append(result, prom2json.NewFamily(mf))
  480. }
  481. log.Debugf("Finished reading prometheus output, %d entries", len(result))
  482. return result
  483. }
  484. func RestoreHub(dirPath string) error {
  485. var err error
  486. if err := csConfig.LoadHub(); err != nil {
  487. return err
  488. }
  489. if err := cwhub.SetHubBranch(); err != nil {
  490. return fmt.Errorf("error while setting hub branch: %s", err)
  491. }
  492. for _, itype := range cwhub.ItemTypes {
  493. itemDirectory := fmt.Sprintf("%s/%s/", dirPath, itype)
  494. if _, err = os.Stat(itemDirectory); err != nil {
  495. log.Infof("no %s in backup", itype)
  496. continue
  497. }
  498. /*restore the upstream items*/
  499. upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
  500. file, err := os.ReadFile(upstreamListFN)
  501. if err != nil {
  502. return fmt.Errorf("error while opening %s : %s", upstreamListFN, err)
  503. }
  504. var upstreamList []string
  505. err = json.Unmarshal(file, &upstreamList)
  506. if err != nil {
  507. return fmt.Errorf("error unmarshaling %s : %s", upstreamListFN, err)
  508. }
  509. for _, toinstall := range upstreamList {
  510. label, err := silenceInstallItem(toinstall, itype)
  511. if err != nil {
  512. log.Errorf("Error while installing %s : %s", toinstall, err)
  513. } else if label != "" {
  514. log.Infof("Installed %s : %s", toinstall, label)
  515. } else {
  516. log.Printf("Installed %s : ok", toinstall)
  517. }
  518. }
  519. /*restore the local and tainted items*/
  520. files, err := os.ReadDir(itemDirectory)
  521. if err != nil {
  522. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err)
  523. }
  524. for _, file := range files {
  525. //this was the upstream data
  526. if file.Name() == fmt.Sprintf("upstream-%s.json", itype) {
  527. continue
  528. }
  529. if itype == cwhub.PARSERS || itype == cwhub.PARSERS_OVFLW {
  530. //we expect a stage here
  531. if !file.IsDir() {
  532. continue
  533. }
  534. stage := file.Name()
  535. stagedir := fmt.Sprintf("%s/%s/%s/", csConfig.ConfigPaths.ConfigDir, itype, stage)
  536. log.Debugf("Found stage %s in %s, target directory : %s", stage, itype, stagedir)
  537. if err = os.MkdirAll(stagedir, os.ModePerm); err != nil {
  538. return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err)
  539. }
  540. /*find items*/
  541. ifiles, err := os.ReadDir(itemDirectory + "/" + stage + "/")
  542. if err != nil {
  543. return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err)
  544. }
  545. //finally copy item
  546. for _, tfile := range ifiles {
  547. log.Infof("Going to restore local/tainted [%s]", tfile.Name())
  548. sourceFile := fmt.Sprintf("%s/%s/%s", itemDirectory, stage, tfile.Name())
  549. destinationFile := fmt.Sprintf("%s%s", stagedir, tfile.Name())
  550. if err = types.CopyFile(sourceFile, destinationFile); err != nil {
  551. return fmt.Errorf("failed copy %s %s to %s : %s", itype, sourceFile, destinationFile, err)
  552. }
  553. log.Infof("restored %s to %s", sourceFile, destinationFile)
  554. }
  555. } else {
  556. log.Infof("Going to restore local/tainted [%s]", file.Name())
  557. sourceFile := fmt.Sprintf("%s/%s", itemDirectory, file.Name())
  558. destinationFile := fmt.Sprintf("%s/%s/%s", csConfig.ConfigPaths.ConfigDir, itype, file.Name())
  559. if err = types.CopyFile(sourceFile, destinationFile); err != nil {
  560. return fmt.Errorf("failed copy %s %s to %s : %s", itype, sourceFile, destinationFile, err)
  561. }
  562. log.Infof("restored %s to %s", sourceFile, destinationFile)
  563. }
  564. }
  565. }
  566. return nil
  567. }
  568. func BackupHub(dirPath string) error {
  569. var err error
  570. var itemDirectory string
  571. var upstreamParsers []string
  572. for _, itemType := range cwhub.ItemTypes {
  573. clog := log.WithFields(log.Fields{
  574. "type": itemType,
  575. })
  576. itemMap := cwhub.GetItemMap(itemType)
  577. if itemMap == nil {
  578. clog.Infof("No %s to backup.", itemType)
  579. continue
  580. }
  581. itemDirectory = fmt.Sprintf("%s/%s/", dirPath, itemType)
  582. if err := os.MkdirAll(itemDirectory, os.ModePerm); err != nil {
  583. return fmt.Errorf("error while creating %s : %s", itemDirectory, err)
  584. }
  585. upstreamParsers = []string{}
  586. for k, v := range itemMap {
  587. clog = clog.WithFields(log.Fields{
  588. "file": v.Name,
  589. })
  590. if !v.Installed { //only backup installed ones
  591. clog.Debugf("[%s] : not installed", k)
  592. continue
  593. }
  594. //for the local/tainted ones, we backup the full file
  595. if v.Tainted || v.Local || !v.UpToDate {
  596. //we need to backup stages for parsers
  597. if itemType == cwhub.PARSERS || itemType == cwhub.PARSERS_OVFLW {
  598. fstagedir := fmt.Sprintf("%s%s", itemDirectory, v.Stage)
  599. if err := os.MkdirAll(fstagedir, os.ModePerm); err != nil {
  600. return fmt.Errorf("error while creating stage dir %s : %s", fstagedir, err)
  601. }
  602. }
  603. clog.Debugf("[%s] : backuping file (tainted:%t local:%t up-to-date:%t)", k, v.Tainted, v.Local, v.UpToDate)
  604. tfile := fmt.Sprintf("%s%s/%s", itemDirectory, v.Stage, v.FileName)
  605. if err = types.CopyFile(v.LocalPath, tfile); err != nil {
  606. return fmt.Errorf("failed copy %s %s to %s : %s", itemType, v.LocalPath, tfile, err)
  607. }
  608. clog.Infof("local/tainted saved %s to %s", v.LocalPath, tfile)
  609. continue
  610. }
  611. clog.Debugf("[%s] : from hub, just backup name (up-to-date:%t)", k, v.UpToDate)
  612. clog.Infof("saving, version:%s, up-to-date:%t", v.Version, v.UpToDate)
  613. upstreamParsers = append(upstreamParsers, v.Name)
  614. }
  615. //write the upstream items
  616. upstreamParsersFname := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itemType)
  617. upstreamParsersContent, err := json.MarshalIndent(upstreamParsers, "", " ")
  618. if err != nil {
  619. return fmt.Errorf("failed marshaling upstream parsers : %s", err)
  620. }
  621. err = os.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
  622. if err != nil {
  623. return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
  624. }
  625. clog.Infof("Wrote %d entries for %s to %s", len(upstreamParsers), itemType, upstreamParsersFname)
  626. }
  627. return nil
  628. }
  629. type unit struct {
  630. value int64
  631. symbol string
  632. }
  633. var ranges = []unit{
  634. {
  635. value: 1e18,
  636. symbol: "E",
  637. },
  638. {
  639. value: 1e15,
  640. symbol: "P",
  641. },
  642. {
  643. value: 1e12,
  644. symbol: "T",
  645. },
  646. {
  647. value: 1e6,
  648. symbol: "M",
  649. },
  650. {
  651. value: 1e3,
  652. symbol: "k",
  653. },
  654. {
  655. value: 1,
  656. symbol: "",
  657. },
  658. }
  659. func formatNumber(num int) string {
  660. goodUnit := unit{}
  661. for _, u := range ranges {
  662. if int64(num) >= u.value {
  663. goodUnit = u
  664. break
  665. }
  666. }
  667. if goodUnit.value == 1 {
  668. return fmt.Sprintf("%d%s", num, goodUnit.symbol)
  669. }
  670. res := math.Round(float64(num)/float64(goodUnit.value)*100) / 100
  671. return fmt.Sprintf("%.2f%s", res, goodUnit.symbol)
  672. }