errors.Wrap -> fmt.Errorf (#2317)

This commit is contained in:
mmetc 2023-06-29 11:34:59 +02:00 committed by GitHub
parent e61d5a3034
commit bd41f855cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 83 additions and 88 deletions

View file

@ -13,7 +13,6 @@ import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs" "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2" "gopkg.in/tomb.v2"
@ -201,7 +200,7 @@ func (cw *CloudwatchSource) Configure(yamlConfig []byte, logger *log.Entry) erro
targetStream := "*" targetStream := "*"
if cw.Config.StreamRegexp != nil { if cw.Config.StreamRegexp != nil {
if _, err := regexp.Compile(*cw.Config.StreamRegexp); err != 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 targetStream = *cw.Config.StreamRegexp
} else if cw.Config.StreamName != nil { } else if cw.Config.StreamName != nil {
@ -345,8 +344,7 @@ func (cw *CloudwatchSource) WatchLogGroupForStreams(out chan LogStreamTailConfig
}, },
) )
if err != nil { if err != nil {
newerr := errors.Wrapf(err, "while describing group %s", cw.Config.GroupName) return fmt.Errorf("while describing group %s: %w", cw.Config.GroupName, err)
return newerr
} }
cw.logger.Tracef("after DescribeLogStreamsPagesWithContext") cw.logger.Tracef("after DescribeLogStreamsPagesWithContext")
} }
@ -495,7 +493,7 @@ func (cw *CloudwatchSource) TailLogStream(cfg *LogStreamTailConfig, outChan chan
}, },
) )
if err != nil { 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) cfg.logger.Warningf("err : %s", newerr)
return newerr return newerr
} }
@ -532,7 +530,7 @@ func (cw *CloudwatchSource) ConfigureByDSN(dsn string, labels map[string]string,
u, err := url.ParseQuery(args[1]) u, err := url.ParseQuery(args[1])
if err != nil { 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 { 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]) lvl, err := log.ParseLevel(v[0])
if err != nil { 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) 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 //let's reuse our parser helper so that a ton of date formats are supported
duration, err := time.ParseDuration(v[0]) duration, err := time.ParseDuration(v[0])
if err != nil { 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) cw.logger.Debugf("parsed '%s' as '%s'", v[0], duration)
start := time.Now().UTC().Add(-duration) start := time.Now().UTC().Add(-duration)
@ -674,7 +672,7 @@ func (cw *CloudwatchSource) CatLogStream(cfg *LogStreamTailConfig, outChan chan
}, },
) )
if err != nil { 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") cfg.logger.Tracef("after GetLogEventsPagesWithContext")
case <-cw.t.Dying(): case <-cw.t.Dying():

View file

@ -12,7 +12,6 @@ import (
dockerTypes "github.com/docker/docker/api/types" dockerTypes "github.com/docker/docker/api/types"
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2" "gopkg.in/tomb.v2"
@ -80,7 +79,7 @@ func (d *DockerSource) UnmarshalConfig(yamlConfig []byte) error {
err := yaml.UnmarshalStrict(yamlConfig, &d.Config) err := yaml.UnmarshalStrict(yamlConfig, &d.Config)
if err != nil { if err != nil {
return errors.Wrap(err, "Cannot parse DockerAcquisition configuration") return fmt.Errorf("while parsing DockerAcquisition configuration: %w", err)
} }
if d.logger != nil { 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]) parameters, err := url.ParseQuery(args[1])
if err != nil { 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 { 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]) lvl, err := log.ParseLevel(v[0])
if err != nil { 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) d.logger.Logger.SetLevel(lvl)
case "until": case "until":

View file

@ -14,8 +14,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/crowdsecurity/go-cs-lib/pkg/trace"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
"github.com/nxadm/tail" "github.com/nxadm/tail"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -24,6 +22,8 @@ import (
"gopkg.in/tomb.v2" "gopkg.in/tomb.v2"
"gopkg.in/yaml.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/acquisition/configuration"
"github.com/crowdsecurity/crowdsec/pkg/types" "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() f.watcher, err = fsnotify.NewWatcher()
if err != nil { 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) 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) files, err := filepath.Glob(pattern)
if err != nil { if err != nil {
return errors.Wrap(err, "Glob failure") return fmt.Errorf("glob failure: %w", err)
} }
if len(files) == 0 { if len(files) == 0 {
f.logger.Warnf("No matching files for pattern %s", pattern) 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 { if len(args) == 2 && len(args[1]) != 0 {
params, err := url.ParseQuery(args[1]) params, err := url.ParseQuery(args[1])
if err != nil { 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 { for key, value := range params {
switch key { switch key {
@ -201,7 +201,7 @@ func (f *FileSource) ConfigureByDSN(dsn string, labels map[string]string, logger
} }
lvl, err := log.ParseLevel(value[0]) lvl, err := log.ParseLevel(value[0])
if err != nil { 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) f.logger.Logger.SetLevel(lvl)
case "max_buffer_size": 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]) maxBufferSize, err := strconv.Atoi(value[0])
if err != nil { 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 f.config.MaxBufferSize = maxBufferSize
default: 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]) f.logger.Debugf("Will try pattern %s", args[0])
files, err := filepath.Glob(args[0]) files, err := filepath.Glob(args[0])
if err != nil { if err != nil {
return errors.Wrap(err, "Glob failure") return fmt.Errorf("glob failure: %w", err)
} }
if len(files) == 0 { if len(files) == 0 {
@ -433,7 +433,7 @@ func (f *FileSource) monitorNewFiles(out chan types.Event, t *tomb.Tomb) error {
case <-t.Dying(): case <-t.Dying():
err := f.watcher.Close() err := f.watcher.Close()
if err != nil { 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 return nil
} }
@ -495,7 +495,7 @@ func (f *FileSource) readFile(filename string, out chan types.Event, t *tomb.Tom
fd, err := os.Open(filename) fd, err := os.Open(filename)
if err != nil { if err != nil {
return errors.Wrapf(err, "failed opening %s", filename) return fmt.Errorf("failed opening %s: %w", filename, err)
} }
defer fd.Close() 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) gz, err := gzip.NewReader(fd)
if err != nil { if err != nil {
logger.Errorf("Failed to read gz file: %s", err) 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() defer gz.Close()
scanner = bufio.NewScanner(gz) scanner = bufio.NewScanner(gz)

View file

@ -38,7 +38,7 @@ func TestBadConfiguration(t *testing.T) {
{ {
name: "glob syntax error", name: "glob syntax error",
config: `filename: "[asd-.log"`, config: `filename: "[asd-.log"`,
expectedErr: "Glob failure: syntax error in pattern", expectedErr: "glob failure: syntax error in pattern",
}, },
{ {
name: "bad exclude regexp", name: "bad exclude regexp",
@ -150,7 +150,7 @@ filename: /`,
config: ` config: `
mode: cat mode: cat
filename: "[*-.log"`, filename: "[*-.log"`,
expectedConfigErr: "Glob failure: syntax error in pattern", expectedConfigErr: "glob failure: syntax error in pattern",
logLevel: log.WarnLevel, logLevel: log.WarnLevel,
expectedLines: 0, expectedLines: 0,
}, },

View file

@ -9,7 +9,6 @@ import (
"strings" "strings"
"time" "time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2" "gopkg.in/tomb.v2"
@ -237,7 +236,7 @@ func (j *JournalCtlSource) ConfigureByDSN(dsn string, labels map[string]string,
} }
lvl, err := log.ParseLevel(value[0]) lvl, err := log.ParseLevel(value[0])
if err != nil { 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) j.logger.Logger.SetLevel(lvl)
case "since": case "since":

View file

@ -10,7 +10,6 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/segmentio/kafka-go" "github.com/segmentio/kafka-go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -93,12 +92,12 @@ func (k *KafkaSource) Configure(yamlConfig []byte, logger *log.Entry) error {
dialer, err := k.Config.NewDialer() dialer, err := k.Config.NewDialer()
if err != nil { 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) k.Reader, err = k.Config.NewReader(dialer)
if err != nil { 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 { if k.Reader == nil {
@ -149,7 +148,7 @@ func (k *KafkaSource) ReadMessage(out chan types.Event) error {
if err == io.EOF { if err == io.EOF {
return nil 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{ l := types.Line{
Raw: string(m.Value), Raw: string(m.Value),
@ -181,7 +180,7 @@ func (k *KafkaSource) RunReader(out chan types.Event, t *tomb.Tomb) error {
case <-t.Dying(): case <-t.Dying():
k.logger.Infof("%s datasource topic %s stopping", dataSourceName, k.Config.Topic) k.logger.Infof("%s datasource topic %s stopping", dataSourceName, k.Config.Topic)
if err := k.Reader.Close(); err != nil { 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 return nil
} }
@ -264,7 +263,7 @@ func (kc *KafkaConfiguration) NewReader(dialer *kafka.Dialer) (*kafka.Reader, er
rConf.GroupID = kc.GroupID rConf.GroupID = kc.GroupID
} }
if err := rConf.Validate(); err != nil { 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 return kafka.NewReader(rConf), nil
} }

View file

@ -8,16 +8,16 @@ import (
"net/http" "net/http"
"strings" "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" "github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2" "gopkg.in/tomb.v2"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"k8s.io/apiserver/pkg/apis/audit" "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 { type KubernetesAuditConfiguration struct {
@ -66,7 +66,7 @@ func (ka *KubernetesAuditSource) UnmarshalConfig(yamlConfig []byte) error {
k8sConfig := KubernetesAuditConfiguration{} k8sConfig := KubernetesAuditConfiguration{}
err := yaml.UnmarshalStrict(yamlConfig, &k8sConfig) err := yaml.UnmarshalStrict(yamlConfig, &k8sConfig)
if err != nil { 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 ka.config = k8sConfig
@ -140,7 +140,7 @@ func (ka *KubernetesAuditSource) StreamingAcquisition(out chan types.Event, t *t
t.Go(func() error { t.Go(func() error {
err := ka.server.ListenAndServe() err := ka.server.ListenAndServe()
if err != nil && err != http.ErrServerClosed { 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 return nil
}) })

View file

@ -146,7 +146,7 @@ func GetItemByPath(itemType string, itemPath string) (*Item, error) {
finalName := "" finalName := ""
f, err := os.Lstat(itemPath) f, err := os.Lstat(itemPath)
if err != nil { 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 { if f.Mode()&os.ModeSymlink == 0 {
@ -156,7 +156,7 @@ func GetItemByPath(itemType string, itemPath string) (*Item, error) {
/*resolve the symlink to hub file*/ /*resolve the symlink to hub file*/
pathInHub, err := os.Readlink(itemPath) pathInHub, err := os.Readlink(itemPath)
if err != nil { 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 //extract author from path
fname := filepath.Base(pathInHub) fname := filepath.Base(pathInHub)
@ -238,7 +238,7 @@ func GetInstalledScenariosAsString() ([]string, error) {
items, err := GetInstalledScenarios() items, err := GetInstalledScenarios()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "while fetching scenarios") return nil, fmt.Errorf("while fetching scenarios: %w", err)
} }
for _, it := range items { for _, it := range items {
retStr = append(retStr, it.Name) retStr = append(retStr, it.Name)
@ -279,7 +279,7 @@ func GetInstalledParsersAsString() ([]string, error) {
items, err := GetInstalledParsers() items, err := GetInstalledParsers()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "while fetching parsers") return nil, fmt.Errorf("while fetching parsers: %w", err)
} }
for _, it := range items { for _, it := range items {
retStr = append(retStr, it.Name) retStr = append(retStr, it.Name)
@ -306,7 +306,7 @@ func GetInstalledPostOverflowsAsString() ([]string, error) {
items, err := GetInstalledPostOverflows() items, err := GetInstalledPostOverflows()
if err != nil { 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 { for _, it := range items {
retStr = append(retStr, it.Name) retStr = append(retStr, it.Name)
@ -319,8 +319,9 @@ func GetInstalledCollectionsAsString() ([]string, error) {
items, err := GetInstalledCollections() items, err := GetInstalledCollections()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "while fetching collections") return nil, fmt.Errorf("while fetching collections: %w", err)
} }
for _, it := range items { for _, it := range items {
retStr = append(retStr, it.Name) retStr = append(retStr, it.Name)
} }

View file

@ -4,12 +4,12 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/enescakir/emoji" "github.com/enescakir/emoji"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"golang.org/x/mod/semver" "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. // 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) item, err := DownloadLatest(csConfig.Hub, item, force, true)
if err != nil { 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 { 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 { if downloadOnly {
@ -93,11 +93,11 @@ func InstallItem(csConfig *csconfig.Config, name string, obtype string, force bo
item, err = EnableItem(csConfig.Hub, item) item, err = EnableItem(csConfig.Hub, item)
if err != nil { 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 { 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) log.Infof("Enabled %s", item.Name)

View file

@ -7,7 +7,6 @@ import (
"path/filepath" "path/filepath"
"github.com/crowdsecurity/crowdsec/pkg/cwhub" "github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/pkg/errors"
) )
type HubTest struct { type HubTest struct {
@ -105,7 +104,7 @@ func (h *HubTest) LoadAllTests() error {
for _, f := range testsFolder { for _, f := range testsFolder {
if f.IsDir() { if f.IsDir() {
if _, err := h.LoadTestItem(f.Name()); err != nil { 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)
} }
} }
} }

View file

@ -12,14 +12,14 @@ import (
"github.com/antonmedv/expr" "github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm" "github.com/antonmedv/expr/vm"
"github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/enescakir/emoji" "github.com/enescakir/emoji"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/pkg/errors"
diff "github.com/r3labs/diff/v2" diff "github.com/r3labs/diff/v2"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
"github.com/crowdsecurity/crowdsec/pkg/types"
) )
type AssertFail struct { type AssertFail struct {
@ -164,7 +164,7 @@ func (p *ParserAssert) RunExpression(expression string) (interface{}, error) {
if err != nil { if err != nil {
log.Warningf("running : %s", expression) log.Warningf("running : %s", expression)
log.Warningf("runtime error : %s", err) 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 return output, nil
} }

View file

@ -11,11 +11,11 @@ import (
"github.com/antonmedv/expr" "github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm" "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" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
"github.com/crowdsecurity/crowdsec/pkg/types"
) )
type ScenarioAssert struct { type ScenarioAssert struct {
@ -149,7 +149,7 @@ func (s *ScenarioAssert) RunExpression(expression string) (interface{}, error) {
env := map[string]interface{}{"results": *s.TestData} env := map[string]interface{}{"results": *s.TestData}
if runtimeFilter, err = expr.Compile(expression, exprhelpers.GetExprOptions(env)...); err != nil { 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 { // if debugFilter, err = exprhelpers.NewDebugger(assert, expr.Env(env)); err != nil {
// log.Warningf("Failed building debugher for %s : %s", assert, err) // 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 { if err != nil {
log.Warningf("running : %s", expression) log.Warningf("running : %s", expression)
log.Warningf("runtime error : %s", err) 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 return output, nil
} }

View file

@ -7,7 +7,6 @@ import (
"strings" "strings"
"github.com/crowdsecurity/crowdsec/pkg/csconfig" "github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/pkg/errors"
) )
type Database struct { type Database struct {
@ -80,13 +79,13 @@ func (d *Database) Update() error {
data, err := json.Marshal(success) data, err := json.Marshal(success)
if err != nil { if err != nil {
return errors.Wrap(err, "update sqlite db response (marshal)") return fmt.Errorf("update sqlite db response (marshal): %w", err)
} }
model := Model{} model := Model{}
if err := json.Unmarshal(data, &model); err != nil { 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 model.Details = d.Details
_, errormsg, err = d.Client.Do("PUT", routes[databaseEndpoint], model) _, errormsg, err = d.Client.Do("PUT", routes[databaseEndpoint], model)

View file

@ -4,6 +4,7 @@ import (
"archive/zip" "archive/zip"
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -15,10 +16,9 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/crowdsec/pkg/csconfig" "github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
) )
type Metabase struct { 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) m.Container, err = NewContainer(m.Config.ListenAddr, m.Config.ListenPort, m.Config.DBPath, containerName, metabaseImage, DBConnectionURI, m.Config.DockerGroupID)
if err != nil { if err != nil {
return errors.Wrap(err, "container init") return fmt.Errorf("container init: %w", err)
} }
return nil return nil
@ -151,36 +151,36 @@ func SetupMetabase(dbConfig *csconfig.DatabaseCfg, listenAddr string, listenPort
}, },
} }
if err := metabase.Init(containerName); err != nil { 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 { 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 { 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 { 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)") log.Infof("waiting for metabase to be up (can take up to a minute)")
if err := metabase.WaitAlive(); err != nil { 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 { 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 { 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 { if err := metabase.ResetCredentials(); err != nil {
return nil, errors.Wrap(err, "reset creds") return nil, fmt.Errorf("reset creds: %w", err)
} }
return metabase, nil return metabase, nil
@ -193,7 +193,7 @@ func (m *Metabase) WaitAlive() error {
if err != nil { if err != nil {
if strings.Contains(err.Error(), "password:did not match stored password") { 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.") 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) log.Debugf("%+v", err)
} else { } else {
@ -252,7 +252,7 @@ func (m *Metabase) ResetPassword(current string, newPassword string) error {
} }
_, errormsg, err := m.Client.Do("PUT", routes[resetPasswordEndpoint], body) _, errormsg, err := m.Client.Do("PUT", routes[resetPasswordEndpoint], body)
if err != nil { if err != nil {
return errors.Wrap(err, "reset username") return fmt.Errorf("reset username: %w", err)
} }
if errormsg != nil { if errormsg != nil {
return fmt.Errorf("http reset password: %s", errormsg) 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) _, errormsg, err := m.Client.Do("PUT", routes[userEndpoint], body)
if err != nil { if err != nil {
return errors.Wrap(err, "reset username") return fmt.Errorf("reset username: %w", err)
} }
if errormsg != nil { if errormsg != nil {

View file

@ -6,13 +6,14 @@ import (
"math" "math"
"net" "net"
"strings" "strings"
"github.com/pkg/errors"
) )
// LastAddress returns the last address of a network
func LastAddress(n net.IPNet) net.IP { func LastAddress(n net.IPNet) net.IP {
// get the last address by ORing the hostmask and the IP
ip := n.IP.To4() ip := n.IP.To4()
if ip == nil { if ip == nil {
// IPv6
ip = n.IP ip = n.IP
return net.IP{ return net.IP{
ip[0] | ^n.Mask[0], ip[1] | ^n.Mask[1], ip[2] | ^n.Mask[2], 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, "/") { if strings.Contains(anyIP, "/") {
_, net, err := net.ParseCIDR(anyIP) _, net, err := net.ParseCIDR(anyIP)
if err != nil { 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) return Range2Ints(*net)
} }
@ -47,7 +48,7 @@ func Addr2Ints(anyIP string) (int, int64, int64, int64, int64, error) {
sz, start, end, err := IP2Ints(ip) sz, start, end, err := IP2Ints(ip)
if err != nil { 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 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) szStart, nwStart, sfxStart, err := IP2Ints(network.IP)
if err != nil { 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) lastAddr := LastAddress(network)
szEnd, nwEnd, sfxEnd, err := IP2Ints(lastAddr) szEnd, nwEnd, sfxEnd, err := IP2Ints(lastAddr)
if err != nil { 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 { if szEnd != szStart {
return -1, 0, 0, 0, 0, fmt.Errorf("inconsistent size for range first(%d) and last(%d) ip", szStart, szEnd) return -1, 0, 0, 0, 0, fmt.Errorf("inconsistent size for range first(%d) and last(%d) ip", szStart, szEnd)