github.com/crowdsecurity/crowdsec@v1.6.1/pkg/csconfig/simulation.go (about)

     1  package csconfig
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"fmt"
     7  	"io"
     8  	"path/filepath"
     9  
    10  	"gopkg.in/yaml.v3"
    11  
    12  	"github.com/crowdsecurity/go-cs-lib/yamlpatch"
    13  )
    14  
    15  type SimulationConfig struct {
    16  	Simulation *bool    `yaml:"simulation"`
    17  	Exclusions []string `yaml:"exclusions,omitempty"`
    18  }
    19  
    20  func (s *SimulationConfig) IsSimulated(scenario string) bool {
    21  	var simulated bool
    22  
    23  	if s.Simulation != nil && *s.Simulation {
    24  		simulated = true
    25  	}
    26  
    27  	for _, excluded := range s.Exclusions {
    28  		if excluded == scenario {
    29  			simulated = !simulated
    30  			break
    31  		}
    32  	}
    33  
    34  	return simulated
    35  }
    36  
    37  func (c *Config) LoadSimulation() error {
    38  	simCfg := SimulationConfig{}
    39  
    40  	if c.ConfigPaths.SimulationFilePath == "" {
    41  		c.ConfigPaths.SimulationFilePath = filepath.Clean(c.ConfigPaths.ConfigDir + "/simulation.yaml")
    42  	}
    43  
    44  	patcher := yamlpatch.NewPatcher(c.ConfigPaths.SimulationFilePath, ".local")
    45  
    46  	rcfg, err := patcher.MergedPatchContent()
    47  	if err != nil {
    48  		return err
    49  	}
    50  
    51  	dec := yaml.NewDecoder(bytes.NewReader(rcfg))
    52  	dec.KnownFields(true)
    53  
    54  	if err := dec.Decode(&simCfg); err != nil {
    55  		if !errors.Is(err, io.EOF) {
    56  			return fmt.Errorf("while unmarshaling simulation file '%s': %w", c.ConfigPaths.SimulationFilePath, err)
    57  		}
    58  	}
    59  
    60  	if simCfg.Simulation == nil {
    61  		simCfg.Simulation = new(bool)
    62  	}
    63  
    64  	if c.Crowdsec != nil {
    65  		c.Crowdsec.SimulationConfig = &simCfg
    66  	}
    67  
    68  	if c.Cscli != nil {
    69  		c.Cscli.SimulationConfig = &simCfg
    70  	}
    71  
    72  	return nil
    73  }