From bd41f855cfa8cb22d782e29ef57b5a7cf7feaf86 Mon Sep 17 00:00:00 2001 From: mmetc <92726601+mmetc@users.noreply.github.com> Date: Thu, 29 Jun 2023 11:34:59 +0200 Subject: [PATCH] errors.Wrap -> fmt.Errorf (#2317) --- .../modules/cloudwatch/cloudwatch.go | 16 +++++------ pkg/acquisition/modules/docker/docker.go | 7 ++--- pkg/acquisition/modules/file/file.go | 22 +++++++-------- pkg/acquisition/modules/file/file_test.go | 4 +-- .../modules/journalctl/journalctl.go | 3 +- pkg/acquisition/modules/kafka/kafka.go | 11 ++++---- .../modules/kubernetesaudit/k8s_audit.go | 14 +++++----- pkg/cwhub/cwhub.go | 13 +++++---- pkg/cwhub/helpers.go | 14 +++++----- pkg/hubtest/hubtest.go | 3 +- pkg/hubtest/parser_assert.go | 8 +++--- pkg/hubtest/scenario_assert.go | 10 +++---- pkg/metabase/database.go | 5 ++-- pkg/metabase/metabase.go | 28 +++++++++---------- pkg/types/ip.go | 13 +++++---- 15 files changed, 83 insertions(+), 88 deletions(-) diff --git a/pkg/acquisition/modules/cloudwatch/cloudwatch.go b/pkg/acquisition/modules/cloudwatch/cloudwatch.go index 1abf04c5b35..48bbe421753 100644 --- a/pkg/acquisition/modules/cloudwatch/cloudwatch.go +++ b/pkg/acquisition/modules/cloudwatch/cloudwatch.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "gopkg.in/tomb.v2" @@ -201,7 +200,7 @@ func (cw *CloudwatchSource) Configure(yamlConfig []byte, logger *log.Entry) erro targetStream := "*" if cw.Config.StreamRegexp != nil { if _, err := regexp.Compile(*cw.Config.StreamRegexp); err != nil { - return errors.Wrapf(err, "error while compiling regexp '%s'", *cw.Config.StreamRegexp) + return fmt.Errorf("while compiling regexp '%s': %w", *cw.Config.StreamRegexp, err) } targetStream = *cw.Config.StreamRegexp } else if cw.Config.StreamName != nil { @@ -345,8 +344,7 @@ func (cw *CloudwatchSource) WatchLogGroupForStreams(out chan LogStreamTailConfig }, ) if err != nil { - newerr := errors.Wrapf(err, "while describing group %s", cw.Config.GroupName) - return newerr + return fmt.Errorf("while describing group %s: %w", cw.Config.GroupName, err) } cw.logger.Tracef("after DescribeLogStreamsPagesWithContext") } @@ -495,7 +493,7 @@ func (cw *CloudwatchSource) TailLogStream(cfg *LogStreamTailConfig, outChan chan }, ) if err != nil { - newerr := errors.Wrapf(err, "while reading %s/%s", cfg.GroupName, cfg.StreamName) + newerr := fmt.Errorf("while reading %s/%s: %w", cfg.GroupName, cfg.StreamName, err) cfg.logger.Warningf("err : %s", newerr) return newerr } @@ -532,7 +530,7 @@ func (cw *CloudwatchSource) ConfigureByDSN(dsn string, labels map[string]string, u, err := url.ParseQuery(args[1]) if err != nil { - return errors.Wrapf(err, "while parsing %s", dsn) + return fmt.Errorf("while parsing %s: %w", dsn, err) } for k, v := range u { @@ -543,7 +541,7 @@ func (cw *CloudwatchSource) ConfigureByDSN(dsn string, labels map[string]string, } lvl, err := log.ParseLevel(v[0]) if err != nil { - return errors.Wrapf(err, "unknown level %s", v[0]) + return fmt.Errorf("unknown level %s: %w", v[0], err) } cw.logger.Logger.SetLevel(lvl) @@ -577,7 +575,7 @@ func (cw *CloudwatchSource) ConfigureByDSN(dsn string, labels map[string]string, //let's reuse our parser helper so that a ton of date formats are supported duration, err := time.ParseDuration(v[0]) if err != nil { - return errors.Wrapf(err, "unable to parse '%s' as duration", v[0]) + return fmt.Errorf("unable to parse '%s' as duration: %w", v[0], err) } cw.logger.Debugf("parsed '%s' as '%s'", v[0], duration) start := time.Now().UTC().Add(-duration) @@ -674,7 +672,7 @@ func (cw *CloudwatchSource) CatLogStream(cfg *LogStreamTailConfig, outChan chan }, ) if err != nil { - return errors.Wrapf(err, "while reading logs from %s/%s", cfg.GroupName, cfg.StreamName) + return fmt.Errorf("while reading logs from %s/%s: %w", cfg.GroupName, cfg.StreamName, err) } cfg.logger.Tracef("after GetLogEventsPagesWithContext") case <-cw.t.Dying(): diff --git a/pkg/acquisition/modules/docker/docker.go b/pkg/acquisition/modules/docker/docker.go index b1808e446bb..92962697437 100644 --- a/pkg/acquisition/modules/docker/docker.go +++ b/pkg/acquisition/modules/docker/docker.go @@ -12,7 +12,6 @@ import ( dockerTypes "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "gopkg.in/tomb.v2" @@ -80,7 +79,7 @@ func (d *DockerSource) UnmarshalConfig(yamlConfig []byte) error { err := yaml.UnmarshalStrict(yamlConfig, &d.Config) if err != nil { - return errors.Wrap(err, "Cannot parse DockerAcquisition configuration") + return fmt.Errorf("while parsing DockerAcquisition configuration: %w", err) } if d.logger != nil { @@ -214,7 +213,7 @@ func (d *DockerSource) ConfigureByDSN(dsn string, labels map[string]string, logg parameters, err := url.ParseQuery(args[1]) if err != nil { - return errors.Wrapf(err, "while parsing parameters %s: %s", dsn, err) + return fmt.Errorf("while parsing parameters %s: %w", dsn, err) } for k, v := range parameters { @@ -225,7 +224,7 @@ func (d *DockerSource) ConfigureByDSN(dsn string, labels map[string]string, logg } lvl, err := log.ParseLevel(v[0]) if err != nil { - return errors.Wrapf(err, "unknown level %s", v[0]) + return fmt.Errorf("unknown level %s: %w", v[0], err) } d.logger.Logger.SetLevel(lvl) case "until": diff --git a/pkg/acquisition/modules/file/file.go b/pkg/acquisition/modules/file/file.go index c24b1733218..799e78dca3d 100644 --- a/pkg/acquisition/modules/file/file.go +++ b/pkg/acquisition/modules/file/file.go @@ -14,8 +14,6 @@ import ( "strings" "time" - "github.com/crowdsecurity/go-cs-lib/pkg/trace" - "github.com/fsnotify/fsnotify" "github.com/nxadm/tail" "github.com/pkg/errors" @@ -24,6 +22,8 @@ import ( "gopkg.in/tomb.v2" "gopkg.in/yaml.v2" + "github.com/crowdsecurity/go-cs-lib/pkg/trace" + "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration" "github.com/crowdsecurity/crowdsec/pkg/types" ) @@ -110,7 +110,7 @@ func (f *FileSource) Configure(yamlConfig []byte, logger *log.Entry) error { f.watcher, err = fsnotify.NewWatcher() if err != nil { - return errors.Wrapf(err, "Could not create fsnotify watcher") + return fmt.Errorf("could not create fsnotify watcher: %w", err) } f.logger.Tracef("Actual FileAcquisition Configuration %+v", f.config) @@ -130,7 +130,7 @@ func (f *FileSource) Configure(yamlConfig []byte, logger *log.Entry) error { } files, err := filepath.Glob(pattern) if err != nil { - return errors.Wrap(err, "Glob failure") + return fmt.Errorf("glob failure: %w", err) } if len(files) == 0 { f.logger.Warnf("No matching files for pattern %s", pattern) @@ -191,7 +191,7 @@ func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger if len(args) == 2 && len(args[1]) != 0 { params, err := url.ParseQuery(args[1]) if err != nil { - return errors.Wrap(err, "could not parse file args") + return fmt.Errorf("could not parse file args: %w", err) } for key, value := range params { switch key { @@ -201,7 +201,7 @@ func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger } lvl, err := log.ParseLevel(value[0]) if err != nil { - return errors.Wrapf(err, "unknown level %s", value[0]) + return fmt.Errorf("unknown level %s: %w", value[0], err) } f.logger.Logger.SetLevel(lvl) case "max_buffer_size": @@ -210,7 +210,7 @@ func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger } maxBufferSize, err := strconv.Atoi(value[0]) if err != nil { - return errors.Wrapf(err, "could not parse max_buffer_size %s", value[0]) + return fmt.Errorf("could not parse max_buffer_size %s: %w", value[0], err) } f.config.MaxBufferSize = maxBufferSize default: @@ -226,7 +226,7 @@ func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger f.logger.Debugf("Will try pattern %s", args[0]) files, err := filepath.Glob(args[0]) if err != nil { - return errors.Wrap(err, "Glob failure") + return fmt.Errorf("glob failure: %w", err) } if len(files) == 0 { @@ -433,7 +433,7 @@ func (f *FileSource) monitorNewFiles(out chan types.Event, t *tomb.Tomb) error { case <-t.Dying(): err := f.watcher.Close() if err != nil { - return errors.Wrapf(err, "could not remove all inotify watches") + return fmt.Errorf("could not remove all inotify watches: %w", err) } return nil } @@ -495,7 +495,7 @@ func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tom fd, err := os.Open(filename) if err != nil { - return errors.Wrapf(err, "failed opening %s", filename) + return fmt.Errorf("failed opening %s: %w", filename, err) } defer fd.Close() @@ -503,7 +503,7 @@ func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tom gz, err := gzip.NewReader(fd) if err != nil { logger.Errorf("Failed to read gz file: %s", err) - return errors.Wrapf(err, "failed to read gz %s", filename) + return fmt.Errorf("failed to read gz %s: %w", filename, err) } defer gz.Close() scanner = bufio.NewScanner(gz) diff --git a/pkg/acquisition/modules/file/file_test.go b/pkg/acquisition/modules/file/file_test.go index ff55bc4134e..8f80d050fd9 100644 --- a/pkg/acquisition/modules/file/file_test.go +++ b/pkg/acquisition/modules/file/file_test.go @@ -38,7 +38,7 @@ func TestBadConfiguration(t *testing.T) { { name: "glob syntax error", config: `filename: "[asd-.log"`, - expectedErr: "Glob failure: syntax error in pattern", + expectedErr: "glob failure: syntax error in pattern", }, { name: "bad exclude regexp", @@ -150,7 +150,7 @@ filename: /`, config: ` mode: cat filename: "[*-.log"`, - expectedConfigErr: "Glob failure: syntax error in pattern", + expectedConfigErr: "glob failure: syntax error in pattern", logLevel: log.WarnLevel, expectedLines: 0, }, diff --git a/pkg/acquisition/modules/journalctl/journalctl.go b/pkg/acquisition/modules/journalctl/journalctl.go index 7882cb7c29c..b060ac364c4 100644 --- a/pkg/acquisition/modules/journalctl/journalctl.go +++ b/pkg/acquisition/modules/journalctl/journalctl.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "gopkg.in/tomb.v2" @@ -237,7 +236,7 @@ func (j *JournalCtlSource) ConfigureByDSN(dsn string, labels map[string]string, } lvl, err := log.ParseLevel(value[0]) if err != nil { - return errors.Wrapf(err, "unknown level %s", value[0]) + return fmt.Errorf("unknown level %s: %w", value[0], err) } j.logger.Logger.SetLevel(lvl) case "since": diff --git a/pkg/acquisition/modules/kafka/kafka.go b/pkg/acquisition/modules/kafka/kafka.go index 085751cfc59..dba8daf7592 100644 --- a/pkg/acquisition/modules/kafka/kafka.go +++ b/pkg/acquisition/modules/kafka/kafka.go @@ -10,7 +10,6 @@ import ( "strconv" "time" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/segmentio/kafka-go" log "github.com/sirupsen/logrus" @@ -93,12 +92,12 @@ func (k *KafkaSource) Configure(yamlConfig []byte, logger *log.Entry) error { dialer, err := k.Config.NewDialer() if err != nil { - return errors.Wrapf(err, "cannot create %s dialer", dataSourceName) + return fmt.Errorf("cannot create %s dialer: %w", dataSourceName, err) } k.Reader, err = k.Config.NewReader(dialer) if err != nil { - return errors.Wrapf(err, "cannote create %s reader", dataSourceName) + return fmt.Errorf("cannote create %s reader: %w", dataSourceName, err) } if k.Reader == nil { @@ -149,7 +148,7 @@ func (k *KafkaSource) ReadMessage(out chan types.Event) error { if err == io.EOF { return nil } - k.logger.Errorln(errors.Wrapf(err, "while reading %s message", dataSourceName)) + k.logger.Errorln(fmt.Errorf("while reading %s message: %w", dataSourceName, err)) } l := types.Line{ Raw: string(m.Value), @@ -181,7 +180,7 @@ func (k *KafkaSource) RunReader(out chan types.Event, t *tomb.Tomb) error { case <-t.Dying(): k.logger.Infof("%s datasource topic %s stopping", dataSourceName, k.Config.Topic) if err := k.Reader.Close(); err != nil { - return errors.Wrapf(err, "while closing %s reader on topic '%s'", dataSourceName, k.Config.Topic) + return fmt.Errorf("while closing %s reader on topic '%s': %w", dataSourceName, k.Config.Topic, err) } return nil } @@ -264,7 +263,7 @@ func (kc *KafkaConfiguration) NewReader(dialer *kafka.Dialer) (*kafka.Reader, er rConf.GroupID = kc.GroupID } if err := rConf.Validate(); err != nil { - return &kafka.Reader{}, errors.Wrapf(err, "while validating reader configuration") + return &kafka.Reader{}, fmt.Errorf("while validating reader configuration: %w", err) } return kafka.NewReader(rConf), nil } diff --git a/pkg/acquisition/modules/kubernetesaudit/k8s_audit.go b/pkg/acquisition/modules/kubernetesaudit/k8s_audit.go index f65a0aa579a..24354738114 100644 --- a/pkg/acquisition/modules/kubernetesaudit/k8s_audit.go +++ b/pkg/acquisition/modules/kubernetesaudit/k8s_audit.go @@ -8,16 +8,16 @@ import ( "net/http" "strings" - "github.com/crowdsecurity/go-cs-lib/pkg/trace" - - "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration" - "github.com/crowdsecurity/crowdsec/pkg/types" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "gopkg.in/tomb.v2" "gopkg.in/yaml.v2" "k8s.io/apiserver/pkg/apis/audit" + + "github.com/crowdsecurity/go-cs-lib/pkg/trace" + + "github.com/crowdsecurity/crowdsec/pkg/acquisition/configuration" + "github.com/crowdsecurity/crowdsec/pkg/types" ) type KubernetesAuditConfiguration struct { @@ -66,7 +66,7 @@ func (ka *KubernetesAuditSource) UnmarshalConfig(yamlConfig []byte) error { k8sConfig := KubernetesAuditConfiguration{} err := yaml.UnmarshalStrict(yamlConfig, &k8sConfig) if err != nil { - return errors.Wrap(err, "Cannot parse k8s-audit configuration") + return fmt.Errorf("cannot parse k8s-audit configuration: %w", err) } ka.config = k8sConfig @@ -140,7 +140,7 @@ func (ka *KubernetesAuditSource) StreamingAcquisition(out chan types.Event, t *t t.Go(func() error { err := ka.server.ListenAndServe() if err != nil && err != http.ErrServerClosed { - return errors.Wrap(err, "k8s-audit server failed") + return fmt.Errorf("k8s-audit server failed: %w", err) } return nil }) diff --git a/pkg/cwhub/cwhub.go b/pkg/cwhub/cwhub.go index f48dc223f16..bdd03c89ac5 100644 --- a/pkg/cwhub/cwhub.go +++ b/pkg/cwhub/cwhub.go @@ -146,7 +146,7 @@ func GetItemByPath(itemType string, itemPath string) (*Item, error) { finalName := "" f, err := os.Lstat(itemPath) if err != nil { - return nil, errors.Wrapf(err, "while performing lstat on %s", itemPath) + return nil, fmt.Errorf("while performing lstat on %s: %w", itemPath, err) } if f.Mode()&os.ModeSymlink == 0 { @@ -156,7 +156,7 @@ func GetItemByPath(itemType string, itemPath string) (*Item, error) { /*resolve the symlink to hub file*/ pathInHub, err := os.Readlink(itemPath) if err != nil { - return nil, errors.Wrapf(err, "while reading symlink of %s", itemPath) + return nil, fmt.Errorf("while reading symlink of %s: %w", itemPath, err) } //extract author from path fname := filepath.Base(pathInHub) @@ -238,7 +238,7 @@ func GetInstalledScenariosAsString() ([]string, error) { items, err := GetInstalledScenarios() if err != nil { - return nil, errors.Wrap(err, "while fetching scenarios") + return nil, fmt.Errorf("while fetching scenarios: %w", err) } for _, it := range items { retStr = append(retStr, it.Name) @@ -279,7 +279,7 @@ func GetInstalledParsersAsString() ([]string, error) { items, err := GetInstalledParsers() if err != nil { - return nil, errors.Wrap(err, "while fetching parsers") + return nil, fmt.Errorf("while fetching parsers: %w", err) } for _, it := range items { retStr = append(retStr, it.Name) @@ -306,7 +306,7 @@ func GetInstalledPostOverflowsAsString() ([]string, error) { items, err := GetInstalledPostOverflows() if err != nil { - return nil, errors.Wrap(err, "while fetching post overflows") + return nil, fmt.Errorf("while fetching post overflows: %w", err) } for _, it := range items { retStr = append(retStr, it.Name) @@ -319,8 +319,9 @@ func GetInstalledCollectionsAsString() ([]string, error) { items, err := GetInstalledCollections() if err != nil { - return nil, errors.Wrap(err, "while fetching collections") + return nil, fmt.Errorf("while fetching collections: %w", err) } + for _, it := range items { retStr = append(retStr, it.Name) } diff --git a/pkg/cwhub/helpers.go b/pkg/cwhub/helpers.go index af1e938d79d..4133e227250 100644 --- a/pkg/cwhub/helpers.go +++ b/pkg/cwhub/helpers.go @@ -4,12 +4,12 @@ import ( "fmt" "path/filepath" - "github.com/crowdsecurity/crowdsec/pkg/csconfig" - "github.com/crowdsecurity/crowdsec/pkg/cwversion" "github.com/enescakir/emoji" - "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/mod/semver" + + "github.com/crowdsecurity/crowdsec/pkg/csconfig" + "github.com/crowdsecurity/crowdsec/pkg/cwversion" ) // pick a hub branch corresponding to the current crowdsec version. @@ -79,11 +79,11 @@ func InstallItem(csConfig *csconfig.Config, name string, obtype string, force bo item, err := DownloadLatest(csConfig.Hub, item, force, true) if err != nil { - return errors.Wrapf(err, "while downloading %s", item.Name) + return fmt.Errorf("while downloading %s: %w", item.Name, err) } if err := AddItem(obtype, item); err != nil { - return errors.Wrapf(err, "while adding %s", item.Name) + return fmt.Errorf("while adding %s: %w", item.Name, err) } if downloadOnly { @@ -93,11 +93,11 @@ func InstallItem(csConfig *csconfig.Config, name string, obtype string, force bo item, err = EnableItem(csConfig.Hub, item) if err != nil { - return errors.Wrapf(err, "while enabling %s", item.Name) + return fmt.Errorf("while enabling %s: %w", item.Name, err) } if err := AddItem(obtype, item); err != nil { - return errors.Wrapf(err, "while adding %s", item.Name) + return fmt.Errorf("while adding %s: %w", item.Name, err) } log.Infof("Enabled %s", item.Name) diff --git a/pkg/hubtest/hubtest.go b/pkg/hubtest/hubtest.go index 36415f746da..c1aa4251ca1 100644 --- a/pkg/hubtest/hubtest.go +++ b/pkg/hubtest/hubtest.go @@ -7,7 +7,6 @@ import ( "path/filepath" "github.com/crowdsecurity/crowdsec/pkg/cwhub" - "github.com/pkg/errors" ) type HubTest struct { @@ -105,7 +104,7 @@ func (h *HubTest) LoadAllTests() error { for _, f := range testsFolder { if f.IsDir() { if _, err := h.LoadTestItem(f.Name()); err != nil { - return errors.Wrapf(err, "while loading %s", f.Name()) + return fmt.Errorf("while loading %s: %w", f.Name(), err) } } } diff --git a/pkg/hubtest/parser_assert.go b/pkg/hubtest/parser_assert.go index 3d52f37e5c3..95400b50d1a 100644 --- a/pkg/hubtest/parser_assert.go +++ b/pkg/hubtest/parser_assert.go @@ -12,14 +12,14 @@ import ( "github.com/antonmedv/expr" "github.com/antonmedv/expr/vm" - "github.com/crowdsecurity/crowdsec/pkg/exprhelpers" - "github.com/crowdsecurity/crowdsec/pkg/types" "github.com/enescakir/emoji" "github.com/fatih/color" - "github.com/pkg/errors" diff "github.com/r3labs/diff/v2" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" + + "github.com/crowdsecurity/crowdsec/pkg/exprhelpers" + "github.com/crowdsecurity/crowdsec/pkg/types" ) type AssertFail struct { @@ -164,7 +164,7 @@ func (p *ParserAssert) RunExpression(expression string) (interface{}, error) { if err != nil { log.Warningf("running : %s", expression) log.Warningf("runtime error : %s", err) - return output, errors.Wrapf(err, "while running expression %s", expression) + return output, fmt.Errorf("while running expression %s: %w", expression, err) } return output, nil } diff --git a/pkg/hubtest/scenario_assert.go b/pkg/hubtest/scenario_assert.go index d9ec4dddcb7..2e2a4e9c8be 100644 --- a/pkg/hubtest/scenario_assert.go +++ b/pkg/hubtest/scenario_assert.go @@ -11,11 +11,11 @@ import ( "github.com/antonmedv/expr" "github.com/antonmedv/expr/vm" - "github.com/crowdsecurity/crowdsec/pkg/exprhelpers" - "github.com/crowdsecurity/crowdsec/pkg/types" - "github.com/pkg/errors" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" + + "github.com/crowdsecurity/crowdsec/pkg/exprhelpers" + "github.com/crowdsecurity/crowdsec/pkg/types" ) type ScenarioAssert struct { @@ -149,7 +149,7 @@ func (s *ScenarioAssert) RunExpression(expression string) (interface{}, error) { env := map[string]interface{}{"results": *s.TestData} if runtimeFilter, err = expr.Compile(expression, exprhelpers.GetExprOptions(env)...); err != nil { - return output, err + return nil, err } // if debugFilter, err = exprhelpers.NewDebugger(assert, expr.Env(env)); err != nil { // log.Warningf("Failed building debugher for %s : %s", assert, err) @@ -162,7 +162,7 @@ func (s *ScenarioAssert) RunExpression(expression string) (interface{}, error) { if err != nil { log.Warningf("running : %s", expression) log.Warningf("runtime error : %s", err) - return output, errors.Wrapf(err, "while running expression %s", expression) + return nil, fmt.Errorf("while running expression %s: %w", expression, err) } return output, nil } diff --git a/pkg/metabase/database.go b/pkg/metabase/database.go index 49101b715c8..273d06dee16 100644 --- a/pkg/metabase/database.go +++ b/pkg/metabase/database.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/crowdsecurity/crowdsec/pkg/csconfig" - "github.com/pkg/errors" ) type Database struct { @@ -80,13 +79,13 @@ func (d *Database) Update() error { data, err := json.Marshal(success) if err != nil { - return errors.Wrap(err, "update sqlite db response (marshal)") + return fmt.Errorf("update sqlite db response (marshal): %w", err) } model := Model{} if err := json.Unmarshal(data, &model); err != nil { - return errors.Wrap(err, "update sqlite db response (unmarshal)") + return fmt.Errorf("update sqlite db response (unmarshal): %w", err) } model.Details = d.Details _, errormsg, err = d.Client.Do("PUT", routes[databaseEndpoint], model) diff --git a/pkg/metabase/metabase.go b/pkg/metabase/metabase.go index 32805329dea..cdbe65ec8df 100644 --- a/pkg/metabase/metabase.go +++ b/pkg/metabase/metabase.go @@ -4,6 +4,7 @@ import ( "archive/zip" "bytes" "context" + "errors" "fmt" "io" "net/http" @@ -15,10 +16,9 @@ import ( "github.com/docker/docker/client" log "github.com/sirupsen/logrus" + "gopkg.in/yaml.v2" "github.com/crowdsecurity/crowdsec/pkg/csconfig" - "github.com/pkg/errors" - "gopkg.in/yaml.v2" ) type Metabase struct { @@ -90,7 +90,7 @@ func (m *Metabase) Init(containerName string) error { } m.Container, err = NewContainer(m.Config.ListenAddr, m.Config.ListenPort, m.Config.DBPath, containerName, metabaseImage, DBConnectionURI, m.Config.DockerGroupID) if err != nil { - return errors.Wrap(err, "container init") + return fmt.Errorf("container init: %w", err) } return nil @@ -151,36 +151,36 @@ func SetupMetabase(dbConfig *csconfig.DatabaseCfg, listenAddr string, listenPort }, } if err := metabase.Init(containerName); err != nil { - return nil, errors.Wrap(err, "metabase setup init") + return nil, fmt.Errorf("metabase setup init: %w", err) } if err := metabase.DownloadDatabase(false); err != nil { - return nil, errors.Wrap(err, "metabase db download") + return nil, fmt.Errorf("metabase db download: %w", err) } if err := metabase.Container.Create(); err != nil { - return nil, errors.Wrap(err, "container create") + return nil, fmt.Errorf("container create: %w", err) } if err := metabase.Container.Start(); err != nil { - return nil, errors.Wrap(err, "container start") + return nil, fmt.Errorf("container start: %w", err) } log.Infof("waiting for metabase to be up (can take up to a minute)") if err := metabase.WaitAlive(); err != nil { - return nil, errors.Wrap(err, "wait alive") + return nil, fmt.Errorf("wait alive: %w", err) } if err := metabase.Database.Update(); err != nil { - return nil, errors.Wrap(err, "update database") + return nil, fmt.Errorf("update database: %w", err) } if err := metabase.Scan(); err != nil { - return nil, errors.Wrap(err, "db scan") + return nil, fmt.Errorf("db scan: %w", err) } if err := metabase.ResetCredentials(); err != nil { - return nil, errors.Wrap(err, "reset creds") + return nil, fmt.Errorf("reset creds: %w", err) } return metabase, nil @@ -193,7 +193,7 @@ func (m *Metabase) WaitAlive() error { if err != nil { if strings.Contains(err.Error(), "password:did not match stored password") { log.Errorf("Password mismatch error, is your dashboard already setup ? Run 'cscli dashboard remove' to reset it.") - return errors.Wrapf(err, "Password mismatch error") + return fmt.Errorf("password mismatch error: %w", err) } log.Debugf("%+v", err) } else { @@ -252,7 +252,7 @@ func (m *Metabase) ResetPassword(current string, newPassword string) error { } _, errormsg, err := m.Client.Do("PUT", routes[resetPasswordEndpoint], body) if err != nil { - return errors.Wrap(err, "reset username") + return fmt.Errorf("reset username: %w", err) } if errormsg != nil { return fmt.Errorf("http reset password: %s", errormsg) @@ -275,7 +275,7 @@ func (m *Metabase) ResetUsername(username string) error { _, errormsg, err := m.Client.Do("PUT", routes[userEndpoint], body) if err != nil { - return errors.Wrap(err, "reset username") + return fmt.Errorf("reset username: %w", err) } if errormsg != nil { diff --git a/pkg/types/ip.go b/pkg/types/ip.go index 647fb4a6303..5e4d7734f2d 100644 --- a/pkg/types/ip.go +++ b/pkg/types/ip.go @@ -6,13 +6,14 @@ import ( "math" "net" "strings" - - "github.com/pkg/errors" ) +// LastAddress returns the last address of a network func LastAddress(n net.IPNet) net.IP { + // get the last address by ORing the hostmask and the IP ip := n.IP.To4() if ip == nil { + // IPv6 ip = n.IP return net.IP{ ip[0] | ^n.Mask[0], ip[1] | ^n.Mask[1], ip[2] | ^n.Mask[2], @@ -35,7 +36,7 @@ func Addr2Ints(anyIP string) (int, int64, int64, int64, int64, error) { if strings.Contains(anyIP, "/") { _, net, err := net.ParseCIDR(anyIP) if err != nil { - return -1, 0, 0, 0, 0, errors.Wrapf(err, "while parsing range %s", anyIP) + return -1, 0, 0, 0, 0, fmt.Errorf("while parsing range %s: %w", anyIP, err) } return Range2Ints(*net) } @@ -47,7 +48,7 @@ func Addr2Ints(anyIP string) (int, int64, int64, int64, int64, error) { sz, start, end, err := IP2Ints(ip) if err != nil { - return -1, 0, 0, 0, 0, errors.Wrapf(err, "while parsing ip %s", anyIP) + return -1, 0, 0, 0, 0, fmt.Errorf("while parsing ip %s: %w", anyIP, err) } return sz, start, end, start, end, nil @@ -58,12 +59,12 @@ func Range2Ints(network net.IPNet) (int, int64, int64, int64, int64, error) { szStart, nwStart, sfxStart, err := IP2Ints(network.IP) if err != nil { - return -1, 0, 0, 0, 0, errors.Wrap(err, "converting first ip in range") + return -1, 0, 0, 0, 0, fmt.Errorf("converting first ip in range: %w", err) } lastAddr := LastAddress(network) szEnd, nwEnd, sfxEnd, err := IP2Ints(lastAddr) if err != nil { - return -1, 0, 0, 0, 0, errors.Wrap(err, "transforming last address of range") + return -1, 0, 0, 0, 0, fmt.Errorf("transforming last address of range: %w", err) } if szEnd != szStart { return -1, 0, 0, 0, 0, fmt.Errorf("inconsistent size for range first(%d) and last(%d) ip", szStart, szEnd)