utils.go 22 KB

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