From 3325ba1caf101f17c2b822ad453a8053c2cad1be Mon Sep 17 00:00:00 2001 From: Amit Kanfer Date: Wed, 21 Jun 2023 15:43:16 +0300 Subject: [PATCH] Removing obsolete errors package (#35825) --- filebeat/cmd/modules.go | 10 ++--- filebeat/fileset/compatibility.go | 9 ++-- filebeat/fileset/fileset.go | 41 +++++++++---------- filebeat/input/container/input.go | 8 ++-- filebeat/input/mqtt/input.go | 4 +- filebeat/input/syslog/input.go | 5 +-- filebeat/inputsource/common/streaming/conn.go | 3 +- .../inputsource/common/streaming/handler.go | 5 +-- .../inputsource/common/streaming/listener.go | 3 +- filebeat/inputsource/unix/socket.go | 7 ++-- filebeat/scripts/mage/package.go | 5 ++- libbeat/asset/asset.go | 9 ++-- .../autodiscover/appenders/config/config.go | 6 +-- .../providers/jolokia/discovery.go | 4 +- .../autodiscover/providers/jolokia/jolokia.go | 3 +- libbeat/cfgfile/factories.go | 2 +- libbeat/cfgfile/glob_manager.go | 12 +++--- libbeat/cloudid/cloudid.go | 15 ++++--- libbeat/common/capabilities_linux.go | 10 +++-- libbeat/common/cfgtype/timezone.go | 5 +-- libbeat/common/cli/confirm.go | 3 +- libbeat/common/cli/input.go | 2 +- libbeat/common/cli/password.go | 5 ++- libbeat/common/event.go | 10 ++--- libbeat/common/fmtstr/formatevents.go | 5 +-- libbeat/common/schema/options_test.go | 3 +- libbeat/common/schema/schema_test.go | 3 +- libbeat/common/seccomp/seccomp.go | 5 ++- libbeat/conditions/network.go | 11 ++--- libbeat/dashboards/dashboards.go | 4 +- libbeat/dashboards/export.go | 9 ++-- libbeat/dashboards/importer.go | 8 ++-- libbeat/dashboards/kibana_loader.go | 5 +-- libbeat/esleg/eslegclient/api.go | 4 +- libbeat/generator/fields/validate/mapping.go | 38 ++++++++--------- libbeat/generator/fields/validate/validate.go | 7 ++-- libbeat/idxmgmt/ilm/ilm.go | 10 ++--- libbeat/licenser/elastic_fetcher.go | 3 +- libbeat/mapping/field.go | 8 ++-- libbeat/monitoring/report/report.go | 10 ++--- .../add_cloud_metadata/http_fetcher.go | 15 ++++--- .../add_process_metadata_test.go | 2 +- .../processors/add_process_metadata/config.go | 6 +-- .../gosigar_cid_provider.go | 5 +-- libbeat/processors/dissect/config.go | 5 +-- libbeat/processors/dissect/dissect.go | 3 +- libbeat/processors/dns/config.go | 23 +++++------ libbeat/processors/dns/resolver.go | 2 +- libbeat/processors/ratelimit/algorithm.go | 4 +- libbeat/processors/ratelimit/token_bucket.go | 4 +- .../script/javascript/beatevent_v0.go | 8 ++-- .../processors/script/javascript/config.go | 7 ++-- .../javascript/module/console/console.go | 5 ++- .../javascript/module/processor/processor.go | 3 +- .../javascript/module/require/require.go | 5 ++- .../processors/script/javascript/session.go | 17 ++++---- libbeat/processors/translate_sid/config.go | 2 +- libbeat/reader/readjson/docker_json.go | 10 ++--- libbeat/tests/compose/project.go | 5 +-- libbeat/tests/compose/wrapper.go | 32 +++++++-------- libbeat/tests/docker/docker.go | 11 +++-- 61 files changed, 234 insertions(+), 259 deletions(-) diff --git a/filebeat/cmd/modules.go b/filebeat/cmd/modules.go index d07ebd78fb5d..de76e32c6e68 100644 --- a/filebeat/cmd/modules.go +++ b/filebeat/cmd/modules.go @@ -18,10 +18,10 @@ package cmd import ( + "errors" + "fmt" "strings" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/beats/v7/libbeat/cfgfile" "github.com/elastic/beats/v7/libbeat/cmd" @@ -32,16 +32,16 @@ func buildModulesManager(beat *beat.Beat) (cmd.ModulesManager, error) { glob, err := config.String("config.modules.path", -1) if err != nil { - return nil, errors.Errorf("modules management requires 'filebeat.config.modules.path' setting") + return nil, errors.New("modules management requires 'filebeat.config.modules.path' setting") } if !strings.HasSuffix(glob, "*.yml") { - return nil, errors.Errorf("wrong settings for config.modules.path, it is expected to end with *.yml. Got: %s", glob) + return nil, fmt.Errorf("wrong settings for config.modules.path, it is expected to end with *.yml. Got: %s", glob) } modulesManager, err := cfgfile.NewGlobManager(glob, ".yml", ".disabled") if err != nil { - return nil, errors.Wrap(err, "initialization error") + return nil, fmt.Errorf("initialization error: %w", err) } return modulesManager, nil } diff --git a/filebeat/fileset/compatibility.go b/filebeat/fileset/compatibility.go index 4d56367b69c9..5e2aefb8bef3 100644 --- a/filebeat/fileset/compatibility.go +++ b/filebeat/fileset/compatibility.go @@ -19,11 +19,10 @@ package fileset import ( "encoding/json" + "errors" "fmt" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-libs/version" ) @@ -242,14 +241,14 @@ nextProcessor: for i, obj := range processors { processor, err := NewProcessor(obj) if err != nil { - return errors.Wrapf(err, "cannot parse processor in section '%s' index %d body=%+v", section, i, obj) + return fmt.Errorf("cannot parse processor in section '%s' index %d body=%+v: %w", section, i, obj, err) } // Adapt any on_failure processors for this processor. prevOnFailure, _ := processor.GetList("on_failure") if err = adaptProcessorsForCompatibility(esVersion, processor.Config(), "on_failure", true, log.With("parent_processor_type", processor.Name(), "parent_processor_index", i)); err != nil { - return errors.Wrapf(err, "cannot parse on_failure for processor in section '%s' index %d body=%+v", section, i, obj) + return fmt.Errorf("cannot parse on_failure for processor in section '%s' index %d body=%+v: %w", section, i, obj, err) } if onFailure, _ := processor.GetList("on_failure"); len(prevOnFailure) > 0 && len(onFailure) == 0 { processor.Delete("on_failure") @@ -260,7 +259,7 @@ nextProcessor: processor.Set("processor", []interface{}{inner}) if err = adaptProcessorsForCompatibility(esVersion, processor.Config(), "processor", false, log.With("parent_processor_type", processor.Name(), "parent_processor_index", i)); err != nil { - return errors.Wrapf(err, "cannot parse inner processor for foreach in section '%s' index %d", section, i) + return fmt.Errorf("cannot parse inner processor for foreach in section '%s' index %d: %w", section, i, err) } newList, _ := processor.GetList("processor") switch len(newList) { diff --git a/filebeat/fileset/fileset.go b/filebeat/fileset/fileset.go index a5bfdbf95d05..7fc91135dcc8 100644 --- a/filebeat/fileset/fileset.go +++ b/filebeat/fileset/fileset.go @@ -34,7 +34,6 @@ import ( "github.com/elastic/go-ucfg" - errw "github.com/pkg/errors" "gopkg.in/yaml.v2" "github.com/elastic/beats/v7/libbeat/beat" @@ -219,7 +218,7 @@ func (fs *Fileset) turnOffElasticsearchVars(vars map[string]interface{}, esVersi if ok { minVersion, err := version.New(minESVersion["version"].(string)) if err != nil { - return vars, fmt.Errorf("Error parsing version %s: %v", minESVersion["version"].(string), err) + return vars, fmt.Errorf("Error parsing version %s: %w", minESVersion["version"].(string), err) } logp.Debug("fileset", "Comparing ES version %s with requirement of %s", esVersion.String(), minVersion) @@ -270,13 +269,13 @@ func ApplyTemplate(vars map[string]interface{}, templateString string, specialDe tplFunctions, err := getTemplateFunctions(vars) if err != nil { - return "", errw.Wrap(err, "error fetching template functions") + return "", fmt.Errorf("error fetching template functions: %w", err) } tpl = tpl.Funcs(tplFunctions) tpl, err = tpl.Parse(templateString) if err != nil { - return "", fmt.Errorf("Error parsing template %s: %v", templateString, err) + return "", fmt.Errorf("Error parsing template %s: %w", templateString, err) } buf := bytes.NewBufferString("") err = tpl.Execute(buf, vars) @@ -325,7 +324,7 @@ func getTemplateFunctions(vars map[string]interface{}) (template.FuncMap, error) func (fs *Fileset) getBuiltinVars(info beat.Info) (map[string]interface{}, error) { host, err := os.Hostname() if err != nil || len(host) == 0 { - return nil, fmt.Errorf("Error getting the hostname: %v", err) + return nil, fmt.Errorf("Error getting the hostname: %w", err) } split := strings.SplitN(host, ".", 2) hostname := split[0] @@ -347,21 +346,21 @@ func (fs *Fileset) getBuiltinVars(info beat.Info) (map[string]interface{}, error func (fs *Fileset) getInputConfig() (*conf.C, error) { path, err := ApplyTemplate(fs.vars, fs.manifest.Input, false) if err != nil { - return nil, fmt.Errorf("Error expanding vars on the input path: %v", err) + return nil, fmt.Errorf("Error expanding vars on the input path: %w", err) } contents, err := ioutil.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) if err != nil { - return nil, fmt.Errorf("Error reading input file %s: %v", path, err) + return nil, fmt.Errorf("Error reading input file %s: %w", path, err) } yaml, err := ApplyTemplate(fs.vars, string(contents), false) if err != nil { - return nil, fmt.Errorf("Error interpreting the template of the input: %v", err) + return nil, fmt.Errorf("Error interpreting the template of the input: %w", err) } cfg, err := conf.NewConfigWithYAML([]byte(yaml), "") if err != nil { - return nil, fmt.Errorf("Error reading input config: %v", err) + return nil, fmt.Errorf("Error reading input config: %w", err) } cfg, err = mergePathDefaults(cfg) @@ -373,11 +372,11 @@ func (fs *Fileset) getInputConfig() (*conf.C, error) { if len(fs.fcfg.Input) > 0 { overrides, err := conf.NewConfigFrom(fs.fcfg.Input) if err != nil { - return nil, fmt.Errorf("Error creating config from input overrides: %v", err) + return nil, fmt.Errorf("Error creating config from input overrides: %w", err) } cfg, err = conf.MergeConfigsWithOptions([]*conf.C{cfg, overrides}, ucfg.FieldReplaceValues("**.paths"), ucfg.FieldAppendValues("**.processors")) if err != nil { - return nil, fmt.Errorf("Error applying config overrides: %v", err) + return nil, fmt.Errorf("Error applying config overrides: %w", err) } } @@ -388,18 +387,18 @@ func (fs *Fileset) getInputConfig() (*conf.C, error) { rootPipelineID = fs.pipelineIDs[0] } if err := cfg.SetString(pipelineField, -1, rootPipelineID); err != nil { - return nil, errw.Wrap(err, "error setting the fileset pipeline ID in config") + return nil, fmt.Errorf("error setting the fileset pipeline ID in config: %w", err) } } // force our the module/fileset name err = cfg.SetString("_module_name", -1, fs.mname) if err != nil { - return nil, fmt.Errorf("Error setting the _module_name cfg in the input config: %v", err) + return nil, fmt.Errorf("Error setting the _module_name cfg in the input config: %w", err) } err = cfg.SetString("_fileset_name", -1, fs.name) if err != nil { - return nil, fmt.Errorf("Error setting the _fileset_name cfg in the input config: %v", err) + return nil, fmt.Errorf("Error setting the _fileset_name cfg in the input config: %w", err) } common.PrintConfigDebugf(cfg, "Merged input config for fileset %s/%s", fs.mname, fs.name) @@ -413,7 +412,7 @@ func (fs *Fileset) getPipelineIDs(info beat.Info) ([]string, error) { for _, ingestPipeline := range fs.manifest.IngestPipeline { path, err := ApplyTemplate(fs.vars, ingestPipeline, false) if err != nil { - return nil, fmt.Errorf("Error expanding vars on the ingest pipeline path: %v", err) + return nil, fmt.Errorf("Error expanding vars on the ingest pipeline path: %w", err) } pipelineIDs = append(pipelineIDs, FormatPipelineID(info.IndexPrefix, fs.mname, fs.name, path, info.Version)) @@ -432,32 +431,32 @@ func (fs *Fileset) GetPipelines(esVersion version.V) (pipelines []pipeline, err for idx, ingestPipeline := range fs.manifest.IngestPipeline { path, err := ApplyTemplate(fs.vars, ingestPipeline, false) if err != nil { - return nil, fmt.Errorf("Error expanding vars on the ingest pipeline path: %v", err) + return nil, fmt.Errorf("Error expanding vars on the ingest pipeline path: %w", err) } strContents, err := ioutil.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) if err != nil { - return nil, fmt.Errorf("Error reading pipeline file %s: %v", path, err) + return nil, fmt.Errorf("Error reading pipeline file %s: %w", path, err) } encodedString, err := ApplyTemplate(vars, string(strContents), true) if err != nil { - return nil, fmt.Errorf("Error interpreting the template of the ingest pipeline: %v", err) + return nil, fmt.Errorf("Error interpreting the template of the ingest pipeline: %w", err) } var content map[string]interface{} switch extension := strings.ToLower(filepath.Ext(path)); extension { case ".json": if err = json.Unmarshal([]byte(encodedString), &content); err != nil { - return nil, fmt.Errorf("Error JSON decoding the pipeline file: %s: %v", path, err) + return nil, fmt.Errorf("Error JSON decoding the pipeline file: %s: %w", path, err) } case ".yaml", ".yml": if err = yaml.Unmarshal([]byte(encodedString), &content); err != nil { - return nil, fmt.Errorf("Error YAML decoding the pipeline file: %s: %v", path, err) + return nil, fmt.Errorf("Error YAML decoding the pipeline file: %s: %w", path, err) } newContent, err := FixYAMLMaps(content) if err != nil { - return nil, fmt.Errorf("Failed to sanitize the YAML pipeline file: %s: %v", path, err) + return nil, fmt.Errorf("Failed to sanitize the YAML pipeline file: %s: %w", path, err) } content = newContent.(map[string]interface{}) default: diff --git a/filebeat/input/container/input.go b/filebeat/input/container/input.go index 440b3b294381..dde16fb9d5d8 100644 --- a/filebeat/input/container/input.go +++ b/filebeat/input/container/input.go @@ -18,13 +18,13 @@ package container import ( + "fmt" + "github.com/elastic/beats/v7/filebeat/channel" "github.com/elastic/beats/v7/filebeat/input" "github.com/elastic/beats/v7/filebeat/input/log" conf "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/mapstr" - - "github.com/pkg/errors" ) func init() { @@ -43,7 +43,7 @@ func NewInput( // Wrap log input with custom docker settings config := defaultConfig if err := cfg.Unpack(&config); err != nil { - return nil, errors.Wrap(err, "reading container input config") + return nil, fmt.Errorf("reading container input config: %w", err) } err := cfg.Merge(mapstr.M{ @@ -60,7 +60,7 @@ func NewInput( "symlinks": true, }) if err != nil { - return nil, errors.Wrap(err, "update input config") + return nil, fmt.Errorf("update input config: %w", err) } // Add stream to meta to ensure different state per stream diff --git a/filebeat/input/mqtt/input.go b/filebeat/input/mqtt/input.go index b15b0a7a9a1c..1ede23cdd78b 100644 --- a/filebeat/input/mqtt/input.go +++ b/filebeat/input/mqtt/input.go @@ -18,12 +18,12 @@ package mqtt import ( + "fmt" "strings" "sync" "time" libmqtt "github.com/eclipse/paho.mqtt.golang" - "github.com/pkg/errors" "github.com/elastic/beats/v7/filebeat/channel" "github.com/elastic/beats/v7/filebeat/input" @@ -77,7 +77,7 @@ func newInput( ) (input.Input, error) { config := defaultConfig() if err := cfg.Unpack(&config); err != nil { - return nil, errors.Wrap(err, "reading mqtt input config") + return nil, fmt.Errorf("reading mqtt input config: %w", err) } out, err := connector.Connect(cfg) diff --git a/filebeat/input/syslog/input.go b/filebeat/input/syslog/input.go index 779be47c0fe7..702472794dd6 100644 --- a/filebeat/input/syslog/input.go +++ b/filebeat/input/syslog/input.go @@ -18,12 +18,11 @@ package syslog import ( + "fmt" "strings" "sync" "time" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/filebeat/channel" "github.com/elastic/beats/v7/filebeat/harvester" "github.com/elastic/beats/v7/filebeat/input" @@ -319,7 +318,7 @@ func newBeatEvent(timestamp time.Time, metadata inputsource.NetworkMetadata, fie func mapValueToName(v int, m mapper) (string, error) { if v < 0 || v >= len(m) { - return "", errors.Errorf("value out of bound: %d", v) + return "", fmt.Errorf("value out of bound: %d", v) } return m[v], nil } diff --git a/filebeat/inputsource/common/streaming/conn.go b/filebeat/inputsource/common/streaming/conn.go index e0c2b3e90380..682ecc04898e 100644 --- a/filebeat/inputsource/common/streaming/conn.go +++ b/filebeat/inputsource/common/streaming/conn.go @@ -18,11 +18,10 @@ package streaming import ( + "errors" "io" "net" "time" - - "github.com/pkg/errors" ) // ErrMaxReadBuffer returns when too many bytes was read on the io.Reader diff --git a/filebeat/inputsource/common/streaming/handler.go b/filebeat/inputsource/common/streaming/handler.go index 45ff4ded8639..aac5197c8bd7 100644 --- a/filebeat/inputsource/common/streaming/handler.go +++ b/filebeat/inputsource/common/streaming/handler.go @@ -20,10 +20,9 @@ package streaming import ( "bufio" "context" + "fmt" "net" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/filebeat/inputsource" "github.com/elastic/elastic-agent-libs/logp" ) @@ -76,7 +75,7 @@ func SplitHandlerFactory(family inputsource.Family, logger *logp.Logger, metadat if IsMaxReadBufferErr(err) { log.Errorw("split_client error", "error", err) } - return errors.Wrap(err, string(family)+" split_client error") + return fmt.Errorf(string(family)+" split_client error: %w", err) } r.Reset() callback(scanner.Bytes(), metadata) diff --git a/filebeat/inputsource/common/streaming/listener.go b/filebeat/inputsource/common/streaming/listener.go index 6a13737e0cd6..69fb077144c4 100644 --- a/filebeat/inputsource/common/streaming/listener.go +++ b/filebeat/inputsource/common/streaming/listener.go @@ -21,13 +21,12 @@ import ( "bufio" "bytes" "context" + "errors" "fmt" "net" "strings" "sync" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/filebeat/inputsource" "github.com/elastic/beats/v7/libbeat/common/atomic" "github.com/elastic/elastic-agent-libs/logp" diff --git a/filebeat/inputsource/unix/socket.go b/filebeat/inputsource/unix/socket.go index 7bb8e69e97d3..c35a69ce6a31 100644 --- a/filebeat/inputsource/unix/socket.go +++ b/filebeat/inputsource/unix/socket.go @@ -18,14 +18,13 @@ package unix import ( + "errors" "fmt" "os" "os/user" "runtime" "strconv" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/logp" ) @@ -36,7 +35,7 @@ func cleanupStaleSocket(path string) error { if os.IsNotExist(err) { return nil } - return errors.Wrapf(err, "cannot lstat unix socket file at location %s", path) + return fmt.Errorf("cannot lstat unix socket file at location %s: %w", path, err) } if runtime.GOOS != "windows" { @@ -47,7 +46,7 @@ func cleanupStaleSocket(path string) error { } if err := os.Remove(path); err != nil { - return errors.Wrapf(err, "cannot remove existing unix socket file at location %s", path) + return fmt.Errorf("cannot remove existing unix socket file at location %s: %w", path, err) } return nil diff --git a/filebeat/scripts/mage/package.go b/filebeat/scripts/mage/package.go index eaf84cb98569..80c2e8e651b0 100644 --- a/filebeat/scripts/mage/package.go +++ b/filebeat/scripts/mage/package.go @@ -18,8 +18,9 @@ package mage import ( + "fmt" + "github.com/magefile/mage/mg" - "github.com/pkg/errors" devtools "github.com/elastic/beats/v7/dev-tools/mage" ) @@ -59,7 +60,7 @@ func CustomizePackaging() { args.Spec.Files["/usr/share/{{.BeatName}}/"+moduleTarget] = module args.Spec.Files["/etc/{{.BeatName}}/"+modulesDTarget] = modulesD default: - panic(errors.Errorf("unhandled package type: %v", pkgType)) + panic(fmt.Errorf("unhandled package type: %v", pkgType)) } break } diff --git a/libbeat/asset/asset.go b/libbeat/asset/asset.go index 7b9f0526eada..e26a4881618c 100644 --- a/libbeat/asset/asset.go +++ b/libbeat/asset/asset.go @@ -19,12 +19,11 @@ package asset import ( "bytes" + "fmt" "go/format" "math" "strings" "text/template" - - "github.com/pkg/errors" ) type Priority int32 @@ -80,7 +79,7 @@ func CreateAsset(license string, beat string, name string, pkg string, data []by // what leads to different results, remove them before encoding. encData, err := EncodeData(strings.Replace(string(data), "\r", "", -1)) if err != nil { - return nil, errors.Wrap(err, "error encoding the data") + return nil, fmt.Errorf("error encoding the data: %w", err) } goTypeName := goTypeName(name) @@ -96,12 +95,12 @@ func CreateAsset(license string, beat string, name string, pkg string, data []by GoTypeName: goTypeName, }) if err != nil { - return nil, errors.Wrap(err, "error creating golang file from template") + return nil, fmt.Errorf("error creating golang file from template: %w", err) } bs, err := format.Source(buf.Bytes()) if err != nil { - return nil, errors.Wrap(err, "error formatting golang file from template") + return nil, fmt.Errorf("error formatting golang file from template: %w", err) } return bs, nil diff --git a/libbeat/autodiscover/appenders/config/config.go b/libbeat/autodiscover/appenders/config/config.go index d9dcf8c49a9e..472a4986b063 100644 --- a/libbeat/autodiscover/appenders/config/config.go +++ b/libbeat/autodiscover/appenders/config/config.go @@ -20,8 +20,6 @@ package config import ( "fmt" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/autodiscover" "github.com/elastic/beats/v7/libbeat/autodiscover/template" "github.com/elastic/beats/v7/libbeat/common/cfgwarn" @@ -61,7 +59,7 @@ func NewConfigAppender(cfg *conf.C) (autodiscover.Appender, error) { if config.ConditionConfig != nil { cond, err = conditions.NewCondition(config.ConditionConfig) if err != nil { - return nil, errors.Wrap(err, "unable to create condition due to error") + return nil, fmt.Errorf("unable to create condition due to error: %w", err) } } @@ -69,7 +67,7 @@ func NewConfigAppender(cfg *conf.C) (autodiscover.Appender, error) { cf := mapstr.M{} err = config.Config.Unpack(&cf) if err != nil { - return nil, errors.Wrap(err, "unable to unpack config due to error") + return nil, fmt.Errorf("unable to unpack config due to error: %w", err) } return &configAppender{condition: cond, config: cf}, nil diff --git a/libbeat/autodiscover/providers/jolokia/discovery.go b/libbeat/autodiscover/providers/jolokia/discovery.go index 20fc379a91eb..cf0f1f5199d3 100644 --- a/libbeat/autodiscover/providers/jolokia/discovery.go +++ b/libbeat/autodiscover/providers/jolokia/discovery.go @@ -19,13 +19,13 @@ package jolokia import ( "encoding/json" + "fmt" "net" "strings" "sync" "time" "github.com/gofrs/uuid" - "github.com/pkg/errors" s "github.com/elastic/beats/v7/libbeat/common/schema" c "github.com/elastic/beats/v7/libbeat/common/schema/mapstriface" @@ -187,7 +187,7 @@ func matchInterfaceName(name, candidate string) bool { func getIPv4Addr(i net.Interface) (net.IP, error) { addrs, err := i.Addrs() if err != nil { - return nil, errors.Wrap(err, "failed to get addresses for "+i.Name) + return nil, fmt.Errorf("failed to get addresses for "+i.Name+": %w", err) } for _, a := range addrs { if ip, _, err := net.ParseCIDR(a.String()); err == nil && ip != nil { diff --git a/libbeat/autodiscover/providers/jolokia/jolokia.go b/libbeat/autodiscover/providers/jolokia/jolokia.go index 594fed24bc01..beb566805c44 100644 --- a/libbeat/autodiscover/providers/jolokia/jolokia.go +++ b/libbeat/autodiscover/providers/jolokia/jolokia.go @@ -21,7 +21,6 @@ import ( "fmt" "github.com/gofrs/uuid" - "github.com/pkg/errors" "github.com/elastic/beats/v7/libbeat/autodiscover" "github.com/elastic/beats/v7/libbeat/autodiscover/template" @@ -61,7 +60,7 @@ func AutodiscoverBuilder( keystore keystore.Keystore, ) (autodiscover.Provider, error) { errWrap := func(err error) error { - return errors.Wrap(err, "error setting up jolokia autodiscover provider") + return fmt.Errorf("error setting up jolokia autodiscover provider: %w", err) } config := defaultConfig() diff --git a/libbeat/cfgfile/factories.go b/libbeat/cfgfile/factories.go index c7d97a980025..e85260e22692 100644 --- a/libbeat/cfgfile/factories.go +++ b/libbeat/cfgfile/factories.go @@ -18,7 +18,7 @@ package cfgfile import ( - "github.com/pkg/errors" + "errors" "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/elastic-agent-libs/config" diff --git a/libbeat/cfgfile/glob_manager.go b/libbeat/cfgfile/glob_manager.go index e73dc3b56b1b..47aeb505fdb5 100644 --- a/libbeat/cfgfile/glob_manager.go +++ b/libbeat/cfgfile/glob_manager.go @@ -18,12 +18,12 @@ package cfgfile import ( + "errors" + "fmt" "os" "path/filepath" "sort" "strings" - - "github.com/pkg/errors" ) // GlobManager allows to manage a directory of conf files. Using a glob pattern @@ -155,7 +155,7 @@ func (g *GlobManager) Enable(name string) error { if !file.Enabled { newPath := strings.TrimSuffix(file.Path, g.disabledExtension) if err := os.Rename(file.Path, newPath); err != nil { - return errors.Wrap(err, "enable failed") + return fmt.Errorf("enable failed: %w", err) } file.Enabled = true file.Path = newPath @@ -164,7 +164,7 @@ func (g *GlobManager) Enable(name string) error { } } - return errors.Errorf("module %s not found", name) + return fmt.Errorf("module %s not found", name) } // Disable given conf file, does nothing if it's disabled already @@ -174,7 +174,7 @@ func (g *GlobManager) Disable(name string) error { if file.Enabled { newPath := file.Path + g.disabledExtension if err := os.Rename(file.Path, newPath); err != nil { - return errors.Wrap(err, "disable failed") + return fmt.Errorf("disable failed: %w", err) } file.Enabled = false file.Path = newPath @@ -183,7 +183,7 @@ func (g *GlobManager) Disable(name string) error { } } - return errors.Errorf("module %s not found", name) + return fmt.Errorf("module %s not found", name) } // For sorting config files in the desired order, so variants will diff --git a/libbeat/cloudid/cloudid.go b/libbeat/cloudid/cloudid.go index a0a25864ebf4..4d2dcd07d728 100644 --- a/libbeat/cloudid/cloudid.go +++ b/libbeat/cloudid/cloudid.go @@ -21,12 +21,11 @@ package cloudid import ( "encoding/base64" + "errors" "fmt" "net/url" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/logp" ) @@ -81,12 +80,12 @@ func (c *CloudID) Password() string { func (c *CloudID) decode() error { var err error if err = c.decodeCloudID(); err != nil { - return errors.Wrapf(err, "invalid cloud id '%v'", c.id) + return fmt.Errorf("invalid cloud id '%v': %w", c.id, err) } if c.auth != "" { if err = c.decodeCloudAuth(); err != nil { - return errors.Wrap(err, "invalid cloud auth") + return fmt.Errorf("invalid cloud auth: %w", err) } } @@ -106,13 +105,13 @@ func (c *CloudID) decodeCloudID() error { // 2. base64 decode decoded, err := base64.StdEncoding.DecodeString(cloudID) if err != nil { - return errors.Wrapf(err, "base64 decoding failed on %s", cloudID) + return fmt.Errorf("base64 decoding failed on %s: %w", cloudID, err) } // 3. separate based on `$` words := strings.Split(string(decoded), "$") if len(words) < 3 { - return errors.Errorf("Expected at least 3 parts in %s", string(decoded)) + return fmt.Errorf("Expected at least 3 parts in %s", string(decoded)) } // 4. extract port from the ES and Kibana host, or use 443 as the default @@ -166,7 +165,7 @@ func OverwriteSettings(cfg *config.C) error { // cloudID overwrites cid, err := NewCloudID(cloudID, cloudAuth) if err != nil { - return errors.Errorf("Error decoding cloud.id: %v", err) + return fmt.Errorf("Error decoding cloud.id: %w", err) } logger.Infof("Setting Elasticsearch and Kibana URLs based on the cloud id: output.elasticsearch.hosts=%s and setup.kibana.host=%s", cid.esURL, cid.kibURL) @@ -184,7 +183,7 @@ func OverwriteSettings(cfg *config.C) error { return err } if out := tmp.Output; out.IsSet() && out.Name() != "elasticsearch" { - return errors.Errorf("The cloud.id setting enables the Elasticsearch output, but you already have the %s output enabled in the config", out.Name()) + return fmt.Errorf("The cloud.id setting enables the Elasticsearch output, but you already have the %s output enabled in the config", out.Name()) } err = cfg.SetChild("output.elasticsearch.hosts", -1, esURLConfig) diff --git a/libbeat/common/capabilities_linux.go b/libbeat/common/capabilities_linux.go index da7e2dc55792..b2992c251ef8 100644 --- a/libbeat/common/capabilities_linux.go +++ b/libbeat/common/capabilities_linux.go @@ -20,7 +20,8 @@ package common import ( - "github.com/pkg/errors" + "errors" + "fmt" "github.com/elastic/go-sysinfo" "github.com/elastic/go-sysinfo/types" @@ -50,12 +51,15 @@ func (c Capabilities) Check(set []string) bool { func GetCapabilities() (Capabilities, error) { p, err := sysinfo.Self() if err != nil { - return Capabilities{}, errors.Wrap(err, "failed to read self process information") + return Capabilities{}, fmt.Errorf("failed to read self process information: %w", err) } if c, ok := p.(types.Capabilities); ok { capabilities, err := c.Capabilities() - return Capabilities(*capabilities), errors.Wrap(err, "failed to read process capabilities") + if err != nil { + return Capabilities{}, fmt.Errorf("failed to read process capabilities: %w", err) + } + return Capabilities(*capabilities), nil } return Capabilities{}, errors.New("capabilities not available") diff --git a/libbeat/common/cfgtype/timezone.go b/libbeat/common/cfgtype/timezone.go index db49eb4d5063..7f5635f258e1 100644 --- a/libbeat/common/cfgtype/timezone.go +++ b/libbeat/common/cfgtype/timezone.go @@ -19,10 +19,9 @@ package cfgtype import ( "encoding/json" + "fmt" "time" - "github.com/pkg/errors" - // Embed the timezone database so this code works across platforms. _ "time/tzdata" ) @@ -39,7 +38,7 @@ type Timezone time.Location func NewTimezone(tz string) (*Timezone, error) { loc, err := loadLocation(tz) if err != nil { - return nil, errors.Wrapf(err, "failed to parse timezone %q", tz) + return nil, fmt.Errorf("failed to parse timezone %q: %w", tz, err) } return (*Timezone)(loc), nil } diff --git a/libbeat/common/cli/confirm.go b/libbeat/common/cli/confirm.go index 5129071a7fa6..7028561abe28 100644 --- a/libbeat/common/cli/confirm.go +++ b/libbeat/common/cli/confirm.go @@ -19,12 +19,11 @@ package cli import ( "bufio" + "errors" "fmt" "io" "os" "strings" - - "github.com/pkg/errors" ) // Confirm shows the confirmation text and ask the user to answer (y/n) diff --git a/libbeat/common/cli/input.go b/libbeat/common/cli/input.go index 7025f63f2aaa..0d5163e4ec15 100644 --- a/libbeat/common/cli/input.go +++ b/libbeat/common/cli/input.go @@ -23,7 +23,7 @@ import ( "io" "os" - "github.com/pkg/errors" + "errors" ) // ReadInput shows the text and ask the user to provide input. diff --git a/libbeat/common/cli/password.go b/libbeat/common/cli/password.go index c139f58f3b4f..c9546a354c35 100644 --- a/libbeat/common/cli/password.go +++ b/libbeat/common/cli/password.go @@ -23,7 +23,8 @@ import ( "strings" "syscall" - "github.com/pkg/errors" + "errors" + "golang.org/x/crypto/ssh/terminal" ) @@ -63,7 +64,7 @@ func stdin(p string) (string, error) { fmt.Print("Enter password: ") bytePassword, err := terminal.ReadPassword(int(syscall.Stdin)) if err != nil { - return "", errors.Wrap(err, "reading password input") + return "", fmt.Errorf("reading password input: %w", err) } fmt.Println() return string(bytePassword), nil diff --git a/libbeat/common/event.go b/libbeat/common/event.go index 081a0269cc1b..5b2763463e25 100644 --- a/libbeat/common/event.go +++ b/libbeat/common/event.go @@ -26,8 +26,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-libs/mapstr" ) @@ -175,7 +173,7 @@ func (e *GenericEventConverter) normalizeValue(value interface{}, keys ...string } text, err := value.(encoding.TextMarshaler).MarshalText() if err != nil { - return nil, []error{errors.Wrapf(err, "key=%v: error converting %T to string", joinKeys(keys...), value)} + return nil, []error{fmt.Errorf("key=%v: error converting %T to string: %w", joinKeys(keys...), value, err)} } return string(text), nil case string, []string: @@ -243,7 +241,7 @@ func (e *GenericEventConverter) normalizeValue(value interface{}, keys ...string var m mapstr.M err := marshalUnmarshal(value, &m) if err != nil { - return m, []error{errors.Wrapf(err, "key=%v: error converting %T to mapstr.M", joinKeys(keys...), value)} + return m, []error{fmt.Errorf("key=%v: error converting %T to mapstr.M: %w", joinKeys(keys...), value, err)} } return m, nil default: @@ -262,11 +260,11 @@ func marshalUnmarshal(in interface{}, out interface{}) error { // Decode and encode as JSON to normalized the types. marshaled, err := json.Marshal(in) if err != nil { - return errors.Wrap(err, "error marshalling to JSON") + return fmt.Errorf("error marshalling to JSON: %w", err) } err = json.Unmarshal(marshaled, out) if err != nil { - return errors.Wrap(err, "error unmarshalling from JSON") + return fmt.Errorf("error unmarshalling from JSON: %w", err) } return nil diff --git a/libbeat/common/fmtstr/formatevents.go b/libbeat/common/fmtstr/formatevents.go index 82c3b4cc3141..68477073da21 100644 --- a/libbeat/common/fmtstr/formatevents.go +++ b/libbeat/common/fmtstr/formatevents.go @@ -19,6 +19,7 @@ package fmtstr import ( "bytes" + "errors" "fmt" "reflect" "strconv" @@ -26,8 +27,6 @@ import ( "sync" "time" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/beats/v7/libbeat/common" "github.com/elastic/beats/v7/libbeat/common/dtfmt" @@ -420,7 +419,7 @@ func fieldString(event *beat.Event, field string) (string, error) { s, err := tryConvString(v) if err != nil { - return s, errors.Wrapf(err, "can not convert key '%v' value to string", v) + return s, fmt.Errorf("can not convert key '%v' value to string: %w", v, err) } return s, nil } diff --git a/libbeat/common/schema/options_test.go b/libbeat/common/schema/options_test.go index 551f3aee5871..3b99117f313a 100644 --- a/libbeat/common/schema/options_test.go +++ b/libbeat/common/schema/options_test.go @@ -20,8 +20,9 @@ package schema import ( "testing" + "errors" + "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/elastic/elastic-agent-libs/mapstr" diff --git a/libbeat/common/schema/schema_test.go b/libbeat/common/schema/schema_test.go index 21cd98c78978..7e0b68583b4a 100644 --- a/libbeat/common/schema/schema_test.go +++ b/libbeat/common/schema/schema_test.go @@ -20,7 +20,8 @@ package schema import ( "testing" - "github.com/pkg/errors" + "errors" + "github.com/stretchr/testify/assert" "github.com/elastic/elastic-agent-libs/mapstr" diff --git a/libbeat/common/seccomp/seccomp.go b/libbeat/common/seccomp/seccomp.go index c711c89bf173..8dfdf41edec3 100644 --- a/libbeat/common/seccomp/seccomp.go +++ b/libbeat/common/seccomp/seccomp.go @@ -18,9 +18,10 @@ package seccomp import ( + "fmt" "runtime" - "github.com/pkg/errors" + "errors" "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/logp" @@ -56,7 +57,7 @@ func MustRegisterPolicy(p *seccomp.Policy) { // Ensure that the policy is valid and usable. if _, err := p.Assemble(); err != nil { - panic(errors.Wrap(err, "failed to register seccomp policy")) + panic(fmt.Errorf("failed to register seccomp policy: %w", err)) } registeredPolicy = p } diff --git a/libbeat/conditions/network.go b/libbeat/conditions/network.go index 1e34bdf1db60..76ab2d08423c 100644 --- a/libbeat/conditions/network.go +++ b/libbeat/conditions/network.go @@ -22,8 +22,6 @@ import ( "net" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-libs/mapstr" ) @@ -194,9 +192,12 @@ func (c *Network) String() string { // parseCIDR parses a network CIDR. func parseCIDR(value string) (*net.IPNet, error) { _, mask, err := net.ParseCIDR(value) - return mask, errors.Wrap(err, "failed to parse CIDR, values must be "+ - "an IP address and prefix length, like '192.0.2.0/24' or "+ - "'2001:db8::/32', as defined in RFC 4632 and RFC 4291.") + if err != nil { + return mask, fmt.Errorf("failed to parse CIDR, values must be "+ + "an IP address and prefix length, like '192.0.2.0/24' or "+ + "'2001:db8::/32', as defined in RFC 4632 and RFC 4291: %w", err) + } + return mask, nil } // extractIP return an IP address if unk is an IP address string or a net.IP. diff --git a/libbeat/dashboards/dashboards.go b/libbeat/dashboards/dashboards.go index 9eb236765be2..90004321eca0 100644 --- a/libbeat/dashboards/dashboards.go +++ b/libbeat/dashboards/dashboards.go @@ -23,8 +23,6 @@ import ( "fmt" "path/filepath" - errw "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/mapstr" @@ -91,7 +89,7 @@ func ImportDashboardsViaKibana(kibanaLoader *KibanaLoader, fields mapstr.M) erro } if err := importer.Import(); err != nil { - return errw.Wrap(err, "fail to import the dashboards in Kibana") + return fmt.Errorf("fail to import the dashboards in Kibana: %w", err) } return nil diff --git a/libbeat/dashboards/export.go b/libbeat/dashboards/export.go index a044c7d85adf..54aace94aaa3 100644 --- a/libbeat/dashboards/export.go +++ b/libbeat/dashboards/export.go @@ -29,7 +29,6 @@ import ( "path/filepath" "strconv" - "github.com/pkg/errors" "gopkg.in/yaml.v2" "github.com/elastic/elastic-agent-libs/kibana" @@ -64,15 +63,15 @@ func Export(client *kibana.Client, id string) ([]byte, error) { func ExportAllFromYml(client *kibana.Client, ymlPath string) ([][]byte, ListYML, error) { b, err := ioutil.ReadFile(ymlPath) if err != nil { - return nil, ListYML{}, errors.Wrap(err, "error opening the list of dashboards") + return nil, ListYML{}, fmt.Errorf("error opening the list of dashboards: %w", err) } var list ListYML err = yaml.Unmarshal(b, &list) if err != nil { - return nil, ListYML{}, errors.Wrap(err, "error reading the list of dashboards") + return nil, ListYML{}, fmt.Errorf("error reading the list of dashboards: %w", err) } if len(list.Dashboards) == 0 { - return nil, ListYML{}, errors.Errorf("dashboards list is empty in file %v", ymlPath) + return nil, ListYML{}, fmt.Errorf("dashboards list is empty in file %v", ymlPath) } results, err := ExportAll(client, list) @@ -86,7 +85,7 @@ func ExportAll(client *kibana.Client, list ListYML) ([][]byte, error) { for _, e := range list.Dashboards { result, err := Export(client, e.ID) if err != nil { - return nil, errors.Wrapf(err, "failed exporting id=%v", e.ID) + return nil, fmt.Errorf("failed exporting id=%v: %w", e.ID, err) } results = append(results, result) } diff --git a/libbeat/dashboards/importer.go b/libbeat/dashboards/importer.go index 6a8d1680b515..3d3658d7c83b 100644 --- a/libbeat/dashboards/importer.go +++ b/libbeat/dashboards/importer.go @@ -29,8 +29,6 @@ import ( "path/filepath" "strings" - errw "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/mapstr" "github.com/elastic/elastic-agent-libs/version" ) @@ -81,12 +79,12 @@ func (imp Importer) Import() error { if imp.cfg.URL != "" || imp.cfg.File != "" { err := imp.ImportArchive() if err != nil { - return errw.Wrap(err, "Error importing URL/file") + return fmt.Errorf("Error importing URL/file: %w", err) } } else { err := imp.ImportKibanaDir(imp.cfg.Dir) if err != nil { - return errw.Wrapf(err, "Error importing directory %s", imp.cfg.Dir) + return fmt.Errorf("Error importing directory %s: %w", imp.cfg.Dir, err) } } return nil @@ -308,7 +306,7 @@ func (imp Importer) ImportKibanaDir(dir string) error { // Loads the internal index pattern if imp.fields != nil { if err = imp.loader.ImportIndex(imp.fields); err != nil { - return errw.Wrap(err, "failed to import Kibana index pattern") + return fmt.Errorf("failed to import Kibana index pattern: %w", err) } } diff --git a/libbeat/dashboards/kibana_loader.go b/libbeat/dashboards/kibana_loader.go index 73d4189a7bfe..e13a56ca4b6e 100644 --- a/libbeat/dashboards/kibana_loader.go +++ b/libbeat/dashboards/kibana_loader.go @@ -27,7 +27,6 @@ import ( "time" "github.com/joeshaw/multierror" - "github.com/pkg/errors" beatversion "github.com/elastic/beats/v7/libbeat/version" "github.com/elastic/elastic-agent-libs/config" @@ -136,11 +135,11 @@ func (loader KibanaLoader) ImportIndex(pattern mapstr.M) error { params.Set("overwrite", "true") if err := ReplaceIndexInIndexPattern(loader.config.Index, pattern); err != nil { - errs = append(errs, errors.Wrapf(err, "error setting index '%s' in index pattern", loader.config.Index)) + errs = append(errs, fmt.Errorf("error setting index '%s' in index pattern: %w", loader.config.Index, err)) } if err := loader.client.ImportMultiPartFormFile(importAPI, params, "index-template.ndjson", pattern.String()); err != nil { - errs = append(errs, errors.Wrap(err, "error loading index pattern")) + errs = append(errs, fmt.Errorf("error loading index pattern: %w", err)) } return errs.Err() } diff --git a/libbeat/esleg/eslegclient/api.go b/libbeat/esleg/eslegclient/api.go index 91df12365b89..980c358df32f 100644 --- a/libbeat/esleg/eslegclient/api.go +++ b/libbeat/esleg/eslegclient/api.go @@ -22,8 +22,6 @@ import ( "fmt" "strconv" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/version" ) @@ -92,7 +90,7 @@ type CountResults struct { func withQueryResult(status int, resp []byte, err error) (int, *QueryResult, error) { if err != nil { - return status, nil, errors.Wrapf(err, "Elasticsearch response: %s", resp) + return status, nil, fmt.Errorf("Elasticsearch response: %s: %w", resp, err) } result, err := readQueryResult(resp) return status, result, err diff --git a/libbeat/generator/fields/validate/mapping.go b/libbeat/generator/fields/validate/mapping.go index a364511a0c90..2b372bf20040 100644 --- a/libbeat/generator/fields/validate/mapping.go +++ b/libbeat/generator/fields/validate/mapping.go @@ -18,9 +18,9 @@ package validate import ( + "fmt" "strings" - "github.com/pkg/errors" "gopkg.in/yaml.v2" ) @@ -49,11 +49,11 @@ func NewMapping(fieldsYAML []byte) (Mapping, error) { var fields interface{} if err := yaml.Unmarshal(fieldsYAML, &fields); err != nil { - return result, errors.Wrap(err, "decoding fields YAML") + return result, fmt.Errorf("decoding fields YAML: %w", err) } subFields, ok := fields.([]interface{}) if !ok { - return result, errors.Errorf("top-level fields is not an array, but %T", fields) + return result, fmt.Errorf("top-level fields is not an array, but %T", fields) } for _, subField := range subFields { if err := recursiveFattenFields(subField, "", &result, ""); err != nil { @@ -75,7 +75,7 @@ func (m *Mapping) Validate(dict map[string]interface{}) error { } for _, required := range m.Required { if _, found := docFields[required]; !found { - return errors.Errorf("required field '%s' not found", required) + return fmt.Errorf("required field '%s' not found", required) } } return nil @@ -86,11 +86,11 @@ func (m *Mapping) validateFields(dict map[string]interface{}, prefix Prefix) (se name := prefix.Append(key) field, found := m.Fields[name.String()] if !found { - return nil, errors.Errorf("field %s not found in mapping", name.String()) + return nil, fmt.Errorf("field %s not found in mapping", name.String()) } dicts, err := typeCheck(value, field.Type) if err != nil { - return nil, errors.Wrapf(err, "field %s does not match expected type %s", name.String(), field.Type) + return nil, fmt.Errorf("field %s does not match expected type %s: %w", name.String(), field.Type, err) } for _, dict := range dicts { s, err := m.validateFields(dict, name) @@ -134,7 +134,7 @@ func (m *Mapping) storeField(path string, field Field) error { } else { // Allow groups to be specified more than once if prev.Type != "group" || field.Type != "group" { - return errors.Errorf("duplicate field %s (types %s and %s)", path, prev.Type, field.Type) + return fmt.Errorf("duplicate field %s (types %s and %s)", path, prev.Type, field.Type) } } return nil @@ -143,7 +143,7 @@ func (m *Mapping) storeField(path string, field Field) error { func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, key string) error { dict, ok := fields.(map[interface{}]interface{}) if !ok { - return errors.Errorf("fields entry [%s](%s) is not a dictionary", key, prefix) + return fmt.Errorf("fields entry [%s](%s) is not a dictionary", key, prefix) } keyIf, hasKey := dict["key"] nameIf, hasName := dict["name"] @@ -157,22 +157,22 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, if hasKey { newKey, ok := keyIf.(string) if !ok { - return errors.Errorf("a 'key' field is not of type string, but %T (value=%v)", keyIf, keyIf) + return fmt.Errorf("a 'key' field is not of type string, but %T (value=%v)", keyIf, keyIf) } if len(key) > 0 { - return errors.Errorf("unexpected 'key' field in [%s](%s). Keys can only be defined at top level", key, prefix) + return fmt.Errorf("unexpected 'key' field in [%s](%s). Keys can only be defined at top level", key, prefix) } key = newKey } else { if len(key) == 0 { - return errors.Errorf("found top-level fields entry without a 'key' field") + return fmt.Errorf("found top-level fields entry without a 'key' field") } } if hasName { name, ok = nameIf.(string) if !ok { - return errors.Errorf("a field in [%s](%s) has a 'name' entry of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) + return fmt.Errorf("a field in [%s](%s) has a 'name' entry of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) } prefix = prefix.Append(name) } else { @@ -181,14 +181,14 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, // Ignore fields that have no name or key, but a release. Used in metricbeat to document some modules. return nil } - return errors.Errorf("field [%s](%s) has a sub-field without 'name' nor 'key'", key, prefix) + return fmt.Errorf("field [%s](%s) has a sub-field without 'name' nor 'key'", key, prefix) } } if hasType { typ, ok = typIf.(string) if !ok { - return errors.Errorf("field [%s](%s) has a 'type' entry of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) + return fmt.Errorf("field [%s](%s) has a 'type' entry of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) } if typ == "object" { typ = "group" @@ -198,7 +198,7 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, if hasRequired { required, ok = requiredIf.(bool) if !ok { - return errors.Errorf("field [%s](%s) has 'required' property but is not a boolean, but %T (value=%v)", key, prefix, requiredIf, requiredIf) + return fmt.Errorf("field [%s](%s) has 'required' property but is not a boolean, but %T (value=%v)", key, prefix, requiredIf, requiredIf) } } @@ -211,7 +211,7 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, path := prefix.String() if err := mapping.addField(path, Field{Type: typ}, required); err != nil { - return errors.Wrapf(err, "adding field [%s](%s)", key, path) + return fmt.Errorf("adding field [%s](%s): %w", key, path, err) } return nil } @@ -219,7 +219,7 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, // Parse a group if hasType && typ != "group" { - return errors.Errorf("field [%s](%s) has a 'fields' tag but type is not group (type=%s)", key, prefix, typ) + return fmt.Errorf("field [%s](%s) has a 'fields' tag but type is not group (type=%s)", key, prefix, typ) } if !hasType { typ = "group" @@ -228,14 +228,14 @@ func recursiveFattenFields(fields interface{}, prefix Prefix, mapping *Mapping, if hasName { path := prefix.String() if err := mapping.addField(path, Field{Type: typ}, required); err != nil { - return errors.Wrapf(err, "adding field [%s](%s)", key, path) + return fmt.Errorf("adding field [%s](%s): %w", key, path, err) } } if fieldsIf != nil { innerFields, ok := fieldsIf.([]interface{}) if !ok { - return errors.Errorf("field [%s](%s) has a 'fields' tag of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) + return fmt.Errorf("field [%s](%s) has a 'fields' tag of unexpected type (type=%T value=%v)", key, prefix, nameIf, nameIf) } for _, field := range innerFields { if err := recursiveFattenFields(field, prefix, mapping, key); err != nil { diff --git a/libbeat/generator/fields/validate/validate.go b/libbeat/generator/fields/validate/validate.go index 79d7f15cf188..f4ee1d954292 100644 --- a/libbeat/generator/fields/validate/validate.go +++ b/libbeat/generator/fields/validate/validate.go @@ -19,8 +19,7 @@ package validate import ( "encoding/json" - - "github.com/pkg/errors" + "fmt" ) // Document takes a document from Elasticsearch in JSON format @@ -29,12 +28,12 @@ import ( func Document(docJSON []byte, fieldsYAML []byte) error { var ifDocument interface{} if err := json.Unmarshal(docJSON, &ifDocument); err != nil { - return errors.Wrap(err, "decoding JSON document") + return fmt.Errorf("decoding JSON document: %w", err) } document, ok := ifDocument.(map[string]interface{}) if !ok { - return errors.Errorf("document must be a dictionary of string keys, but %T", ifDocument) + return fmt.Errorf("document must be a dictionary of string keys, but %T", ifDocument) } fields, err := NewMapping(fieldsYAML) diff --git a/libbeat/idxmgmt/ilm/ilm.go b/libbeat/idxmgmt/ilm/ilm.go index 17fff18d376e..bd67c186f212 100644 --- a/libbeat/idxmgmt/ilm/ilm.go +++ b/libbeat/idxmgmt/ilm/ilm.go @@ -19,11 +19,11 @@ package ilm import ( "encoding/json" + "errors" + "fmt" "io/ioutil" "time" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/beats/v7/libbeat/common/fmtstr" "github.com/elastic/elastic-agent-libs/config" @@ -98,7 +98,7 @@ func StdSupport(log *logp.Logger, info beat.Info, c *config.C) (Supporter, error name, err := applyStaticFmtstr(info, &cfg.PolicyName) if err != nil { - return nil, errors.Wrap(err, "failed to read ilm policy name") + return nil, errors.New("failed to read ilm policy name") } policy := Policy{ @@ -108,12 +108,12 @@ func StdSupport(log *logp.Logger, info beat.Info, c *config.C) (Supporter, error if path := cfg.PolicyFile; path != "" { contents, err := ioutil.ReadFile(path) if err != nil { - return nil, errors.Wrapf(err, "failed to read policy file '%v'", path) + return nil, fmt.Errorf("failed to read policy file '%v': %w", path, err) } var body map[string]interface{} if err := json.Unmarshal(contents, &body); err != nil { - return nil, errors.Wrapf(err, "failed to decode policy file '%v'", path) + return nil, fmt.Errorf("failed to decode policy file '%v': %w", path, err) } policy.Body = body diff --git a/libbeat/licenser/elastic_fetcher.go b/libbeat/licenser/elastic_fetcher.go index 0e8a181ae111..bcbe68a938f9 100644 --- a/libbeat/licenser/elastic_fetcher.go +++ b/libbeat/licenser/elastic_fetcher.go @@ -19,12 +19,11 @@ package licenser import ( "encoding/json" + "errors" "fmt" "math/rand" "net/http" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/esleg/eslegclient" "github.com/elastic/elastic-agent-libs/logp" ) diff --git a/libbeat/mapping/field.go b/libbeat/mapping/field.go index 7615c5c39e68..c1264db26d2c 100644 --- a/libbeat/mapping/field.go +++ b/libbeat/mapping/field.go @@ -18,11 +18,11 @@ package mapping import ( + "errors" "fmt" "strings" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/elastic/elastic-agent-libs/mapstr" "github.com/elastic/go-ucfg/yaml" @@ -158,7 +158,7 @@ func (a *Analyzer) Unpack(v interface{}) error { // Validate ensures objectTypeParams are not mixed with top level objectType configuration func (f *Field) Validate() error { if err := f.validateType(); err != nil { - return errors.Wrapf(err, "incorrect type configuration for field '%s'", f.Name) + return fmt.Errorf("incorrect type configuration for field '%s': %w", f.Name, err) } if len(f.ObjectTypeParams) > 0 { if f.ScalingFactor != 0 || f.ObjectTypeMappingType != "" || f.ObjectType != "" { @@ -468,12 +468,12 @@ func (f Fields) canConcat(k string, keys []string) error { } // last key to compare if len(keys) == 0 { - return errors.Errorf("fields contain key <%s>", k) + return fmt.Errorf("fields contain key <%s>", k) } // last field to compare, only valid if it is of type object if len(field.Fields) == 0 { if field.Type != "object" { - return errors.Errorf("fields contain non object node conflicting with key <%s>", k) + return fmt.Errorf("fields contain non object node conflicting with key <%s>", k) } } return field.Fields.canConcat(k, keys) diff --git a/libbeat/monitoring/report/report.go b/libbeat/monitoring/report/report.go index 6a3361d79797..c505c5acbdb3 100644 --- a/libbeat/monitoring/report/report.go +++ b/libbeat/monitoring/report/report.go @@ -21,8 +21,6 @@ import ( "errors" "fmt" - errw "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/beat" conf "github.com/elastic/elastic-agent-libs/config" ) @@ -150,14 +148,14 @@ func mergeHosts(merged, outCfg, reporterCfg *conf.C) error { outputHosts := hostsCfg{} if outCfg != nil { if err := outCfg.Unpack(&outputHosts); err != nil { - return errw.Wrap(err, "unable to parse hosts from output config") + return fmt.Errorf("unable to parse hosts from output config: %w", err) } } reporterHosts := hostsCfg{} if reporterCfg != nil { if err := reporterCfg.Unpack(&reporterHosts); err != nil { - return errw.Wrap(err, "unable to parse hosts from reporter config") + return fmt.Errorf("unable to parse hosts from reporter config: %w", err) } } @@ -174,11 +172,11 @@ func mergeHosts(merged, outCfg, reporterCfg *conf.C) error { newHostsCfg, err = conf.NewConfigFrom(outputHosts.Hosts) } if err != nil { - return errw.Wrap(err, "unable to make config from new hosts") + return fmt.Errorf("unable to make config from new hosts: %w", err) } if err := merged.SetChild("hosts", -1, newHostsCfg); err != nil { - return errw.Wrap(err, "unable to set new hosts into merged config") + return fmt.Errorf("unable to set new hosts into merged config: %w", err) } return nil } diff --git a/libbeat/processors/add_cloud_metadata/http_fetcher.go b/libbeat/processors/add_cloud_metadata/http_fetcher.go index 54edd81aad1d..4ca27f53d4a0 100644 --- a/libbeat/processors/add_cloud_metadata/http_fetcher.go +++ b/libbeat/processors/add_cloud_metadata/http_fetcher.go @@ -21,11 +21,10 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io/ioutil" "net/http" - "github.com/pkg/errors" - cfg "github.com/elastic/elastic-agent-libs/config" "github.com/elastic/elastic-agent-libs/mapstr" "github.com/elastic/elastic-agent-libs/transport/tlscommon" @@ -91,7 +90,7 @@ func (f *httpMetadataFetcher) fetchRaw( ) { req, err := http.NewRequest("GET", url, nil) if err != nil { - result.err = errors.Wrapf(err, "failed to create http request for %v", f.provider) + result.err = fmt.Errorf("failed to create http request for %v: %w", f.provider, err) return } for k, v := range f.headers { @@ -101,19 +100,19 @@ func (f *httpMetadataFetcher) fetchRaw( rsp, err := client.Do(req) if err != nil { - result.err = errors.Wrapf(err, "failed requesting %v metadata", f.provider) + result.err = fmt.Errorf("failed requesting %v metadata: %w", f.provider, err) return } defer rsp.Body.Close() if rsp.StatusCode != http.StatusOK { - result.err = errors.Errorf("failed with http status code %v", rsp.StatusCode) + result.err = fmt.Errorf("failed with http status code %v", rsp.StatusCode) return } all, err := ioutil.ReadAll(rsp.Body) if err != nil { - result.err = errors.Wrapf(err, "failed requesting %v metadata", f.provider) + result.err = fmt.Errorf("failed requesting %v metadata: %w", f.provider, err) return } @@ -143,7 +142,7 @@ func getMetadataURLsWithScheme(c *cfg.C, scheme string, defaultHost string, meta } err := c.Unpack(&config) if err != nil { - return urls, errors.Wrap(err, "failed to unpack add_cloud_metadata config") + return urls, fmt.Errorf("failed to unpack add_cloud_metadata config: %w", err) } for _, uri := range metadataURIs { urls = append(urls, scheme+"://"+config.MetadataHostAndPort+uri) @@ -159,7 +158,7 @@ func makeJSONPicker(provider string) responseHandler { dec.UseNumber() err := dec.Decode(&res.metadata) if err != nil { - err = errors.Wrapf(err, "failed to unmarshal %v JSON of '%v'", provider, string(all)) + err = fmt.Errorf("failed to unmarshal %v JSON of '%v': %w", provider, string(all), err) return err } return nil diff --git a/libbeat/processors/add_process_metadata/add_process_metadata_test.go b/libbeat/processors/add_process_metadata/add_process_metadata_test.go index d833a188fc04..cd2042d8b89e 100644 --- a/libbeat/processors/add_process_metadata/add_process_metadata_test.go +++ b/libbeat/processors/add_process_metadata/add_process_metadata_test.go @@ -18,13 +18,13 @@ package add_process_metadata import ( + "errors" "math" "os" "testing" "time" "unsafe" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/elastic/beats/v7/libbeat/beat" diff --git a/libbeat/processors/add_process_metadata/config.go b/libbeat/processors/add_process_metadata/config.go index dc8ce612da0d..447cf87ea3a5 100644 --- a/libbeat/processors/add_process_metadata/config.go +++ b/libbeat/processors/add_process_metadata/config.go @@ -22,8 +22,6 @@ import ( "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/mapstr" ) @@ -131,13 +129,13 @@ func (pf *config) getMappings() (mappings mapstr.M, err error) { key := dstField + "." + subField val := docSrc + "." + subField if _, err = mappings.Put(key, val); err != nil { - return nil, errors.Wrapf(err, "failed to set mapping '%v' -> '%v'", dstField, docSrc) + return nil, fmt.Errorf("failed to set mapping '%v' -> '%v': %w", dstField, docSrc, err) } } } else { prev, err := mappings.Put(dstField, docSrc) if err != nil { - return nil, errors.Wrapf(err, "failed to set mapping '%v' -> '%v'", dstField, docSrc) + return nil, fmt.Errorf("failed to set mapping '%v' -> '%v': %w", dstField, docSrc, err) } if prev != nil { return nil, fmt.Errorf("field '%v' repeated", docSrc) diff --git a/libbeat/processors/add_process_metadata/gosigar_cid_provider.go b/libbeat/processors/add_process_metadata/gosigar_cid_provider.go index cc1063635b20..5499b95a142f 100644 --- a/libbeat/processors/add_process_metadata/gosigar_cid_provider.go +++ b/libbeat/processors/add_process_metadata/gosigar_cid_provider.go @@ -18,13 +18,12 @@ package add_process_metadata import ( + "fmt" "os" "path/filepath" "regexp" "strings" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/common" "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-system-metrics/metric/system/cgroup" @@ -98,7 +97,7 @@ func (p gosigarCidProvider) getProcessCgroups(pid int) (cgroup.PathList, error) // or not running in linux system default: // should never happen - return cgroup, errors.Wrapf(err, "failed to read cgroups for pid=%v", pid) + return cgroup, fmt.Errorf("failed to read cgroups for pid=%v: %w", pid, err) } return cgroup, nil diff --git a/libbeat/processors/dissect/config.go b/libbeat/processors/dissect/config.go index 4f6aa8e74345..0568a1dc8185 100644 --- a/libbeat/processors/dissect/config.go +++ b/libbeat/processors/dissect/config.go @@ -18,9 +18,8 @@ package dissect import ( + "fmt" "strings" - - "github.com/pkg/errors" ) type trimMode byte @@ -73,7 +72,7 @@ func (tm *trimMode) Unpack(v string) error { case "all", "both": *tm = trimModeAll default: - return errors.Errorf("unsupported value %s. Must be one of [none, left, right, all]", v) + return fmt.Errorf("unsupported value %s. Must be one of [none, left, right, all]", v) } return nil } diff --git a/libbeat/processors/dissect/dissect.go b/libbeat/processors/dissect/dissect.go index e1e657b28a58..9a1021813d1f 100644 --- a/libbeat/processors/dissect/dissect.go +++ b/libbeat/processors/dissect/dissect.go @@ -18,13 +18,12 @@ package dissect import ( + "errors" "fmt" "net" "strconv" "strings" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/mapstr" ) diff --git a/libbeat/processors/dns/config.go b/libbeat/processors/dns/config.go index 4b585a1d1776..fb8a13eaf216 100644 --- a/libbeat/processors/dns/config.go +++ b/libbeat/processors/dns/config.go @@ -18,12 +18,11 @@ package dns import ( + "fmt" "strconv" "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/mapstr" ) @@ -71,7 +70,7 @@ func (fa *FieldAction) Unpack(v string) error { case "replace": *fa = ActionReplace default: - return errors.Errorf("invalid dns field action value '%v'", v) + return fmt.Errorf("invalid dns field action value '%v'", v) } return nil } @@ -106,7 +105,7 @@ func (c *Config) Validate() error { switch c.Type { case "reverse": default: - return errors.Errorf("invalid dns lookup type '%v' specified in "+ + return fmt.Errorf("invalid dns lookup type '%v' specified in "+ "config (valid values are: reverse)", c.Type) } @@ -115,7 +114,7 @@ func (c *Config) Validate() error { for k, v := range c.Fields.Flatten() { target, ok := v.(string) if !ok { - return errors.Errorf("target field for dns lookup of %v "+ + return fmt.Errorf("target field for dns lookup of %v "+ "must be a string but got %T", k, v) } c.reverseFlat[k] = target @@ -126,7 +125,7 @@ func (c *Config) Validate() error { case "tls": case "udp": default: - return errors.Errorf("invalid transport method type '%v' specified in "+ + return fmt.Errorf("invalid transport method type '%v' specified in "+ "config (valid value is: tls or udp)", c.Transport) } return nil @@ -135,24 +134,24 @@ func (c *Config) Validate() error { // Validate validates the data contained in the CacheConfig. func (c *CacheConfig) Validate() error { if c.SuccessCache.MinTTL <= 0 { - return errors.Errorf("success_cache.min_ttl must be > 0") + return fmt.Errorf("success_cache.min_ttl must be > 0") } if c.FailureCache.TTL <= 0 { - return errors.Errorf("failure_cache.ttl must be > 0") + return fmt.Errorf("failure_cache.ttl must be > 0") } if c.SuccessCache.MaxCapacity <= 0 { - return errors.Errorf("success_cache.capacity.max must be > 0") + return fmt.Errorf("success_cache.capacity.max must be > 0") } if c.FailureCache.MaxCapacity <= 0 { - return errors.Errorf("failure_cache.capacity.max must be > 0") + return fmt.Errorf("failure_cache.capacity.max must be > 0") } if c.SuccessCache.MaxCapacity < c.SuccessCache.InitialCapacity { - return errors.Errorf("success_cache.capacity.max must be >= success_cache.capacity.initial") + return fmt.Errorf("success_cache.capacity.max must be >= success_cache.capacity.initial") } if c.FailureCache.MaxCapacity < c.FailureCache.InitialCapacity { - return errors.Errorf("failure_cache.capacity.max must be >= failure_cache.capacity.initial") + return fmt.Errorf("failure_cache.capacity.max must be >= failure_cache.capacity.initial") } return nil diff --git a/libbeat/processors/dns/resolver.go b/libbeat/processors/dns/resolver.go index 71ccea6c8ce3..7e0f160315cb 100644 --- a/libbeat/processors/dns/resolver.go +++ b/libbeat/processors/dns/resolver.go @@ -18,6 +18,7 @@ package dns import ( + "errors" "net" "strconv" "strings" @@ -25,7 +26,6 @@ import ( "time" "github.com/miekg/dns" - "github.com/pkg/errors" "github.com/rcrowley/go-metrics" "github.com/elastic/elastic-agent-libs/monitoring" diff --git a/libbeat/processors/ratelimit/algorithm.go b/libbeat/processors/ratelimit/algorithm.go index 33ccac8bbde1..35603fabd189 100644 --- a/libbeat/processors/ratelimit/algorithm.go +++ b/libbeat/processors/ratelimit/algorithm.go @@ -20,8 +20,6 @@ package ratelimit import ( "fmt" - "github.com/pkg/errors" - cfg "github.com/elastic/elastic-agent-libs/config" ) @@ -63,7 +61,7 @@ func factory(id string, config algoConfig) (algorithm, error) { algorithm, err := ctor(config) if err != nil { - return nil, errors.Wrap(err, "could not construct algorithm") + return nil, fmt.Errorf("could not construct algorithm: %w", err) } return algorithm, nil diff --git a/libbeat/processors/ratelimit/token_bucket.go b/libbeat/processors/ratelimit/token_bucket.go index 97b6b89860d6..1f1381fd8dfe 100644 --- a/libbeat/processors/ratelimit/token_bucket.go +++ b/libbeat/processors/ratelimit/token_bucket.go @@ -18,11 +18,11 @@ package ratelimit import ( + "fmt" "sync" "time" "github.com/jonboulle/clockwork" - "github.com/pkg/errors" "github.com/elastic/go-concert/unison" @@ -83,7 +83,7 @@ func newTokenBucket(config algoConfig) (algorithm, error) { } if err := config.config.Unpack(&cfg); err != nil { - return nil, errors.Wrap(err, "could not unpack token_bucket algorithm configuration") + return nil, fmt.Errorf("could not unpack token_bucket algorithm configuration: %w", err) } return &tokenBucket{ diff --git a/libbeat/processors/script/javascript/beatevent_v0.go b/libbeat/processors/script/javascript/beatevent_v0.go index 19bb3d2017e1..82b011fb991e 100644 --- a/libbeat/processors/script/javascript/beatevent_v0.go +++ b/libbeat/processors/script/javascript/beatevent_v0.go @@ -18,8 +18,10 @@ package javascript import ( + "errors" + "fmt" + "github.com/dop251/goja" - "github.com/pkg/errors" "github.com/elastic/beats/v7/libbeat/beat" "github.com/elastic/elastic-agent-libs/mapstr" @@ -62,7 +64,7 @@ func newBeatEventV0Constructor(s Session) func(call goja.ConstructorCall) *goja. case mapstr.M: fields = v default: - panic(errors.Errorf("Event constructor requires a "+ + panic(fmt.Errorf("Event constructor requires a "+ "map[string]interface{} argument but got %T", a0)) } @@ -289,7 +291,7 @@ func appendString(m mapstr.M, field, value string, alwaysArray bool) error { } m.Put(field, append(v, value)) default: - return errors.Errorf("unexpected type %T found for %v field", list, field) + return fmt.Errorf("unexpected type %T found for %v field", list, field) } return nil } diff --git a/libbeat/processors/script/javascript/config.go b/libbeat/processors/script/javascript/config.go index 56d17bcfd2da..03415a96d1b2 100644 --- a/libbeat/processors/script/javascript/config.go +++ b/libbeat/processors/script/javascript/config.go @@ -18,9 +18,8 @@ package javascript import ( + "fmt" "time" - - "github.com/pkg/errors" ) // Config defines the Javascript source files to use for the processor. @@ -46,10 +45,10 @@ func (c Config) Validate() error { switch { case numConfigured == 0: - return errors.Errorf("javascript must be defined via 'file', " + + return fmt.Errorf("javascript must be defined via 'file', " + "'files', or inline as 'source'") case numConfigured > 1: - return errors.Errorf("javascript can be defined in only one of " + + return fmt.Errorf("javascript can be defined in only one of " + "'file', 'files', or inline as 'source'") } diff --git a/libbeat/processors/script/javascript/module/console/console.go b/libbeat/processors/script/javascript/module/console/console.go index 3d29c20a88b3..642343a4f498 100644 --- a/libbeat/processors/script/javascript/module/console/console.go +++ b/libbeat/processors/script/javascript/module/console/console.go @@ -18,9 +18,10 @@ package console import ( + "fmt" + "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" - "github.com/pkg/errors" "github.com/elastic/elastic-agent-libs/logp" @@ -53,7 +54,7 @@ func (c *Console) makeLogFunc(level logp.Level) func(call goja.FunctionCall) goj case logp.ErrorLevel: log.Error(ret.String()) default: - panic(errors.Errorf("unhandled logp.Level: %v", level)) + panic(fmt.Errorf("unhandled logp.Level: %v", level)) } } else { panic(c.runtime.NewTypeError("util.format is not a function")) diff --git a/libbeat/processors/script/javascript/module/processor/processor.go b/libbeat/processors/script/javascript/module/processor/processor.go index bcb360c54724..c6be88208a33 100644 --- a/libbeat/processors/script/javascript/module/processor/processor.go +++ b/libbeat/processors/script/javascript/module/processor/processor.go @@ -20,7 +20,8 @@ package processor import ( "github.com/dop251/goja" "github.com/dop251/goja_nodejs/require" - "github.com/pkg/errors" + + "errors" "github.com/elastic/beats/v7/libbeat/processors" "github.com/elastic/beats/v7/libbeat/processors/script/javascript" diff --git a/libbeat/processors/script/javascript/module/require/require.go b/libbeat/processors/script/javascript/module/require/require.go index db0dcaaa4efc..e081cac8e1d9 100644 --- a/libbeat/processors/script/javascript/module/require/require.go +++ b/libbeat/processors/script/javascript/module/require/require.go @@ -18,8 +18,9 @@ package require import ( + "fmt" + "github.com/dop251/goja_nodejs/require" - "github.com/pkg/errors" "github.com/elastic/beats/v7/libbeat/processors/script/javascript" ) @@ -33,5 +34,5 @@ func init() { // loadSource disallows loading custom modules from file. func loadSource(path string) ([]byte, error) { - return nil, errors.Errorf("cannot load %v, only built-in modules are supported", path) + return nil, fmt.Errorf("cannot load %v, only built-in modules are supported", path) } diff --git a/libbeat/processors/script/javascript/session.go b/libbeat/processors/script/javascript/session.go index 224888cfcb07..337d2eae7997 100644 --- a/libbeat/processors/script/javascript/session.go +++ b/libbeat/processors/script/javascript/session.go @@ -18,11 +18,12 @@ package javascript import ( + "errors" + "fmt" "reflect" "time" "github.com/dop251/goja" - "github.com/pkg/errors" "go.uber.org/zap" "github.com/elastic/beats/v7/libbeat/beat" @@ -145,7 +146,7 @@ func (s *session) setProcessFunction() error { return errors.New("process is not a function") } if err := s.vm.ExportTo(processFunc, &s.processFunc); err != nil { - return errors.Wrap(err, "failed to export process function") + return fmt.Errorf("failed to export process function: %w", err) } return nil } @@ -161,10 +162,10 @@ func (s *session) registerScriptParams(params map[string]interface{}) error { } var register goja.Callable if err := s.vm.ExportTo(registerFunc, ®ister); err != nil { - return errors.Wrap(err, "failed to export register function") + return fmt.Errorf("failed to export register function: %w", err) } if _, err := register(goja.Undefined(), s.Runtime().ToValue(params)); err != nil { - return errors.Wrap(err, "failed to register script_params") + return fmt.Errorf("failed to register script_params: %w", err) } s.log.Debug("Registered params with processor") return nil @@ -179,11 +180,11 @@ func (s *session) executeTestFunction() error { } var test goja.Callable if err := s.vm.ExportTo(testFunc, &test); err != nil { - return errors.Wrap(err, "failed to export test function") + return fmt.Errorf("failed to export test function: %w", err) } _, err := test(goja.Undefined(), nil) if err != nil { - return errors.Wrap(err, "failed in test() function") + return fmt.Errorf("failed in test() function: %w", err) } s.log.Debugf("Successful test() execution for processor.") } @@ -215,7 +216,7 @@ func (s *session) runProcessFunc(b *beat.Event) (out *beat.Event, err error) { if !s.evt.IsCancelled() { out = b } - err = errors.Errorf("unexpected panic in javascript processor: %v", r) + err = fmt.Errorf("unexpected panic in javascript processor: %v", r) if s.tagOnException != "" { mapstr.AddTags(b.Fields, []string{s.tagOnException}) } @@ -241,7 +242,7 @@ func (s *session) runProcessFunc(b *beat.Event) (out *beat.Event, err error) { mapstr.AddTags(b.Fields, []string{s.tagOnException}) } appendString(b.Fields, "error.message", err.Error(), false) - return b, errors.Wrap(err, "failed in process function") + return b, fmt.Errorf("failed in process function: %w", err) } if s.evt.IsCancelled() { diff --git a/libbeat/processors/translate_sid/config.go b/libbeat/processors/translate_sid/config.go index 192d8fd6e0ce..3ef316c46eeb 100644 --- a/libbeat/processors/translate_sid/config.go +++ b/libbeat/processors/translate_sid/config.go @@ -17,7 +17,7 @@ package translate_sid -import "github.com/pkg/errors" +import "errors" type config struct { Field string `config:"field" validate:"required"` diff --git a/libbeat/reader/readjson/docker_json.go b/libbeat/reader/readjson/docker_json.go index 026d91257872..5f7e97483ffc 100644 --- a/libbeat/reader/readjson/docker_json.go +++ b/libbeat/reader/readjson/docker_json.go @@ -20,12 +20,12 @@ package readjson import ( "bytes" "encoding/json" + "errors" + "fmt" "runtime" "strings" "time" - "github.com/pkg/errors" - "github.com/elastic/beats/v7/libbeat/reader" "github.com/elastic/elastic-agent-libs/logp" "github.com/elastic/elastic-agent-libs/mapstr" @@ -134,7 +134,7 @@ func (p *DockerJSONReader) parseCRILog(message *reader.Message, msg *logLine) er } ts, err := time.Parse(time.RFC3339Nano, string(log[i])) if err != nil { - return errors.Wrap(err, "parsing CRI timestamp") + return fmt.Errorf("parsing CRI timestamp: %w", err) } message.Ts = ts i++ @@ -176,13 +176,13 @@ func (p *DockerJSONReader) parseDockerJSONLog(message *reader.Message, msg *logL dec := json.NewDecoder(bytes.NewReader(message.Content)) if err := dec.Decode(&msg); err != nil { - return errors.Wrap(err, "decoding docker JSON") + return fmt.Errorf("decoding docker JSON: %w", err) } // Parse timestamp ts, err := time.Parse(time.RFC3339, msg.Time) if err != nil { - return errors.Wrap(err, "parsing docker timestamp") + return fmt.Errorf("parsing docker timestamp: %w", err) } message.Ts = ts diff --git a/libbeat/tests/compose/project.go b/libbeat/tests/compose/project.go index 3d6751befbe0..685cc69ba42d 100644 --- a/libbeat/tests/compose/project.go +++ b/libbeat/tests/compose/project.go @@ -19,14 +19,13 @@ package compose import ( "context" + "errors" "fmt" "os" "path/filepath" "syscall" "time" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-libs/logp" ) @@ -278,7 +277,7 @@ func acquireLock(path string) bool { _, err = fmt.Fprintf(file, "%d", os.Getpid()) if err != nil { - panic(errors.Wrap(err, "Failed to write pid to lock file")) + panic(fmt.Errorf("Failed to write pid to lock file: %w", err)) } return true } diff --git a/libbeat/tests/compose/wrapper.go b/libbeat/tests/compose/wrapper.go index 2c81e2557b30..a0c40afd6de9 100644 --- a/libbeat/tests/compose/wrapper.go +++ b/libbeat/tests/compose/wrapper.go @@ -192,7 +192,7 @@ func (d *wrapperDriver) Up(ctx context.Context, opts UpOptions, service string) pull.Stdout = nil pull.Stderr = &stderr if err := pull.Run(); err != nil { - return errors.Wrapf(err, "failed to pull images using docker-compose: %s", stderr.String()) + return fmt.Errorf("failed to pull images using docker-compose: %s: %w", stderr.String(), err) } err := d.cmd(ctx, "up", args...).Run() @@ -219,13 +219,13 @@ func writeToContainer(ctx context.Context, cli *client.Client, id, filename, con ChangeTime: now, }) if err != nil { - return errors.Wrap(err, "failed to write tar header") + return fmt.Errorf("failed to write tar header: %w", err) } if _, err := tw.Write([]byte(content)); err != nil { - return errors.Wrap(err, "failed to write tar file") + return fmt.Errorf("failed to write tar file: %w", err) } if err := tw.Close(); err != nil { - return errors.Wrap(err, "failed to close tar") + return fmt.Errorf("failed to close tar: %w", err) } opts := types.CopyToContainerOptions{} @@ -242,10 +242,10 @@ func writeToContainer(ctx context.Context, cli *client.Client, id, filename, con func (d *wrapperDriver) setupAdvertisedHost(ctx context.Context, service string, port int) error { containers, err := d.containers(ctx, Filter{State: AnyState}, service) if err != nil { - return errors.Wrap(err, "setupAdvertisedHost") + return fmt.Errorf("setupAdvertisedHost: %w", err) } if len(containers) == 0 { - return errors.Errorf("no containers for service %s", service) + return fmt.Errorf("no containers for service %s", service) } for _, c := range containers { @@ -277,7 +277,7 @@ func (d *wrapperDriver) Kill(ctx context.Context, signal string, service string) func (d *wrapperDriver) Ps(ctx context.Context, filter ...string) ([]ContainerStatus, error) { containers, err := d.containers(ctx, Filter{State: AnyState}, filter...) if err != nil { - return nil, errors.Wrap(err, "ps") + return nil, fmt.Errorf("ps: %w", err) } ps := make([]ContainerStatus, len(containers)) @@ -290,7 +290,7 @@ func (d *wrapperDriver) Ps(ctx context.Context, filter ...string) ([]ContainerSt func (d *wrapperDriver) Containers(ctx context.Context, projectFilter Filter, filter ...string) ([]string, error) { containers, err := d.containers(ctx, projectFilter, filter...) if err != nil { - return nil, errors.Wrap(err, "containers") + return nil, fmt.Errorf("containers: %w", err) } ids := make([]string, len(containers)) @@ -314,7 +314,7 @@ func (d *wrapperDriver) containers(ctx context.Context, projectFilter Filter, fi serviceNames, err := d.serviceNames(ctx) if err != nil { - return nil, errors.Wrap(err, "failed to get container list") + return nil, fmt.Errorf("failed to get container list: %w", err) } var containers []types.Container @@ -324,7 +324,7 @@ func (d *wrapperDriver) containers(ctx context.Context, projectFilter Filter, fi Filters: f, }) if err != nil { - return nil, errors.Wrap(err, "failed to get container list") + return nil, fmt.Errorf("failed to get container list: %w", err) } for _, container := range list { serviceName, ok := container.Labels[labelComposeService] @@ -345,7 +345,7 @@ func (d *wrapperDriver) containers(ctx context.Context, projectFilter Filter, fi func (d *wrapperDriver) KillOld(ctx context.Context, except []string) error { list, err := d.client.ContainerList(ctx, types.ContainerListOptions{All: true}) if err != nil { - return errors.Wrap(err, "listing containers to be killed") + return fmt.Errorf("listing containers to be killed: %w", err) } for _, container := range list { container := wrapperContainer{info: container} @@ -367,7 +367,7 @@ func (d *wrapperDriver) serviceNames(ctx context.Context) ([]string, error) { cmd.Stdout = &stdout err := cmd.Run() if err != nil { - return nil, errors.Wrap(err, "failed to get list of service names") + return nil, fmt.Errorf("failed to get list of service names: %w", err) } return strings.Fields(stdout.String()), nil } @@ -376,7 +376,7 @@ func (d *wrapperDriver) serviceNames(ctx context.Context) ([]string, error) { func (d *wrapperDriver) Inspect(ctx context.Context, serviceName string) (string, error) { list, err := d.client.ContainerList(ctx, types.ContainerListOptions{All: true}) if err != nil { - return "", errors.Wrap(err, "listing containers to be inspected") + return "", fmt.Errorf("listing containers to be inspected: %w", err) } var found bool @@ -391,19 +391,19 @@ func (d *wrapperDriver) Inspect(ctx context.Context, serviceName string) (string } if !found { - return "", errors.Errorf("container not found for service '%s'", serviceName) + return "", fmt.Errorf("container not found for service '%s'", serviceName) } inspect, err := d.client.ContainerInspect(ctx, c.ID) if err != nil { - return "", errors.Wrap(err, "container failed inspection") + return "", fmt.Errorf("container failed inspection: %w", err) } else if inspect.State == nil { return "empty container state", nil } state, err := json.Marshal(inspect.State) if err != nil { - return "", errors.Wrap(err, "container inspection failed") + return "", fmt.Errorf("container inspection failed: %w", err) } return string(state), nil diff --git a/libbeat/tests/docker/docker.go b/libbeat/tests/docker/docker.go index 1b40bef0d808..0c3c8878c9df 100644 --- a/libbeat/tests/docker/docker.go +++ b/libbeat/tests/docker/docker.go @@ -19,11 +19,10 @@ package docker import ( "context" + "fmt" "io" "io/ioutil" - "github.com/pkg/errors" - "github.com/elastic/elastic-agent-autodiscover/docker" "github.com/docker/docker/api/types" @@ -56,11 +55,11 @@ func (c Client) ContainerStart(image string, cmd []string, labels map[string]str Labels: labels, }, nil, nil, nil, "") if err != nil { - return "", errors.Wrap(err, "creating container") + return "", fmt.Errorf("creating container: %w", err) } if err := c.cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil { - return "", errors.Wrap(err, "starting container") + return "", fmt.Errorf("starting container: %w", err) } return resp.ID, nil @@ -78,14 +77,14 @@ func (c Client) imagePull(image string) (err error) { err = func() error { respBody, err := c.cli.ImagePull(ctx, image, types.ImagePullOptions{}) if err != nil { - return errors.Wrapf(err, "pullling image %s", image) + return fmt.Errorf("pullling image %s: %w", image, err) } defer respBody.Close() // Read all the response, to be sure that the pull has finished before returning. _, err = io.Copy(ioutil.Discard, respBody) if err != nil { - return errors.Wrapf(err, "reading response for image %s", image) + return fmt.Errorf("reading response for image %s: %w", image, err) } return nil }()