utils.go 21 KB

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