simulation.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package csconfig
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "gopkg.in/yaml.v2"
  6. "github.com/crowdsecurity/go-cs-lib/yamlpatch"
  7. )
  8. type SimulationConfig struct {
  9. Simulation *bool `yaml:"simulation"`
  10. Exclusions []string `yaml:"exclusions,omitempty"`
  11. }
  12. func (s *SimulationConfig) IsSimulated(scenario string) bool {
  13. var simulated bool
  14. if s.Simulation != nil && *s.Simulation {
  15. simulated = true
  16. }
  17. for _, excluded := range s.Exclusions {
  18. if excluded == scenario {
  19. simulated = !simulated
  20. break
  21. }
  22. }
  23. return simulated
  24. }
  25. func (c *Config) LoadSimulation() error {
  26. if err := c.LoadConfigurationPaths(); err != nil {
  27. return err
  28. }
  29. simCfg := SimulationConfig{}
  30. if c.ConfigPaths.SimulationFilePath == "" {
  31. c.ConfigPaths.SimulationFilePath = filepath.Clean(c.ConfigPaths.ConfigDir + "/simulation.yaml")
  32. }
  33. patcher := yamlpatch.NewPatcher(c.ConfigPaths.SimulationFilePath, ".local")
  34. rcfg, err := patcher.MergedPatchContent()
  35. if err != nil {
  36. return err
  37. }
  38. if err := yaml.UnmarshalStrict(rcfg, &simCfg); err != nil {
  39. return fmt.Errorf("while unmarshaling simulation file '%s' : %s", c.ConfigPaths.SimulationFilePath, err)
  40. }
  41. if simCfg.Simulation == nil {
  42. simCfg.Simulation = new(bool)
  43. }
  44. if c.Crowdsec != nil {
  45. c.Crowdsec.SimulationConfig = &simCfg
  46. }
  47. if c.Cscli != nil {
  48. c.Cscli.SimulationConfig = &simCfg
  49. }
  50. return nil
  51. }