utils.go 21 KB

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