utils.go 21 KB

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