utils.go 20 KB

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