From 1a4ac9d2391c5c53f4038d8fc3cfb2550d126702 Mon Sep 17 00:00:00 2001 From: mmetc <92726601+mmetc@users.noreply.github.com> Date: Fri, 17 May 2024 14:26:10 +0200 Subject: [PATCH] replace log.Fatal with error return (#2996) * log.Fatal -> fmt.Errorf * lint --- pkg/apiserver/papi.go | 10 +++++----- pkg/cache/cache.go | 31 +++++++++++++++++++++---------- pkg/csprofiles/csprofiles.go | 3 ++- pkg/hubtest/hubtest_item.go | 5 +++-- pkg/leakybucket/manager_load.go | 6 +++--- pkg/parser/node.go | 2 +- 6 files changed, 35 insertions(+), 22 deletions(-) diff --git a/pkg/apiserver/papi.go b/pkg/apiserver/papi.go index 8dbd1bb9641..169f1441df4 100644 --- a/pkg/apiserver/papi.go +++ b/pkg/apiserver/papi.go @@ -130,7 +130,7 @@ func (p *Papi) handleEvent(event longpollclient.Event, sync bool) error { message := &Message{} if err := json.Unmarshal([]byte(event.Data), message); err != nil { - return fmt.Errorf("polling papi message format is not compatible: %+v: %s", event.Data, err) + return fmt.Errorf("polling papi message format is not compatible: %+v: %w", event.Data, err) } if message.Header == nil { @@ -161,12 +161,12 @@ func (p *Papi) GetPermissions() (PapiPermCheckSuccess, error) { req, err := http.NewRequest(http.MethodGet, papiCheckUrl, nil) if err != nil { - return PapiPermCheckSuccess{}, fmt.Errorf("failed to create request : %s", err) + return PapiPermCheckSuccess{}, fmt.Errorf("failed to create request: %w", err) } resp, err := httpClient.Do(req) if err != nil { - log.Fatalf("failed to get response : %s", err) + return PapiPermCheckSuccess{}, fmt.Errorf("failed to get response: %w", err) } defer resp.Body.Close() @@ -176,7 +176,7 @@ func (p *Papi) GetPermissions() (PapiPermCheckSuccess, error) { err = json.NewDecoder(resp.Body).Decode(&errResp) if err != nil { - return PapiPermCheckSuccess{}, fmt.Errorf("failed to decode response : %s", err) + return PapiPermCheckSuccess{}, fmt.Errorf("failed to decode response: %w", err) } return PapiPermCheckSuccess{}, fmt.Errorf("unable to query PAPI : %s (%d)", errResp.Error, resp.StatusCode) @@ -186,7 +186,7 @@ func (p *Papi) GetPermissions() (PapiPermCheckSuccess, error) { err = json.NewDecoder(resp.Body).Decode(&respBody) if err != nil { - return PapiPermCheckSuccess{}, fmt.Errorf("failed to decode response : %s", err) + return PapiPermCheckSuccess{}, fmt.Errorf("failed to decode response: %w", err) } return respBody, nil diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 1fd65dc38c3..5b0dcbdc251 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -2,6 +2,7 @@ package cache import ( "errors" + "fmt" "time" "github.com/bluele/gcache" @@ -11,9 +12,11 @@ import ( "github.com/crowdsecurity/crowdsec/pkg/types" ) -var Caches []gcache.Cache -var CacheNames []string -var CacheConfig []CacheCfg +var ( + Caches []gcache.Cache + CacheNames []string + CacheConfig []CacheCfg +) /*prometheus*/ var CacheMetrics = prometheus.NewGaugeVec( @@ -27,6 +30,7 @@ var CacheMetrics = prometheus.NewGaugeVec( // UpdateCacheMetrics is called directly by the prom handler func UpdateCacheMetrics() { CacheMetrics.Reset() + for i, name := range CacheNames { CacheMetrics.With(prometheus.Labels{"name": name, "type": CacheConfig[i].Strategy}).Set(float64(Caches[i].Len(false))) } @@ -42,27 +46,30 @@ type CacheCfg struct { } func CacheInit(cfg CacheCfg) error { - for _, name := range CacheNames { if name == cfg.Name { log.Infof("Cache %s already exists", cfg.Name) } } - //get a default logger + // get a default logger if cfg.LogLevel == nil { cfg.LogLevel = new(log.Level) *cfg.LogLevel = log.InfoLevel } - var clog = log.New() + + clog := log.New() + if err := types.ConfigureLogger(clog); err != nil { - log.Fatalf("While creating cache logger : %s", err) + return fmt.Errorf("while creating cache logger: %w", err) } + clog.SetLevel(*cfg.LogLevel) cfg.Logger = clog.WithFields(log.Fields{ "cache": cfg.Name, }) tmpCache := gcache.New(cfg.Size) + switch cfg.Strategy { case "LRU": tmpCache = tmpCache.LRU() @@ -73,7 +80,6 @@ func CacheInit(cfg CacheCfg) error { default: cfg.Strategy = "LRU" tmpCache = tmpCache.LRU() - } CTICache := tmpCache.Build() @@ -85,18 +91,20 @@ func CacheInit(cfg CacheCfg) error { } func SetKey(cacheName string, key string, value string, expiration *time.Duration) error { - for i, name := range CacheNames { if name == cacheName { if expiration == nil { expiration = &CacheConfig[i].TTL } + CacheConfig[i].Logger.Debugf("Setting key %s to %s with expiration %v", key, value, *expiration) + if err := Caches[i].SetWithExpire(key, value, *expiration); err != nil { CacheConfig[i].Logger.Warningf("While setting key %s in cache %s: %s", key, cacheName, err) } } } + return nil } @@ -104,17 +112,20 @@ func GetKey(cacheName string, key string) (string, error) { for i, name := range CacheNames { if name == cacheName { if value, err := Caches[i].Get(key); err != nil { - //do not warn or log if key not found + // do not warn or log if key not found if errors.Is(err, gcache.KeyNotFoundError) { return "", nil } CacheConfig[i].Logger.Warningf("While getting key %s in cache %s: %s", key, cacheName, err) + return "", err } else { return value.(string), nil } } } + log.Warningf("Cache %s not found", cacheName) + return "", nil } diff --git a/pkg/csprofiles/csprofiles.go b/pkg/csprofiles/csprofiles.go index 95fbb356f3d..42509eaceae 100644 --- a/pkg/csprofiles/csprofiles.go +++ b/pkg/csprofiles/csprofiles.go @@ -35,7 +35,7 @@ func NewProfile(profilesCfg []*csconfig.ProfileCfg) ([]*Runtime, error) { xlog := log.New() if err := types.ConfigureLogger(xlog); err != nil { - log.Fatalf("While creating profiles-specific logger : %s", err) + return nil, fmt.Errorf("while configuring profiles-specific logger: %w", err) } xlog.SetLevel(log.InfoLevel) @@ -196,6 +196,7 @@ func (Profile *Runtime) EvaluateProfile(Alert *models.Alert) ([]*models.Decision decisions = append(decisions, subdecisions...) } else { Profile.Logger.Debugf("Profile %s filter is unsuccessful", Profile.Cfg.Name) + if Profile.Cfg.OnFailure == "break" { break } diff --git a/pkg/hubtest/hubtest_item.go b/pkg/hubtest/hubtest_item.go index 1a2b4863105..918a10f62e1 100644 --- a/pkg/hubtest/hubtest_item.go +++ b/pkg/hubtest/hubtest_item.go @@ -212,7 +212,7 @@ func (t *HubTestItem) InstallHub() error { // load installed hub hub, err := cwhub.NewHub(t.RuntimeHubConfig, nil, false, nil) if err != nil { - log.Fatal(err) + return err } // install data for parsers if needed @@ -327,7 +327,8 @@ func (t *HubTestItem) RunWithNucleiTemplate() error { nucleiConfig := NucleiConfig{ Path: "nuclei", OutputDir: t.RuntimePath, - CmdLineOptions: []string{"-ev", // allow variables from environment + CmdLineOptions: []string{ + "-ev", // allow variables from environment "-nc", // no colors in output "-dresp", // dump response "-j", // json output diff --git a/pkg/leakybucket/manager_load.go b/pkg/leakybucket/manager_load.go index c94291100a4..3e47f1fc16f 100644 --- a/pkg/leakybucket/manager_load.go +++ b/pkg/leakybucket/manager_load.go @@ -308,7 +308,7 @@ func LoadBucket(bucketFactory *BucketFactory, tomb *tomb.Tomb) error { if bucketFactory.Debug { clog := log.New() if err := types.ConfigureLogger(clog); err != nil { - log.Fatalf("While creating bucket-specific logger : %s", err) + return fmt.Errorf("while creating bucket-specific logger: %w", err) } clog.SetLevel(log.DebugLevel) @@ -462,7 +462,7 @@ func LoadBucketsState(file string, buckets *Buckets, bucketFactories []BucketFac val, ok := buckets.Bucket_map.Load(k) if ok { - log.Fatalf("key %s already exists : %+v", k, val) + return fmt.Errorf("key %s already exists: %+v", k, val) } // find back our holder found := false @@ -502,7 +502,7 @@ func LoadBucketsState(file string, buckets *Buckets, bucketFactories []BucketFac } if !found { - log.Fatalf("Unable to find holder for bucket %s : %s", k, spew.Sdump(v)) + return fmt.Errorf("unable to find holder for bucket %s: %s", k, spew.Sdump(v)) } } diff --git a/pkg/parser/node.go b/pkg/parser/node.go index 0906f0b5143..244f361d6b8 100644 --- a/pkg/parser/node.go +++ b/pkg/parser/node.go @@ -447,7 +447,7 @@ func (n *Node) compile(pctx *UnixParserCtx, ectx EnricherCtx) error { if n.Debug { clog := log.New() if err = types.ConfigureLogger(clog); err != nil { - log.Fatalf("While creating bucket-specific logger : %s", err) + return fmt.Errorf("while creating bucket-specific logger: %w", err) } clog.SetLevel(log.DebugLevel)