Skip to content

Commit

Permalink
chore: Fix linter findings for errorlint (part7) (#12772)
Browse files Browse the repository at this point in the history
Co-authored-by: Pawel Zak <Pawel Zak>
  • Loading branch information
zak-pawel authored Mar 3, 2023
1 parent 5c234d8 commit e2a510f
Show file tree
Hide file tree
Showing 45 changed files with 161 additions and 139 deletions.
6 changes: 4 additions & 2 deletions plugins/inputs/rabbitmq/rabbitmq.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package rabbitmq
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -381,7 +382,8 @@ func (r *RabbitMQ) requestJSON(u string, target interface{}) error {
return err
}
if err := json.Unmarshal(buf, target); err != nil {
if _, ok := err.(*json.UnmarshalTypeError); ok {
var jsonErr *json.UnmarshalTypeError
if errors.As(err, &jsonErr) {
// Try to get the error reason from the response
var errResponse ErrorResponse
if json.Unmarshal(buf, &errResponse) == nil && errResponse.Error != "" {
Expand All @@ -390,7 +392,7 @@ func (r *RabbitMQ) requestJSON(u string, target interface{}) error {
}
}

return fmt.Errorf("decoding answer from %q failed: %v", u, err)
return fmt.Errorf("decoding answer from %q failed: %w", u, err)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/raindrops/raindrops.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (r *Raindrops) Gather(acc telegraf.Accumulator) error {
func (r *Raindrops) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := r.httpClient.Get(addr.String())
if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", addr.String(), err)
return fmt.Errorf("error making HTTP request to %q: %w", addr.String(), err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/ras/ras.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func validateDbPath(dbPath string) error {
}

if err != nil {
return fmt.Errorf("cannot get system information for db_path file: [%s] - %v", dbPath, err)
return fmt.Errorf("cannot get system information for db_path file %q: %w", dbPath, err)
}

if mode := pathInfo.Mode(); !mode.IsRegular() {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/redfish/redfish.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ func (r *Redfish) getData(address string, payload interface{}) error {

err = json.Unmarshal(body, &payload)
if err != nil {
return fmt.Errorf("error parsing input: %v", err)
return fmt.Errorf("error parsing input: %w", err)
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ func (r *Redis) connect() error {

u, err := url.Parse(serv)
if err != nil {
return fmt.Errorf("unable to parse to address %q: %s", serv, err.Error())
return fmt.Errorf("unable to parse to address %q: %w", serv, err)
}

username := ""
Expand Down Expand Up @@ -329,7 +329,7 @@ func (r *Redis) gatherCommandValues(client Client, acc telegraf.Accumulator) err
val, err := client.Do(command.Type, command.Command...)
if err != nil {
if strings.Contains(err.Error(), "unexpected type=") {
return fmt.Errorf("could not get command result: %s", err)
return fmt.Errorf("could not get command result: %w", err)
}

return err
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/redis_sentinel/redis_sentinel.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (r *RedisSentinel) Init() error {
for _, serv := range r.Servers {
u, err := url.Parse(serv)
if err != nil {
return fmt.Errorf("unable to parse to address %q: %v", serv, err)
return fmt.Errorf("unable to parse to address %q: %w", serv, err)
}

password := ""
Expand Down Expand Up @@ -136,7 +136,7 @@ func castFieldValue(value string, fieldType configFieldType) (interface{}, error
}

if err != nil {
return nil, fmt.Errorf("casting value %v failed: %v", value, err)
return nil, fmt.Errorf("casting value %q failed: %w", value, err)
}

return castedValue, nil
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/rethinkdb/rethinkdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (r *RethinkDB) gatherServer(server *Server, acc telegraf.Accumulator) error

server.session, err = gorethink.Connect(connectOpts)
if err != nil {
return fmt.Errorf("unable to connect to RethinkDB, %s", err.Error())
return fmt.Errorf("unable to connect to RethinkDB: %w", err)
}
defer server.session.Close()

Expand Down
24 changes: 12 additions & 12 deletions plugins/inputs/rethinkdb/rethinkdb_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@ type Server struct {

func (s *Server) gatherData(acc telegraf.Accumulator) error {
if err := s.getServerStatus(); err != nil {
return fmt.Errorf("failed to get server_status, %s", err)
return fmt.Errorf("failed to get server_status: %w", err)
}

if err := s.validateVersion(); err != nil {
return fmt.Errorf("failed version validation, %s", err.Error())
return fmt.Errorf("failed version validation: %w", err)
}

if err := s.addClusterStats(acc); err != nil {
return fmt.Errorf("error adding cluster stats, %s", err.Error())
return fmt.Errorf("error adding cluster stats: %w", err)
}

if err := s.addMemberStats(acc); err != nil {
return fmt.Errorf("error adding member stats, %s", err.Error())
return fmt.Errorf("error adding member stats: %w", err)
}

if err := s.addTablesStats(acc); err != nil {
return fmt.Errorf("error adding table stats, %s", err.Error())
return fmt.Errorf("error adding table stats: %w", err)
}

return nil
Expand Down Expand Up @@ -112,12 +112,12 @@ var ClusterTracking = []string{
func (s *Server) addClusterStats(acc telegraf.Accumulator) error {
cursor, err := gorethink.DB("rethinkdb").Table("stats").Get([]string{"cluster"}).Run(s.session)
if err != nil {
return fmt.Errorf("cluster stats query error, %s", err.Error())
return fmt.Errorf("cluster stats query error: %w", err)
}
defer cursor.Close()
var clusterStats stats
if err := cursor.One(&clusterStats); err != nil {
return fmt.Errorf("failure to parse cluster stats, %s", err.Error())
return fmt.Errorf("failure to parse cluster stats: %w", err)
}

tags := s.getDefaultTags()
Expand All @@ -140,12 +140,12 @@ var MemberTracking = []string{
func (s *Server) addMemberStats(acc telegraf.Accumulator) error {
cursor, err := gorethink.DB("rethinkdb").Table("stats").Get([]string{"server", s.serverStatus.ID}).Run(s.session)
if err != nil {
return fmt.Errorf("member stats query error, %s", err.Error())
return fmt.Errorf("member stats query error: %w", err)
}
defer cursor.Close()
var memberStats stats
if err := cursor.One(&memberStats); err != nil {
return fmt.Errorf("failure to parse member stats, %s", err.Error())
return fmt.Errorf("failure to parse member stats: %w", err)
}

tags := s.getDefaultTags()
Expand All @@ -164,7 +164,7 @@ var TableTracking = []string{
func (s *Server) addTablesStats(acc telegraf.Accumulator) error {
tablesCursor, err := gorethink.DB("rethinkdb").Table("table_status").Run(s.session)
if err != nil {
return fmt.Errorf("table stats query error, %s", err.Error())
return fmt.Errorf("table stats query error: %w", err)
}

defer tablesCursor.Close()
Expand All @@ -187,13 +187,13 @@ func (s *Server) addTableStats(acc telegraf.Accumulator, table tableStatus) erro
Get([]string{"table_server", table.ID, s.serverStatus.ID}).
Run(s.session)
if err != nil {
return fmt.Errorf("table stats query error, %s", err.Error())
return fmt.Errorf("table stats query error: %w", err)
}
defer cursor.Close()

var ts tableStats
if err := cursor.One(&ts); err != nil {
return fmt.Errorf("failure to parse table stats, %s", err.Error())
return fmt.Errorf("failure to parse table stats: %w", err)
}

tags := s.getDefaultTags()
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/riak/riak.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func (r *Riak) gatherServer(s string, acc telegraf.Accumulator) error {
// Parse the given URL to extract the server tag
u, err := url.Parse(s)
if err != nil {
return fmt.Errorf("riak unable to parse given server url %s: %s", s, err)
return fmt.Errorf("riak unable to parse given server URL %q: %w", s, err)
}

// Perform the GET request to the riak /stats endpoint
Expand All @@ -126,7 +126,7 @@ func (r *Riak) gatherServer(s string, acc telegraf.Accumulator) error {
// Decode the response JSON into a new stats struct
stats := &riakStats{}
if err := json.NewDecoder(resp.Body).Decode(stats); err != nil {
return fmt.Errorf("unable to decode riak response: %s", err)
return fmt.Errorf("unable to decode riak response: %w", err)
}

// Build a map of tags
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/sensors/sensors.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (s *Sensors) Init() error {
if s.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)
}
s.path = path
}
Expand Down Expand Up @@ -78,7 +78,7 @@ func (s *Sensors) parse(acc telegraf.Accumulator) error {
cmd := execCommand(s.path, "-A", "-u")
out, err := internal.StdOutputTimeout(cmd, time.Duration(s.Timeout))
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(strings.TrimSpace(string(out)), "\n")
for _, line := range lines {
Expand Down
9 changes: 6 additions & 3 deletions plugins/inputs/sflow/packetdecoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package sflow

import (
"encoding/binary"
"errors"
"fmt"
"io"

"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs/sflow/binaryio"
"github.com/pkg/errors"
)

type PacketDecoder struct {
Expand Down Expand Up @@ -39,7 +39,7 @@ func (d *PacketDecoder) Decode(r io.Reader) error {
}
d.onPacket(packet)
}
if err != nil && errors.Cause(err) == io.EOF {
if err != nil && errors.Is(err, io.EOF) {
return nil
}
return err
Expand Down Expand Up @@ -479,5 +479,8 @@ func (d *PacketDecoder) decodeUDPHeader(r io.Reader) (h UDPHeader, err error) {

func read(r io.Reader, data interface{}, name string) error {
err := binary.Read(r, binary.BigEndian, data)
return errors.Wrapf(err, "failed to read %s", name)
if err != nil {
return fmt.Errorf("failed to read %q: %w", name, err)
}
return nil
}
2 changes: 1 addition & 1 deletion plugins/inputs/sflow/sflow.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func (s *SFlow) read(acc telegraf.Accumulator, conn net.PacketConn) {

func (s *SFlow) process(acc telegraf.Accumulator, buf []byte) {
if err := s.decoder.Decode(bytes.NewBuffer(buf)); err != nil {
acc.AddError(fmt.Errorf("unable to parse incoming packet: %s", err))
acc.AddError(fmt.Errorf("unable to parse incoming packet: %w", err))
}
}

Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/slab/slab.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (ss *SlabStats) runCmd(cmd string, args []string) ([]byte, error) {

out, err := internal.StdOutputTimeout(execCmd, 5*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to run command %s: %s - %v", execCmd.Args, err, out)
return nil, fmt.Errorf("failed to run command %q: %w - %v", execCmd.Args, err, out)
}

return out, nil
Expand Down
14 changes: 8 additions & 6 deletions plugins/inputs/smart/smart.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package smart
import (
"bufio"
_ "embed"
"errors"
"fmt"
"os"
"os/exec"
Expand Down Expand Up @@ -409,7 +410,7 @@ func (m *Smart) Init() error {
if err != nil {
m.PathSmartctl = ""
//without smartctl, plugin will not be able to gather basic metrics
return fmt.Errorf("smartctl not found: verify that smartctl is installed and it is in your PATH (or specified in config): %s", err.Error())
return fmt.Errorf("smartctl not found: verify that smartctl is installed and it is in your PATH (or specified in config): %w", err)
}

err = validatePath(m.PathNVMe)
Expand Down Expand Up @@ -502,7 +503,7 @@ func distinguishNVMeDevices(userDevices []string, availableNVMeDevices []string)
func (m *Smart) scanDevices(ignoreExcludes bool, scanArgs ...string) ([]string, error) {
out, err := runCmd(m.Timeout, m.UseSudo, m.PathSmartctl, scanArgs...)
if err != nil {
return []string{}, fmt.Errorf("failed to run command '%s %s': %s - %s", m.PathSmartctl, scanArgs, err, string(out))
return []string{}, fmt.Errorf("failed to run command '%s %s': %w - %s", m.PathSmartctl, scanArgs, err, string(out))
}
var devices []string
for _, line := range strings.Split(string(out), "\n") {
Expand Down Expand Up @@ -666,7 +667,7 @@ func gatherIntelNVMeDisk(acc telegraf.Accumulator, timeout config.Duration, uses

_, er := exitStatus(e)
if er != nil {
acc.AddError(fmt.Errorf("failed to run command '%s %s': %s - %s", nvme, strings.Join(args, " "), e, outStr))
acc.AddError(fmt.Errorf("failed to run command '%s %s': %w - %s", nvme, strings.Join(args, " "), e, outStr))
return
}

Expand Down Expand Up @@ -735,7 +736,7 @@ func (m *Smart) gatherDisk(acc telegraf.Accumulator, device string, wg *sync.Wai
// Ignore all exit statuses except if it is a command line parse error
exitStatus, er := exitStatus(e)
if er != nil {
acc.AddError(fmt.Errorf("failed to run command '%s %s': %s - %s", m.PathSmartctl, strings.Join(args, " "), e, outStr))
acc.AddError(fmt.Errorf("failed to run command '%s %s': %w - %s", m.PathSmartctl, strings.Join(args, " "), e, outStr))
return
}

Expand Down Expand Up @@ -882,8 +883,9 @@ func (m *Smart) gatherDisk(acc telegraf.Accumulator, device string, wg *sync.Wai
// Command line parse errors are denoted by the exit code having the 0 bit set.
// All other errors are drive/communication errors and should be ignored.
func exitStatus(err error) (int, error) {
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(), nil
}
}
Expand Down
8 changes: 5 additions & 3 deletions plugins/inputs/snmp/netsnmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ func execCmd(arg0 string, args ...string) ([]byte, error) {

out, err := execCommand(arg0, args...).Output()
if err != nil {
if err, ok := err.(*exec.ExitError); ok {
return nil, fmt.Errorf("%s: %w", bytes.TrimRight(err.Stderr, "\r\n"), err)
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return nil, fmt.Errorf("%s: %w", bytes.TrimRight(exitErr.Stderr, "\r\n"), err)
}
return nil, err
}
Expand Down Expand Up @@ -194,7 +195,8 @@ func snmpTranslateCall(oid string) (mibName string, oidNum string, oidText strin
out, err = execCmd("snmptranslate", "-Td", "-Ob", oid)
} else {
out, err = execCmd("snmptranslate", "-Td", "-Ob", "-m", "all", oid)
if err, ok := err.(*exec.Error); ok && err.Err == exec.ErrNotFound {
var execErr *exec.Error
if errors.As(err, &execErr) && errors.Is(execErr, exec.ErrNotFound) {
// Silently discard error if snmptranslate not found and we have a numeric OID.
// Meaning we can get by without the lookup.
return "", oid, oid, "", nil
Expand Down
3 changes: 2 additions & 1 deletion plugins/inputs/snmp/snmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,8 @@ func (t Table) Build(gs snmpConnection, walk bool, tr Translator) (*RTable, erro
// Our callback always wraps errors in a walkError.
// If this error isn't a walkError, we know it's not
// from the callback
if _, ok := err.(*walkError); !ok {
var walkErr *walkError
if !errors.As(err, &walkErr) {
return nil, fmt.Errorf("performing bulk walk for field %s: %w", f.Name, err)
}
}
Expand Down
6 changes: 3 additions & 3 deletions plugins/inputs/snmp_trap/snmp_trap.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,15 +173,15 @@ func (s *SnmpTrap) Start(acc telegraf.Accumulator) error {

secname, err := s.SecName.Get()
if err != nil {
return fmt.Errorf("getting secname failed: %v", err)
return fmt.Errorf("getting secname failed: %w", err)
}
privPasswd, err := s.PrivPassword.Get()
if err != nil {
return fmt.Errorf("getting secname failed: %v", err)
return fmt.Errorf("getting secname failed: %w", err)
}
authPasswd, err := s.AuthPassword.Get()
if err != nil {
return fmt.Errorf("getting secname failed: %v", err)
return fmt.Errorf("getting secname failed: %w", err)
}
s.listener.Params.SecurityParameters = &gosnmp.UsmSecurityParameters{
UserName: string(secname),
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/socketstat/socketstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func socketList(cmdName string, proto string, timeout config.Duration) (*bytes.B
cmd.Stdout = &out
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running ss -in --%s: %v", proto, err)
return &out, fmt.Errorf("error running ss -in --%s: %w", proto, err)
}
return &out, nil
}
Expand Down
Loading

0 comments on commit e2a510f

Please sign in to comment.