2020-11-30 09:37:17 +00:00
|
|
|
package csconfig
|
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
import (
|
2024-03-04 13:22:53 +00:00
|
|
|
"bytes"
|
|
|
|
"errors"
|
2021-03-24 17:16:17 +00:00
|
|
|
"fmt"
|
2024-03-04 13:22:53 +00:00
|
|
|
"io"
|
2021-03-24 17:16:17 +00:00
|
|
|
"path/filepath"
|
|
|
|
|
2024-03-04 13:22:53 +00:00
|
|
|
"gopkg.in/yaml.v3"
|
2023-10-09 09:10:51 +00:00
|
|
|
|
|
|
|
"github.com/crowdsecurity/go-cs-lib/yamlpatch"
|
2021-03-24 17:16:17 +00:00
|
|
|
)
|
|
|
|
|
2020-11-30 09:37:17 +00:00
|
|
|
type SimulationConfig struct {
|
|
|
|
Simulation *bool `yaml:"simulation"`
|
|
|
|
Exclusions []string `yaml:"exclusions,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SimulationConfig) IsSimulated(scenario string) bool {
|
|
|
|
var simulated bool
|
|
|
|
|
|
|
|
if s.Simulation != nil && *s.Simulation {
|
|
|
|
simulated = true
|
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2020-11-30 09:37:17 +00:00
|
|
|
for _, excluded := range s.Exclusions {
|
|
|
|
if excluded == scenario {
|
|
|
|
simulated = !simulated
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2020-11-30 09:37:17 +00:00
|
|
|
return simulated
|
|
|
|
}
|
2021-03-24 17:16:17 +00:00
|
|
|
|
|
|
|
func (c *Config) LoadSimulation() error {
|
|
|
|
simCfg := SimulationConfig{}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
if c.ConfigPaths.SimulationFilePath == "" {
|
|
|
|
c.ConfigPaths.SimulationFilePath = filepath.Clean(c.ConfigPaths.ConfigDir + "/simulation.yaml")
|
|
|
|
}
|
2022-05-18 08:08:37 +00:00
|
|
|
|
|
|
|
patcher := yamlpatch.NewPatcher(c.ConfigPaths.SimulationFilePath, ".local")
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2022-05-18 08:08:37 +00:00
|
|
|
rcfg, err := patcher.MergedPatchContent()
|
2021-03-24 17:16:17 +00:00
|
|
|
if err != nil {
|
2022-05-18 08:08:37 +00:00
|
|
|
return err
|
2022-02-01 21:08:06 +00:00
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
|
|
|
dec := yaml.NewDecoder(bytes.NewReader(rcfg))
|
|
|
|
dec.KnownFields(true)
|
|
|
|
|
|
|
|
if err := dec.Decode(&simCfg); err != nil {
|
|
|
|
if !errors.Is(err, io.EOF) {
|
|
|
|
return fmt.Errorf("while unmarshaling simulation file '%s': %w", c.ConfigPaths.SimulationFilePath, err)
|
|
|
|
}
|
2021-03-24 17:16:17 +00:00
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
if simCfg.Simulation == nil {
|
|
|
|
simCfg.Simulation = new(bool)
|
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
if c.Crowdsec != nil {
|
|
|
|
c.Crowdsec.SimulationConfig = &simCfg
|
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
if c.Cscli != nil {
|
|
|
|
c.Cscli.SimulationConfig = &simCfg
|
|
|
|
}
|
2024-03-04 13:22:53 +00:00
|
|
|
|
2021-03-24 17:16:17 +00:00
|
|
|
return nil
|
|
|
|
}
|