Skip to content

Commit

Permalink
replace log.Fatal with error return (#2996)
Browse files Browse the repository at this point in the history
* log.Fatal -> fmt.Errorf

* lint
  • Loading branch information
mmetc authored May 17, 2024
1 parent 0ba05ac commit 1a4ac9d
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 22 deletions.
10 changes: 5 additions & 5 deletions pkg/apiserver/papi.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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
Expand Down
31 changes: 21 additions & 10 deletions pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cache

import (
"errors"
"fmt"
"time"

"github.com/bluele/gcache"
Expand All @@ -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(
Expand All @@ -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)))
}
Expand All @@ -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()
Expand All @@ -73,7 +80,6 @@ func CacheInit(cfg CacheCfg) error {
default:
cfg.Strategy = "LRU"
tmpCache = tmpCache.LRU()

}

CTICache := tmpCache.Build()
Expand All @@ -85,36 +91,41 @@ 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
}

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
}
3 changes: 2 additions & 1 deletion pkg/csprofiles/csprofiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/hubtest/hubtest_item.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions pkg/leakybucket/manager_load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/parser/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 1a4ac9d

Please sign in to comment.