Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Fix linter findings for errorlint (part5) #12731

Merged
merged 4 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions plugins/inputs/fail2ban/fail2ban.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (f *Fail2ban) Init() error {
if f.path == "" {
path, err := exec.LookPath(cmd)
if err != nil {
return fmt.Errorf("looking up %q failed: %v", cmd, err)
return fmt.Errorf("looking up %q failed: %w", cmd, err)
}
f.path = path
}
Expand Down Expand Up @@ -81,7 +81,7 @@ func (f *Fail2ban) Gather(acc telegraf.Accumulator) error {
cmd := execCommand(name, args...)
out, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
return fmt.Errorf("failed to run command %q: %w - %s", strings.Join(cmd.Args, " "), err, string(out))
}
lines := strings.Split(string(out), "\n")
const targetString = "Jail list:"
Expand All @@ -102,7 +102,7 @@ func (f *Fail2ban) Gather(acc telegraf.Accumulator) error {
cmd := execCommand(name, args...)
out, err := cmd.Output()
if err != nil {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
return fmt.Errorf("failed to run command %q: %w - %s", strings.Join(cmd.Args, " "), err, string(out))
}

lines := strings.Split(string(out), "\n")
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/fireboard/fireboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (r *Fireboard) Gather(acc telegraf.Accumulator) error {
// Decode the response JSON into a new stats struct
var stats []fireboardStats
if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {
return fmt.Errorf("unable to decode fireboard response: %s", err)
return fmt.Errorf("unable to decode fireboard response: %w", err)
}
// Range over all devices, gathering stats. Returns early in case of any error.
for _, s := range stats {
Expand Down
4 changes: 3 additions & 1 deletion plugins/inputs/github/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package github
import (
"context"
_ "embed"
"errors"
"fmt"
"net/http"
"strings"
Expand Down Expand Up @@ -148,10 +149,11 @@ func (g *GitHub) Gather(acc telegraf.Accumulator) error {
}

func (g *GitHub) handleRateLimit(response *githubLib.Response, err error) {
var rlErr *githubLib.RateLimitError
if err == nil {
g.RateLimit.Set(int64(response.Rate.Limit))
g.RateRemaining.Set(int64(response.Rate.Remaining))
} else if _, ok := err.(*githubLib.RateLimitError); ok {
} else if errors.As(err, &rlErr) {
g.RateLimitErrors.Incr(1)
}
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/gnmi/gnmi.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,11 @@ func (s *Subscription) buildAlias(aliases map[string]string) error {

longPath, _, err := handlePath(gnmiLongPath, nil, nil, "")
if err != nil {
return fmt.Errorf("handling long-path failed: %v", err)
return fmt.Errorf("handling long-path failed: %w", err)
}
shortPath, _, err := handlePath(gnmiShortPath, nil, nil, "")
if err != nil {
return fmt.Errorf("handling short-path failed: %v", err)
return fmt.Errorf("handling short-path failed: %w", err)
}

// If the user didn't provide a measurement name, use last path element
Expand Down
7 changes: 4 additions & 3 deletions plugins/inputs/gnmi/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gnmi
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -62,7 +63,7 @@ func (h *handler) subscribeGNMI(ctx context.Context, acc telegraf.Accumulator, t

client, err := grpc.DialContext(ctx, h.address, opts...)
if err != nil {
return fmt.Errorf("failed to dial: %v", err)
return fmt.Errorf("failed to dial: %w", err)
}
defer client.Close()

Expand All @@ -73,7 +74,7 @@ func (h *handler) subscribeGNMI(ctx context.Context, acc telegraf.Accumulator, t

// If io.EOF is returned, the stream may have ended and stream status
// can be determined by calling Recv.
if err := subscribeClient.Send(request); err != nil && err != io.EOF {
if err := subscribeClient.Send(request); err != nil && !errors.Is(err, io.EOF) {
return fmt.Errorf("failed to send subscription request: %w", err)
}

Expand All @@ -82,7 +83,7 @@ func (h *handler) subscribeGNMI(ctx context.Context, acc telegraf.Accumulator, t
for ctx.Err() == nil {
var reply *gnmiLib.SubscribeResponse
if reply, err = subscribeClient.Recv(); err != nil {
if err != io.EOF && ctx.Err() == nil {
if !errors.Is(err, io.EOF) && ctx.Err() == nil {
return fmt.Errorf("aborted gNMI subscription: %w", err)
}
break
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/gnmi/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,11 @@ func gnmiToFields(name string, updateVal *gnmiLib.TypedValue) (map[string]interf
fields[name] = value
} else if jsondata != nil {
if err := json.Unmarshal(jsondata, &value); err != nil {
return nil, fmt.Errorf("failed to parse JSON value: %v", err)
return nil, fmt.Errorf("failed to parse JSON value: %w", err)
}
flattener := jsonparser.JSONFlattener{Fields: fields}
if err := flattener.FullFlattenJSON(name, value, true, true); err != nil {
return nil, fmt.Errorf("failed to flatten JSON: %v", err)
return nil, fmt.Errorf("failed to flatten JSON: %w", err)
}
}
return fields, nil
Expand Down
7 changes: 4 additions & 3 deletions plugins/inputs/google_cloud_storage/google_cloud_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -82,7 +83,7 @@ func (gcs *GCS) Gather(acc telegraf.Accumulator) error {
for {
attrs, err := it.Next()

if err == iterator.Done {
if errors.Is(err, iterator.Done) {
gcs.Log.Infof("Iterated all the keys")
break
}
Expand All @@ -96,8 +97,8 @@ func (gcs *GCS) Gather(acc telegraf.Accumulator) error {

if !gcs.shoudIgnore(name) {
if err := gcs.processMeasurementsInObject(name, bucket, acc); err != nil {
gcs.Log.Errorf("Could not process object: %v in bucket: %v", name, bucketName, err)
acc.AddError(fmt.Errorf("COULD NOT PROCESS OBJECT: %v IN BUCKET: %v", name, err))
gcs.Log.Errorf("Could not process object %q in bucket %q: %v", name, bucketName, err)
acc.AddError(fmt.Errorf("COULD NOT PROCESS OBJECT %q IN BUCKET %q: %w", name, bucketName, err))
}
}

Expand Down
12 changes: 5 additions & 7 deletions plugins/inputs/haproxy/haproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package haproxy
import (
_ "embed"
"encoding/csv"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -85,8 +86,7 @@ func (h *haproxy) Gather(acc telegraf.Accumulator) error {
}

func (h *haproxy) gatherServerSocket(addr string, acc telegraf.Accumulator) error {
var network string
var address string
var network, address string
if strings.HasPrefix(addr, "tcp://") {
network = "tcp"
address = strings.TrimPrefix(addr, "tcp://")
Expand All @@ -96,15 +96,13 @@ func (h *haproxy) gatherServerSocket(addr string, acc telegraf.Accumulator) erro
}

c, err := net.Dial(network, address)

if err != nil {
return fmt.Errorf("could not connect to '%s://%s': %s", network, address, err)
return fmt.Errorf("could not connect to '%s://%s': %w", network, address, err)
}

_, errw := c.Write([]byte("show stat\n"))

if errw != nil {
return fmt.Errorf("could not write to socket '%s://%s': %s", network, address, errw)
return fmt.Errorf("could not write to socket '%s://%s': %w", network, address, errw)
}

return h.importCsvResult(c, acc, address)
Expand Down Expand Up @@ -212,7 +210,7 @@ func (h *haproxy) importCsvResult(r io.Reader, acc telegraf.Accumulator, host st

for {
row, err := csvr.Read()
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
if err != nil {
Expand Down
12 changes: 6 additions & 6 deletions plugins/inputs/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (h *HTTP) Gather(acc telegraf.Accumulator) error {
go func(url string) {
defer wg.Done()
if err := h.gatherURL(acc, url); err != nil {
acc.AddError(fmt.Errorf("[url=%s]: %s", url, err))
acc.AddError(fmt.Errorf("[url=%s]: %w", url, err))
}
}(u)
}
Expand Down Expand Up @@ -157,17 +157,17 @@ func (h *HTTP) gatherURL(

b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading body failed: %v", err)
return fmt.Errorf("reading body failed: %w", err)
}

// Instantiate a new parser for the new data to avoid trouble with stateful parsers
parser, err := h.parserFunc()
if err != nil {
return fmt.Errorf("instantiating parser failed: %v", err)
return fmt.Errorf("instantiating parser failed: %w", err)
}
metrics, err := parser.Parse(b)
if err != nil {
return fmt.Errorf("parsing metrics failed: %v", err)
return fmt.Errorf("parsing metrics failed: %w", err)
}

for _, metric := range metrics {
Expand All @@ -187,13 +187,13 @@ func (h *HTTP) setRequestAuth(request *http.Request) error {

username, err := h.Username.Get()
if err != nil {
return fmt.Errorf("getting username failed: %v", err)
return fmt.Errorf("getting username failed: %w", err)
}
defer config.ReleaseSecret(username)

password, err := h.Password.Get()
if err != nil {
return fmt.Errorf("getting password failed: %v", err)
return fmt.Errorf("getting password failed: %w", err)
}
defer config.ReleaseSecret(password)

Expand Down
32 changes: 16 additions & 16 deletions plugins/inputs/http_response/http_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,6 @@ type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}

// ErrRedirectAttempted indicates that a redirect occurred
var ErrRedirectAttempted = errors.New("redirect")

// Set the proxy. A configured proxy overwrites the system wide proxy.
func getProxyFunc(httpProxy string) func(*http.Request) (*url.URL, error) {
if httpProxy == "" {
Expand Down Expand Up @@ -157,27 +154,30 @@ func setResult(resultString string, fields map[string]interface{}, tags map[stri
}

func setError(err error, fields map[string]interface{}, tags map[string]string) error {
if timeoutError, ok := err.(net.Error); ok && timeoutError.Timeout() {
var timeoutError net.Error
if errors.As(err, &timeoutError) && timeoutError.Timeout() {
setResult("timeout", fields, tags)
return timeoutError
}

urlErr, isURLErr := err.(*url.Error)
if !isURLErr {
var urlErr *url.Error
if !errors.As(err, &urlErr) {
srebhan marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

opErr, isNetErr := (urlErr.Err).(*net.OpError)
if isNetErr {
switch e := (opErr.Err).(type) {
case *net.DNSError:
var opErr *net.OpError
if errors.As(urlErr, &opErr) {
var dnsErr *net.DNSError
var parseErr *net.ParseError

if errors.As(opErr, &dnsErr) {
setResult("dns_error", fields, tags)
return e
case *net.ParseError:
return dnsErr
} else if errors.As(opErr, &parseErr) {
// Parse error has to do with parsing of IP addresses, so we
// group it with address errors
setResult("address_error", fields, tags)
return e
return parseErr
}
}
srebhan marked this conversation as resolved.
Show resolved Hide resolved

Expand Down Expand Up @@ -339,7 +339,7 @@ func (h *HTTPResponse) Gather(acc telegraf.Accumulator) error {
var err error
h.compiledStringMatch, err = regexp.Compile(h.ResponseStringMatch)
if err != nil {
return fmt.Errorf("failed to compile regular expression %s : %s", h.ResponseStringMatch, err)
return fmt.Errorf("failed to compile regular expression %q: %w", h.ResponseStringMatch, err)
}
}

Expand Down Expand Up @@ -401,12 +401,12 @@ func (h *HTTPResponse) Gather(acc telegraf.Accumulator) error {
func (h *HTTPResponse) setRequestAuth(request *http.Request) error {
username, err := h.Username.Get()
if err != nil {
return fmt.Errorf("getting username failed: %v", err)
return fmt.Errorf("getting username failed: %w", err)
}
defer config.ReleaseSecret(username)
password, err := h.Password.Get()
if err != nil {
return fmt.Errorf("getting password failed: %v", err)
return fmt.Errorf("getting password failed: %w", err)
}
defer config.ReleaseSecret(password)
if len(username) != 0 || len(password) != 0 {
Expand Down
10 changes: 5 additions & 5 deletions plugins/inputs/hugepages/hugepages.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,19 @@ func (h *Hugepages) Init() error {
func (h *Hugepages) Gather(acc telegraf.Accumulator) error {
if h.gatherRoot {
if err := h.gatherRootStats(acc); err != nil {
return fmt.Errorf("gathering root stats failed: %v", err)
return fmt.Errorf("gathering root stats failed: %w", err)
}
}

if h.gatherPerNode {
if err := h.gatherStatsPerNode(acc); err != nil {
return fmt.Errorf("gathering per node stats failed: %v", err)
return fmt.Errorf("gathering per node stats failed: %w", err)
}
}

if h.gatherMeminfo {
if err := h.gatherStatsFromMeminfo(acc); err != nil {
return fmt.Errorf("gathering meminfo stats failed: %v", err)
return fmt.Errorf("gathering meminfo stats failed: %w", err)
}
}

Expand Down Expand Up @@ -160,7 +160,7 @@ func (h *Hugepages) gatherFromHugepagePath(
// read metrics from: hugepages/hugepages-*/*
hugepagesDirs, err := os.ReadDir(path)
if err != nil {
return fmt.Errorf("reading root dir failed: %v", err)
return fmt.Errorf("reading root dir failed: %w", err)
}

for _, hugepagesDir := range hugepagesDirs {
Expand All @@ -177,7 +177,7 @@ func (h *Hugepages) gatherFromHugepagePath(
metricsPath := filepath.Join(path, hugepagesDir.Name())
metricFiles, err := os.ReadDir(metricsPath)
if err != nil {
return fmt.Errorf("reading metric dir failed: %v", err)
return fmt.Errorf("reading metric dir failed: %w", err)
}

metrics := make(map[string]interface{})
Expand Down
Loading