utils.go 21 KB

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