From f7949ca68a5f18e96138da865241111a123153dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Wed, 22 Feb 2023 12:57:53 +0100 Subject: [PATCH] chore: Fix linter findings for errorlint (part1) (#12701) Co-authored-by: Pawel Zak --- agent/agent.go | 15 +++++---------- cmd/telegraf/main.go | 2 +- cmd/telegraf/telegraf.go | 6 +++--- config/config.go | 16 ++++++++-------- config/deprecation.go | 8 ++++---- config/secret.go | 6 +++--- internal/content_coding.go | 6 +++--- internal/http.go | 4 +++- internal/internal.go | 5 +++-- internal/process/process.go | 2 +- internal/snmp/translate.go | 2 +- models/filter.go | 16 ++++++++-------- testutil/container.go | 8 ++++---- testutil/file.go | 4 ++-- tools/custom_builder/config.go | 4 ++-- tools/package_lxd_test/container.go | 6 +++--- tools/package_lxd_test/lxd.go | 2 +- tools/readme_config_includer/generator.go | 4 ++-- tools/update_goversion/main.go | 3 ++- 19 files changed, 59 insertions(+), 60 deletions(-) diff --git a/agent/agent.go b/agent/agent.go index 13c7a4562..442b3a420 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -196,36 +196,31 @@ func (a *Agent) initPlugins() error { } err := input.Init() if err != nil { - return fmt.Errorf("could not initialize input %s: %v", - input.LogName(), err) + return fmt.Errorf("could not initialize input %s: %w", input.LogName(), err) } } for _, processor := range a.Config.Processors { err := processor.Init() if err != nil { - return fmt.Errorf("could not initialize processor %s: %v", - processor.LogName(), err) + return fmt.Errorf("could not initialize processor %s: %w", processor.LogName(), err) } } for _, aggregator := range a.Config.Aggregators { err := aggregator.Init() if err != nil { - return fmt.Errorf("could not initialize aggregator %s: %v", - aggregator.LogName(), err) + return fmt.Errorf("could not initialize aggregator %s: %w", aggregator.LogName(), err) } } for _, processor := range a.Config.AggProcessors { err := processor.Init() if err != nil { - return fmt.Errorf("could not initialize processor %s: %v", - processor.LogName(), err) + return fmt.Errorf("could not initialize processor %s: %w", processor.LogName(), err) } } for _, output := range a.Config.Outputs { err := output.Init() if err != nil { - return fmt.Errorf("could not initialize output %s: %v", - output.LogName(), err) + return fmt.Errorf("could not initialize output %s: %w", output.LogName(), err) } } return nil diff --git a/cmd/telegraf/main.go b/cmd/telegraf/main.go index f47995f61..7036fcccf 100644 --- a/cmd/telegraf/main.go +++ b/cmd/telegraf/main.go @@ -196,7 +196,7 @@ func runApp(args []string, outputBuffer io.Writer, pprof Server, c TelegrafConfi err := PrintInputConfig(cCtx.String("usage"), outputBuffer) err2 := PrintOutputConfig(cCtx.String("usage"), outputBuffer) if err != nil && err2 != nil { - return fmt.Errorf("%s and %s", err, err2) + return fmt.Errorf("%w and %w", err, err2) } return nil // DEPRECATED diff --git a/cmd/telegraf/telegraf.go b/cmd/telegraf/telegraf.go index 2e12619c7..b528ad835 100644 --- a/cmd/telegraf/telegraf.go +++ b/cmd/telegraf/telegraf.go @@ -151,9 +151,9 @@ func (t *Telegraf) reloadLoop() error { } }() - err := t.runAgent(ctx, cfg) - if err != nil && err != context.Canceled { - return fmt.Errorf("[telegraf] Error running agent: %v", err) + err = t.runAgent(ctx, cfg) + if err != nil && !errors.Is(err, context.Canceled) { + return fmt.Errorf("[telegraf] Error running agent: %w", err) } } diff --git a/config/config.go b/config/config.go index 4f350b955..277a0ea29 100644 --- a/config/config.go +++ b/config/config.go @@ -473,7 +473,7 @@ func (c *Config) LoadAll(configFiles ...string) error { func (c *Config) LoadConfigData(data []byte) error { tbl, err := parseConfig(data) if err != nil { - return fmt.Errorf("error parsing data: %s", err) + return fmt.Errorf("error parsing data: %w", err) } // Parse tags tables first: @@ -484,7 +484,7 @@ func (c *Config) LoadConfigData(data []byte) error { return fmt.Errorf("invalid configuration, bad table name %q", tableName) } if err = c.toml.UnmarshalTable(subTable, c.Tags); err != nil { - return fmt.Errorf("error parsing table name %q: %s", tableName, err) + return fmt.Errorf("error parsing table name %q: %w", tableName, err) } } } @@ -614,7 +614,7 @@ func (c *Config) LoadConfigData(data []byte) error { case []*ast.Table: for _, t := range pluginSubTable { if err = c.addAggregator(pluginName, t); err != nil { - return fmt.Errorf("error parsing %s, %s", pluginName, err) + return fmt.Errorf("error parsing %s, %w", pluginName, err) } } default: @@ -632,7 +632,7 @@ func (c *Config) LoadConfigData(data []byte) error { case []*ast.Table: for _, t := range pluginSubTable { if err = c.addSecretStore(pluginName, t); err != nil { - return fmt.Errorf("error parsing %s, %s", pluginName, err) + return fmt.Errorf("error parsing %s, %w", pluginName, err) } } default: @@ -648,7 +648,7 @@ func (c *Config) LoadConfigData(data []byte) error { // identifiers are present default: if err = c.addInput(name, subTable); err != nil { - return fmt.Errorf("error parsing %s, %s", name, err) + return fmt.Errorf("error parsing %s, %w", name, err) } } } @@ -726,7 +726,7 @@ func fetchConfig(u *url.URL) ([]byte, error) { body, err, retry := func() ([]byte, error, bool) { resp, err := http.DefaultClient.Do(req) if err != nil { - return nil, fmt.Errorf("retry %d of %d failed connecting to HTTP config server %s", i, retries, err), false + return nil, fmt.Errorf("retry %d of %d failed connecting to HTTP config server: %w", i, retries, err), false } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -871,13 +871,13 @@ func (c *Config) LinkSecrets() error { } resolver, err := store.GetResolver(key) if err != nil { - return fmt.Errorf("retrieving resolver for %q failed: %v", ref, err) + return fmt.Errorf("retrieving resolver for %q failed: %w", ref, err) } resolvers[ref] = resolver } // Inject the resolver list into the secret if err := s.Link(resolvers); err != nil { - return fmt.Errorf("retrieving resolver failed: %v", err) + return fmt.Errorf("retrieving resolver failed: %w", err) } } return nil diff --git a/config/deprecation.go b/config/deprecation.go index 32190034c..c0f7ac682 100644 --- a/config/deprecation.go +++ b/config/deprecation.go @@ -35,14 +35,14 @@ func (di *DeprecationInfo) determineEscalation(telegrafVersion *semver.Version) since, err := semver.NewVersion(di.info.Since) if err != nil { - return fmt.Errorf("cannot parse 'since' version %q: %v", di.info.Since, err) + return fmt.Errorf("cannot parse 'since' version %q: %w", di.info.Since, err) } var removal *semver.Version if di.info.RemovalIn != "" { removal, err = semver.NewVersion(di.info.RemovalIn) if err != nil { - return fmt.Errorf("cannot parse 'removal' version %q: %v", di.info.RemovalIn, err) + return fmt.Errorf("cannot parse 'removal' version %q: %w", di.info.RemovalIn, err) } } else { removal = &semver.Version{Major: since.Major} @@ -116,7 +116,7 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{ } } if err := info.determineEscalation(c.version); err != nil { - panic(fmt.Errorf("plugin %q: %v", info.Name, err)) + panic(fmt.Errorf("plugin %q: %w", info.Name, err)) } if info.LogLevel != telegraf.None { c.incrementPluginDeprecations(category) @@ -148,7 +148,7 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{ optionInfo.info.RemovalIn = tags[1] } if err := optionInfo.determineEscalation(c.version); err != nil { - panic(fmt.Errorf("plugin %q option %q: %v", info.Name, field.Name, err)) + panic(fmt.Errorf("plugin %q option %q: %w", info.Name, field.Name, err)) } if optionInfo.LogLevel != telegraf.None { diff --git a/config/secret.go b/config/secret.go index b9ddd017d..98e2f34b9 100644 --- a/config/secret.go +++ b/config/secret.go @@ -107,7 +107,7 @@ func (s *Secret) EqualTo(ref []byte) (bool, error) { // Get a locked-buffer of the secret to perform the comparison lockbuf, err := s.enclave.Open() if err != nil { - return false, fmt.Errorf("opening enclave failed: %v", err) + return false, fmt.Errorf("opening enclave failed: %w", err) } defer lockbuf.Destroy() @@ -127,7 +127,7 @@ func (s *Secret) Get() ([]byte, error) { // Decrypt the secret so we can return it lockbuf, err := s.enclave.Open() if err != nil { - return nil, fmt.Errorf("opening enclave failed: %v", err) + return nil, fmt.Errorf("opening enclave failed: %w", err) } defer lockbuf.Destroy() secret := lockbuf.Bytes() @@ -179,7 +179,7 @@ func (s *Secret) Link(resolvers map[string]telegraf.ResolveFunc) error { } lockbuf, err := s.enclave.Open() if err != nil { - return fmt.Errorf("opening enclave failed: %v", err) + return fmt.Errorf("opening enclave failed: %w", err) } defer lockbuf.Destroy() secret := lockbuf.Bytes() diff --git a/internal/content_coding.go b/internal/content_coding.go index e8690f46b..2d43a0bfd 100644 --- a/internal/content_coding.go +++ b/internal/content_coding.go @@ -61,7 +61,7 @@ func (r *GzipReader) Read(b []byte) (int, error) { // Since multistream is disabled, io.EOF indicates the end of the gzip // sequence. On the next read we must read the next gzip header. - if err == io.EOF { + if errors.Is(err, io.EOF) { r.endOfStream = true return n, nil } @@ -225,7 +225,7 @@ func (d *GzipDecoder) Decode(data []byte) ([]byte, error) { d.buf.Reset() _, err = d.buf.ReadFrom(d.reader) - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } err = d.reader.Close() @@ -256,7 +256,7 @@ func (d *ZlibDecoder) Decode(data []byte) ([]byte, error) { return nil, err } _, err = io.Copy(d.buf, r) - if err != nil && err != io.EOF { + if err != nil && !errors.Is(err, io.EOF) { return nil, err } err = r.Close() diff --git a/internal/http.go b/internal/http.go index 7469b9650..a2b3d6293 100644 --- a/internal/http.go +++ b/internal/http.go @@ -2,6 +2,7 @@ package internal import ( "crypto/subtle" + "errors" "net" "net/http" "net/url" @@ -135,7 +136,8 @@ func OnClientError(client *http.Client, err error) { // connection this ensures that next interval a new connection will be // used and name lookup will be performed. // https://github.com/golang/go/issues/36026 - if err, ok := err.(*url.Error); ok && err.Timeout() { + var urlErr *url.Error + if errors.As(err, &urlErr) && urlErr.Timeout() { client.CloseIdleConnections() } } diff --git a/internal/internal.go b/internal/internal.go index 5b38efd3a..1078756e1 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -184,8 +184,9 @@ func AlignTime(tm time.Time, interval time.Duration) time.Time { // and returns the exit status and true // if error is not exit status, will return 0 and false func ExitStatus(err error) (int, bool) { - if exiterr, ok := err.(*exec.ExitError); ok { - if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + if status, ok := exitErr.Sys().(syscall.WaitStatus); ok { return status.ExitStatus(), true } } diff --git a/internal/process/process.go b/internal/process/process.go index 1d8868c67..acd8a4247 100644 --- a/internal/process/process.go +++ b/internal/process/process.go @@ -113,7 +113,7 @@ func (p *Process) cmdStart() error { p.Log.Infof("Starting process: %s %s", p.name, p.args) if err := p.Cmd.Start(); err != nil { - return fmt.Errorf("error starting process: %s", err) + return fmt.Errorf("error starting process: %w", err) } atomic.StoreInt32(&p.pid, int32(p.Cmd.Process.Pid)) return nil diff --git a/internal/snmp/translate.go b/internal/snmp/translate.go index 7e0f19f31..6f168a041 100644 --- a/internal/snmp/translate.go +++ b/internal/snmp/translate.go @@ -135,7 +135,7 @@ func walkPaths(paths []string, log telegraf.Logger) ([]string, error) { return nil }) if err != nil { - return folders, fmt.Errorf("couldn't walk path %q: %v", mibPath, err) + return folders, fmt.Errorf("couldn't walk path %q: %w", mibPath, err) } } return folders, nil diff --git a/models/filter.go b/models/filter.go index b4d871236..0b3172336 100644 --- a/models/filter.go +++ b/models/filter.go @@ -54,41 +54,41 @@ func (f *Filter) Compile() error { var err error f.nameDropFilter, err = filter.Compile(f.NameDrop) if err != nil { - return fmt.Errorf("error compiling 'namedrop', %s", err) + return fmt.Errorf("error compiling 'namedrop', %w", err) } f.namePassFilter, err = filter.Compile(f.NamePass) if err != nil { - return fmt.Errorf("error compiling 'namepass', %s", err) + return fmt.Errorf("error compiling 'namepass', %w", err) } f.fieldDropFilter, err = filter.Compile(f.FieldDrop) if err != nil { - return fmt.Errorf("error compiling 'fielddrop', %s", err) + return fmt.Errorf("error compiling 'fielddrop', %w", err) } f.fieldPassFilter, err = filter.Compile(f.FieldPass) if err != nil { - return fmt.Errorf("error compiling 'fieldpass', %s", err) + return fmt.Errorf("error compiling 'fieldpass', %w", err) } f.tagExcludeFilter, err = filter.Compile(f.TagExclude) if err != nil { - return fmt.Errorf("error compiling 'tagexclude', %s", err) + return fmt.Errorf("error compiling 'tagexclude', %w", err) } f.tagIncludeFilter, err = filter.Compile(f.TagInclude) if err != nil { - return fmt.Errorf("error compiling 'taginclude', %s", err) + return fmt.Errorf("error compiling 'taginclude', %w", err) } for i := range f.TagDropFilters { f.TagDropFilters[i].filter, err = filter.Compile(f.TagDropFilters[i].Values) if err != nil { - return fmt.Errorf("error compiling 'tagdrop', %s", err) + return fmt.Errorf("error compiling 'tagdrop', %w", err) } } for i := range f.TagPassFilters { f.TagPassFilters[i].filter, err = filter.Compile(f.TagPassFilters[i].Values) if err != nil { - return fmt.Errorf("error compiling 'tagpass', %s", err) + return fmt.Errorf("error compiling 'tagpass', %w", err) } } return nil diff --git a/testutil/container.go b/testutil/container.go index 65390d2a1..8c0daa4f9 100644 --- a/testutil/container.go +++ b/testutil/container.go @@ -63,7 +63,7 @@ func (c *Container) Start() error { container, err := testcontainers.GenericContainer(c.ctx, req) if err != nil { - return fmt.Errorf("container failed to start: %s", err) + return fmt.Errorf("container failed to start: %w", err) } c.container = container @@ -73,7 +73,7 @@ func (c *Container) Start() error { c.container.FollowOutput(&c.Logs) err = c.container.StartLogProducer(c.ctx) if err != nil { - return fmt.Errorf("log producer failed: %s", err) + return fmt.Errorf("log producer failed: %w", err) } c.Address = "localhost" @@ -81,7 +81,7 @@ func (c *Container) Start() error { err = c.LookupMappedPorts() if err != nil { c.Terminate() - return fmt.Errorf("port lookup failed: %s", err) + return fmt.Errorf("port lookup failed: %w", err) } return nil @@ -110,7 +110,7 @@ func (c *Container) LookupMappedPorts() error { p, err := c.container.MappedPort(c.ctx, nat.Port(port)) if err != nil { - return fmt.Errorf("failed to find '%s' - %s", port, err) + return fmt.Errorf("failed to find %q: %w", port, err) } fmt.Printf("mapped container port '%s' to host port '%s'\n", port, p.Port()) c.Ports[port] = p.Port() diff --git a/testutil/file.go b/testutil/file.go index f4295cbd7..0e22f41e4 100644 --- a/testutil/file.go +++ b/testutil/file.go @@ -78,7 +78,7 @@ func ParseMetricsFrom(lines []string, header string, parser LineParser) ([]teleg m, err := parser.ParseLine(content) if err != nil { - return nil, fmt.Errorf("unable to parse metric in %q failed: %v", content, err) + return nil, fmt.Errorf("unable to parse metric in %q failed: %w", content, err) } metrics = append(metrics, m) } @@ -104,7 +104,7 @@ func ParseMetricsFromFile(filename string, parser telegraf.Parser) ([]telegraf.M nonutc, err := parser.Parse(line) if err != nil { - return nil, fmt.Errorf("unable to parse metric in %q failed: %v", line, err) + return nil, fmt.Errorf("unable to parse metric in %q failed: %w", line, err) } for _, m := range nonutc { // The timezone needs to be UTC to match the timestamp test results diff --git a/tools/custom_builder/config.go b/tools/custom_builder/config.go index 2d4ac72f7..0567bb137 100644 --- a/tools/custom_builder/config.go +++ b/tools/custom_builder/config.go @@ -95,11 +95,11 @@ func (s *selection) importFiles(configurations []string) error { for _, cfg := range configurations { buf, err := config.LoadConfigFile(cfg) if err != nil { - return fmt.Errorf("reading %q failed: %v", cfg, err) + return fmt.Errorf("reading %q failed: %w", cfg, err) } if err := s.extractPluginsFromConfig(buf); err != nil { - return fmt.Errorf("extracting plugins from %q failed: %v", cfg, err) + return fmt.Errorf("extracting plugins from %q failed: %w", cfg, err) } } diff --git a/tools/package_lxd_test/container.go b/tools/package_lxd_test/container.go index 9dde13d00..0fe093a95 100644 --- a/tools/package_lxd_test/container.go +++ b/tools/package_lxd_test/container.go @@ -32,12 +32,12 @@ func (c *Container) Create(image string) error { c.client = LXDClient{} err := c.client.Connect() if err != nil { - return fmt.Errorf("failed to connect to lxd: %v", err) + return fmt.Errorf("failed to connect to lxd: %w", err) } err = c.client.Create(c.Name, "images", image) if err != nil { - return fmt.Errorf("failed to create instance: %v", err) + return fmt.Errorf("failed to create instance: %w", err) } // at this point the container is created, so on any error during setup @@ -45,7 +45,7 @@ func (c *Container) Create(image string) error { err = c.client.Start(c.Name) if err != nil { c.Delete() - return fmt.Errorf("failed to start instance: %v", err) + return fmt.Errorf("failed to start instance: %w", err) } if err := c.detectPackageManager(); err != nil { diff --git a/tools/package_lxd_test/lxd.go b/tools/package_lxd_test/lxd.go index 209476532..be4af3460 100644 --- a/tools/package_lxd_test/lxd.go +++ b/tools/package_lxd_test/lxd.go @@ -153,7 +153,7 @@ func (c *LXDClient) Push(name string, src string, dst string) error { fmt.Printf("cp %s %s%s\n", src, name, dst) f, err := os.Open(src) if err != nil { - return fmt.Errorf("error reading %s: %v", src, err) + return fmt.Errorf("error reading %s: %w", src, err) } defer f.Close() diff --git a/tools/readme_config_includer/generator.go b/tools/readme_config_includer/generator.go index 4d9e76d6d..966e20223 100644 --- a/tools/readme_config_includer/generator.go +++ b/tools/readme_config_includer/generator.go @@ -78,13 +78,13 @@ func extractIncludeBlock(txt []byte, includesEx *regexp.Regexp, root string) *in func insertInclude(buf *bytes.Buffer, include string) error { file, err := os.Open(include) if err != nil { - return fmt.Errorf("opening include %q failed: %v", include, err) + return fmt.Errorf("opening include %q failed: %w", include, err) } defer file.Close() // Write the include and make sure we get a newline if _, err := io.Copy(buf, file); err != nil { - return fmt.Errorf("inserting include %q failed: %v", include, err) + return fmt.Errorf("inserting include %q failed: %w", include, err) } return nil } diff --git a/tools/update_goversion/main.go b/tools/update_goversion/main.go index b83420e41..b0cf27163 100644 --- a/tools/update_goversion/main.go +++ b/tools/update_goversion/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "io" "log" @@ -72,7 +73,7 @@ func findHashes(body io.Reader, version string) (map[string]string, error) { //the end of the file, or the HTML was malformed if tokenType == html.ErrorToken { err := htmlTokens.Err() - if err == io.EOF { + if errors.Is(err, io.EOF) { //end of the file, break out of the loop break }