From 312fb04b687e6eca7566f1b73d371a3d27292e70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Wed, 22 Feb 2023 21:38:06 +0100 Subject: [PATCH] chore: Fix linter findings for errorlint (part4) (#12723) Co-authored-by: Pawel Zak --- plugins/inputs/activemq/activemq.go | 6 ++--- plugins/inputs/amqp_consumer/amqp_consumer.go | 14 +++++----- plugins/inputs/apache/apache.go | 6 ++--- plugins/inputs/aurora/aurora.go | 8 +++--- plugins/inputs/bcache/bcache.go | 2 +- plugins/inputs/beanstalkd/beanstalkd_test.go | 3 ++- plugins/inputs/bind/bind.go | 2 +- plugins/inputs/bind/json_stats.go | 2 +- plugins/inputs/bind/xml_stats_v2.go | 2 +- plugins/inputs/bind/xml_stats_v3.go | 2 +- plugins/inputs/bond/bond.go | 10 +++---- plugins/inputs/burrow/burrow.go | 2 +- plugins/inputs/ceph/ceph.go | 24 ++++++++--------- plugins/inputs/chrony/chrony.go | 2 +- .../cisco_telemetry_mdt.go | 12 +++++---- .../cisco_telemetry_mdt_test.go | 12 ++++----- plugins/inputs/cloud_pubsub/cloud_pubsub.go | 10 +++---- plugins/inputs/cloudwatch/cloudwatch.go | 2 +- plugins/inputs/conntrack/conntrack.go | 4 +-- plugins/inputs/consul_agent/consul_agent.go | 10 +++---- plugins/inputs/couchdb/couchdb.go | 2 +- plugins/inputs/cpu/cpu.go | 2 +- plugins/inputs/dcos/creds.go | 2 +- plugins/inputs/dcos/dcos.go | 7 +++-- .../directory_monitor/directory_monitor.go | 7 ++--- plugins/inputs/disk/disk.go | 2 +- plugins/inputs/diskio/diskio.go | 4 +-- plugins/inputs/disque/disque.go | 8 +++--- plugins/inputs/dns_query/dns_query.go | 7 +++-- plugins/inputs/docker/docker.go | 23 ++++++++-------- plugins/inputs/docker_log/docker_log.go | 5 ++-- plugins/inputs/dovecot/dovecot.go | 14 +++++----- plugins/inputs/dpdk/dpdk.go | 18 ++++++------- plugins/inputs/dpdk/dpdk_connector.go | 26 +++++++++---------- plugins/inputs/dpdk/dpdk_connector_test.go | 2 +- plugins/inputs/dpdk/dpdk_utils.go | 8 +++--- .../elasticsearch_query/aggregation_query.go | 6 ++--- .../elasticsearch_query.go | 6 ++--- .../eventhub_consumer/eventhub_consumer.go | 2 +- plugins/inputs/exec/exec.go | 7 ++--- plugins/inputs/execd/execd.go | 5 ++-- plugins/inputs/execd/execd_posix.go | 4 +-- 42 files changed, 158 insertions(+), 144 deletions(-) diff --git a/plugins/inputs/activemq/activemq.go b/plugins/inputs/activemq/activemq.go index dc3930f63108c..0e74c76f02189 100644 --- a/plugins/inputs/activemq/activemq.go +++ b/plugins/inputs/activemq/activemq.go @@ -229,7 +229,7 @@ func (a *ActiveMQ) Gather(acc telegraf.Accumulator) error { queues := Queues{} err = xml.Unmarshal(dataQueues, &queues) if err != nil { - return fmt.Errorf("queues XML unmarshal error: %v", err) + return fmt.Errorf("queues XML unmarshal error: %w", err) } dataTopics, err := a.GetMetrics(a.TopicsURL()) @@ -239,7 +239,7 @@ func (a *ActiveMQ) Gather(acc telegraf.Accumulator) error { topics := Topics{} err = xml.Unmarshal(dataTopics, &topics) if err != nil { - return fmt.Errorf("topics XML unmarshal error: %v", err) + return fmt.Errorf("topics XML unmarshal error: %w", err) } dataSubscribers, err := a.GetMetrics(a.SubscribersURL()) @@ -249,7 +249,7 @@ func (a *ActiveMQ) Gather(acc telegraf.Accumulator) error { subscribers := Subscribers{} err = xml.Unmarshal(dataSubscribers, &subscribers) if err != nil { - return fmt.Errorf("subscribers XML unmarshal error: %v", err) + return fmt.Errorf("subscribers XML unmarshal error: %w", err) } a.GatherQueuesMetrics(acc, queues) diff --git a/plugins/inputs/amqp_consumer/amqp_consumer.go b/plugins/inputs/amqp_consumer/amqp_consumer.go index 606a2d70d7045..af0678b8a6b2b 100644 --- a/plugins/inputs/amqp_consumer/amqp_consumer.go +++ b/plugins/inputs/amqp_consumer/amqp_consumer.go @@ -213,7 +213,7 @@ func (a *AMQPConsumer) connect(amqpConf *amqp.Config) (<-chan amqp.Delivery, err ch, err := a.conn.Channel() if err != nil { - return nil, fmt.Errorf("failed to open a channel: %s", err.Error()) + return nil, fmt.Errorf("failed to open a channel: %w", err) } if a.Exchange != "" { @@ -250,7 +250,7 @@ func (a *AMQPConsumer) connect(amqpConf *amqp.Config) (<-chan amqp.Delivery, err nil, ) if err != nil { - return nil, fmt.Errorf("failed to bind a queue: %s", err) + return nil, fmt.Errorf("failed to bind a queue: %w", err) } } @@ -260,7 +260,7 @@ func (a *AMQPConsumer) connect(amqpConf *amqp.Config) (<-chan amqp.Delivery, err false, // global ) if err != nil { - return nil, fmt.Errorf("failed to set QoS: %s", err) + return nil, fmt.Errorf("failed to set QoS: %w", err) } msgs, err := ch.Consume( @@ -273,7 +273,7 @@ func (a *AMQPConsumer) connect(amqpConf *amqp.Config) (<-chan amqp.Delivery, err nil, // arguments ) if err != nil { - return nil, fmt.Errorf("failed establishing connection to queue: %s", err) + return nil, fmt.Errorf("failed establishing connection to queue: %w", err) } return msgs, err @@ -307,7 +307,7 @@ func (a *AMQPConsumer) declareExchange( ) } if err != nil { - return fmt.Errorf("error declaring exchange: %v", err) + return fmt.Errorf("error declaring exchange: %w", err) } return nil } @@ -341,7 +341,7 @@ func (a *AMQPConsumer) declareQueue(channel *amqp.Channel) (*amqp.Queue, error) ) } if err != nil { - return nil, fmt.Errorf("error declaring queue: %v", err) + return nil, fmt.Errorf("error declaring queue: %w", err) } return &queue, nil } @@ -442,7 +442,7 @@ func (a *AMQPConsumer) Stop() { a.cancel() a.wg.Wait() err := a.conn.Close() - if err != nil && err != amqp.ErrClosed { + if err != nil && !errors.Is(err, amqp.ErrClosed) { a.Log.Errorf("Error closing AMQP connection: %s", err) return } diff --git a/plugins/inputs/apache/apache.go b/plugins/inputs/apache/apache.go index 7cb01e322bc65..6263404faa549 100644 --- a/plugins/inputs/apache/apache.go +++ b/plugins/inputs/apache/apache.go @@ -57,7 +57,7 @@ func (n *Apache) Gather(acc telegraf.Accumulator) error { for _, u := range n.Urls { addr, err := url.Parse(u) if err != nil { - acc.AddError(fmt.Errorf("unable to parse address '%s': %s", u, err)) + acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err)) continue } @@ -91,7 +91,7 @@ func (n *Apache) createHTTPClient() (*http.Client, error) { func (n *Apache) gatherURL(addr *url.URL, acc telegraf.Accumulator) error { req, err := http.NewRequest("GET", addr.String(), nil) if err != nil { - return fmt.Errorf("error on new request to %s : %s", addr.String(), err) + return fmt.Errorf("error on new request to %q: %w", addr.String(), err) } if len(n.Username) != 0 && len(n.Password) != 0 { @@ -100,7 +100,7 @@ func (n *Apache) gatherURL(addr *url.URL, acc telegraf.Accumulator) error { resp, err := n.client.Do(req) if err != nil { - return fmt.Errorf("error on request to %s : %s", addr.String(), err) + return fmt.Errorf("error on request to %q: %w", addr.String(), err) } defer resp.Body.Close() diff --git a/plugins/inputs/aurora/aurora.go b/plugins/inputs/aurora/aurora.go index 178fcbca2c35c..a76ca835df4ed 100644 --- a/plugins/inputs/aurora/aurora.go +++ b/plugins/inputs/aurora/aurora.go @@ -81,7 +81,7 @@ func (a *Aurora) Gather(acc telegraf.Accumulator) error { defer wg.Done() role, err := a.gatherRole(ctx, u) if err != nil { - acc.AddError(fmt.Errorf("%s: %v", u, err)) + acc.AddError(fmt.Errorf("%s: %w", u, err)) return } @@ -91,7 +91,7 @@ func (a *Aurora) Gather(acc telegraf.Accumulator) error { err = a.gatherScheduler(ctx, u, role, acc) if err != nil { - acc.AddError(fmt.Errorf("%s: %v", u, err)) + acc.AddError(fmt.Errorf("%s: %w", u, err)) } }(u) } @@ -167,7 +167,7 @@ func (a *Aurora) gatherRole(ctx context.Context, origin *url.URL) (RoleType, err return Unknown, err } if err := resp.Body.Close(); err != nil { - return Unknown, fmt.Errorf("closing body failed: %v", err) + return Unknown, fmt.Errorf("closing body failed: %w", err) } switch resp.StatusCode { @@ -212,7 +212,7 @@ func (a *Aurora) gatherScheduler( decoder.UseNumber() err = decoder.Decode(&vars) if err != nil { - return fmt.Errorf("decoding response: %v", err) + return fmt.Errorf("decoding response: %w", err) } var fields = make(map[string]interface{}, len(vars)) diff --git a/plugins/inputs/bcache/bcache.go b/plugins/inputs/bcache/bcache.go index 6b58cc5a2001e..49b8b27826930 100644 --- a/plugins/inputs/bcache/bcache.go +++ b/plugins/inputs/bcache/bcache.go @@ -128,7 +128,7 @@ func (b *Bcache) Gather(acc telegraf.Accumulator) error { } } if err := b.gatherBcache(bdev, acc); err != nil { - return fmt.Errorf("gathering bcache failed: %v", err) + return fmt.Errorf("gathering bcache failed: %w", err) } } return nil diff --git a/plugins/inputs/beanstalkd/beanstalkd_test.go b/plugins/inputs/beanstalkd/beanstalkd_test.go index 9d97a682c4873..88c311103358d 100644 --- a/plugins/inputs/beanstalkd/beanstalkd_test.go +++ b/plugins/inputs/beanstalkd/beanstalkd_test.go @@ -1,6 +1,7 @@ package beanstalkd_test import ( + "errors" "io" "net" "net/textproto" @@ -121,7 +122,7 @@ func startTestServer(t *testing.T) (net.Listener, error) { for { cmd, err := tp.ReadLine() - if err == io.EOF { + if errors.Is(err, io.EOF) { return } else if err != nil { t.Log("Test server: failed read command. Error: ", err) diff --git a/plugins/inputs/bind/bind.go b/plugins/inputs/bind/bind.go index 6de609ead9e6d..c78d3a5cbeb3d 100644 --- a/plugins/inputs/bind/bind.go +++ b/plugins/inputs/bind/bind.go @@ -48,7 +48,7 @@ func (b *Bind) Gather(acc telegraf.Accumulator) error { for _, u := range b.Urls { addr, err := url.Parse(u) if err != nil { - acc.AddError(fmt.Errorf("unable to parse address '%s': %s", u, err)) + acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err)) continue } diff --git a/plugins/inputs/bind/json_stats.go b/plugins/inputs/bind/json_stats.go index 03661128a3a26..2283dc1158d5d 100644 --- a/plugins/inputs/bind/json_stats.go +++ b/plugins/inputs/bind/json_stats.go @@ -168,7 +168,7 @@ func (b *Bind) readStatsJSON(addr *url.URL, acc telegraf.Accumulator) error { } if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { - return fmt.Errorf("unable to decode JSON blob: %s", err) + return fmt.Errorf("unable to decode JSON blob: %w", err) } return nil diff --git a/plugins/inputs/bind/xml_stats_v2.go b/plugins/inputs/bind/xml_stats_v2.go index aed02aa5ec46f..62283358b4b48 100644 --- a/plugins/inputs/bind/xml_stats_v2.go +++ b/plugins/inputs/bind/xml_stats_v2.go @@ -101,7 +101,7 @@ func (b *Bind) readStatsXMLv2(addr *url.URL, acc telegraf.Accumulator) error { } if err := xml.NewDecoder(resp.Body).Decode(&stats); err != nil { - return fmt.Errorf("unable to decode XML document: %s", err) + return fmt.Errorf("unable to decode XML document: %w", err) } tags := map[string]string{"url": addr.Host} diff --git a/plugins/inputs/bind/xml_stats_v3.go b/plugins/inputs/bind/xml_stats_v3.go index b11678b3a5502..feffc72bf1210 100644 --- a/plugins/inputs/bind/xml_stats_v3.go +++ b/plugins/inputs/bind/xml_stats_v3.go @@ -153,7 +153,7 @@ func (b *Bind) readStatsXMLv3(addr *url.URL, acc telegraf.Accumulator) error { } if err := xml.NewDecoder(resp.Body).Decode(&stats); err != nil { - return fmt.Errorf("unable to decode XML document: %s", err) + return fmt.Errorf("unable to decode XML document: %w", err) } return nil diff --git a/plugins/inputs/bond/bond.go b/plugins/inputs/bond/bond.go index 1f2b43d095c44..3ccad44b077d6 100644 --- a/plugins/inputs/bond/bond.go +++ b/plugins/inputs/bond/bond.go @@ -55,13 +55,13 @@ func (bond *Bond) Gather(acc telegraf.Accumulator) error { bondAbsPath := bond.HostProc + "/net/bonding/" + bondName file, err := os.ReadFile(bondAbsPath) if err != nil { - acc.AddError(fmt.Errorf("error inspecting %q interface: %v", bondAbsPath, err)) + acc.AddError(fmt.Errorf("error inspecting %q interface: %w", bondAbsPath, err)) continue } rawProcFile := strings.TrimSpace(string(file)) err = bond.gatherBondInterface(bondName, rawProcFile, acc) if err != nil { - acc.AddError(fmt.Errorf("error inspecting %q interface: %v", bondName, err)) + acc.AddError(fmt.Errorf("error inspecting %q interface: %w", bondName, err)) } /* @@ -153,18 +153,18 @@ func (bond *Bond) readSysFiles(bondDir string) (sysFiles, error) { file, err := os.ReadFile(bondDir + "/bonding/mode") if err != nil { - return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/mode", err) + return sysFiles{}, fmt.Errorf("error inspecting %q interface: %w", bondDir+"/bonding/mode", err) } output.ModeFile = strings.TrimSpace(string(file)) file, err = os.ReadFile(bondDir + "/bonding/slaves") if err != nil { - return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/slaves", err) + return sysFiles{}, fmt.Errorf("error inspecting %q interface: %w", bondDir+"/bonding/slaves", err) } output.SlaveFile = strings.TrimSpace(string(file)) if bond.BondType == "IEEE 802.3ad Dynamic link aggregation" { file, err = os.ReadFile(bondDir + "/bonding/ad_num_ports") if err != nil { - return sysFiles{}, fmt.Errorf("error inspecting %q interface: %v", bondDir+"/bonding/ad_num_ports", err) + return sysFiles{}, fmt.Errorf("error inspecting %q interface: %w", bondDir+"/bonding/ad_num_ports", err) } output.ADPortsFile = strings.TrimSpace(string(file)) } diff --git a/plugins/inputs/burrow/burrow.go b/plugins/inputs/burrow/burrow.go index 0515444057372..c58f2f24b9264 100644 --- a/plugins/inputs/burrow/burrow.go +++ b/plugins/inputs/burrow/burrow.go @@ -123,7 +123,7 @@ func (b *burrow) Gather(acc telegraf.Accumulator) error { for _, addr := range b.Servers { u, err := url.Parse(addr) if err != nil { - acc.AddError(fmt.Errorf("unable to parse address '%s': %s", addr, err)) + acc.AddError(fmt.Errorf("unable to parse address %q: %w", addr, err)) continue } if u.Path == "" { diff --git a/plugins/inputs/ceph/ceph.go b/plugins/inputs/ceph/ceph.go index f32070ec35dd6..d586d3a018edd 100644 --- a/plugins/inputs/ceph/ceph.go +++ b/plugins/inputs/ceph/ceph.go @@ -70,18 +70,18 @@ func (c *Ceph) Gather(acc telegraf.Accumulator) error { func (c *Ceph) gatherAdminSocketStats(acc telegraf.Accumulator) error { sockets, err := findSockets(c) if err != nil { - return fmt.Errorf("failed to find sockets at path '%s': %v", c.SocketDir, err) + return fmt.Errorf("failed to find sockets at path %q: %w", c.SocketDir, err) } for _, s := range sockets { dump, err := perfDump(c.CephBinary, s) if err != nil { - acc.AddError(fmt.Errorf("error reading from socket '%s': %v", s.socket, err)) + acc.AddError(fmt.Errorf("error reading from socket %q: %w", s.socket, err)) continue } data, err := c.parseDump(dump) if err != nil { - acc.AddError(fmt.Errorf("error parsing dump from socket '%s': %v", s.socket, err)) + acc.AddError(fmt.Errorf("error parsing dump from socket %q: %w", s.socket, err)) continue } for tag, metrics := range data { @@ -107,11 +107,11 @@ func (c *Ceph) gatherClusterStats(acc telegraf.Accumulator) error { for _, job := range jobs { output, err := c.execute(job.command) if err != nil { - return fmt.Errorf("error executing command: %v", err) + return fmt.Errorf("error executing command: %w", err) } err = job.parser(acc, output) if err != nil { - return fmt.Errorf("error parsing output: %v", err) + return fmt.Errorf("error parsing output: %w", err) } } @@ -157,7 +157,7 @@ var perfDump = func(binary string, socket *socket) (string, error) { cmd.Stdout = &out err := cmd.Run() if err != nil { - return "", fmt.Errorf("error running ceph dump: %s", err) + return "", fmt.Errorf("error running ceph dump: %w", err) } return out.String(), nil @@ -166,7 +166,7 @@ var perfDump = func(binary string, socket *socket) (string, error) { var findSockets = func(c *Ceph) ([]*socket, error) { listing, err := os.ReadDir(c.SocketDir) if err != nil { - return []*socket{}, fmt.Errorf("Failed to read socket directory '%s': %v", c.SocketDir, err) + return []*socket{}, fmt.Errorf("failed to read socket directory %q: %w", c.SocketDir, err) } sockets := make([]*socket, 0, len(listing)) for _, info := range listing { @@ -239,7 +239,7 @@ func (c *Ceph) parseDump(dump string) (taggedMetricMap, error) { data := make(map[string]interface{}) err := json.Unmarshal([]byte(dump), &data) if err != nil { - return nil, fmt.Errorf("failed to parse json: '%s': %v", dump, err) + return nil, fmt.Errorf("failed to parse json: %q: %w", dump, err) } return c.newTaggedMetricMap(data), nil @@ -299,7 +299,7 @@ func (c *Ceph) execute(command string) (string, error) { cmd.Stdout = &out err := cmd.Run() if err != nil { - return "", fmt.Errorf("error running ceph %v: %s", command, err) + return "", fmt.Errorf("error running ceph %q: %w", command, err) } output := out.String() @@ -378,7 +378,7 @@ type CephStatus struct { func decodeStatus(acc telegraf.Accumulator, input string) error { data := &CephStatus{} if err := json.Unmarshal([]byte(input), data); err != nil { - return fmt.Errorf("failed to parse json: '%s': %v", input, err) + return fmt.Errorf("failed to parse json: %q: %w", input, err) } decoders := []func(telegraf.Accumulator, *CephStatus) error{ @@ -539,7 +539,7 @@ type CephDf struct { func decodeDf(acc telegraf.Accumulator, input string) error { data := &CephDf{} if err := json.Unmarshal([]byte(input), data); err != nil { - return fmt.Errorf("failed to parse json: '%s': %v", input, err) + return fmt.Errorf("failed to parse json: %q: %w", input, err) } // ceph.usage: records global utilization and number of objects @@ -618,7 +618,7 @@ type CephOSDPoolStats []struct { func decodeOsdPoolStats(acc telegraf.Accumulator, input string) error { data := CephOSDPoolStats{} if err := json.Unmarshal([]byte(input), &data); err != nil { - return fmt.Errorf("failed to parse json: '%s': %v", input, err) + return fmt.Errorf("failed to parse json: %q: %w", input, err) } // ceph.pool.stats: records pre pool IO and recovery throughput diff --git a/plugins/inputs/chrony/chrony.go b/plugins/inputs/chrony/chrony.go index b56052f60116a..34d7fc3033d4c 100644 --- a/plugins/inputs/chrony/chrony.go +++ b/plugins/inputs/chrony/chrony.go @@ -50,7 +50,7 @@ func (c *Chrony) Gather(acc telegraf.Accumulator) error { cmd := execCommand(c.path, flags...) out, err := internal.CombinedOutputTimeout(cmd, time.Second*5) 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)) } fields, tags, err := processChronycOutput(string(out)) if err != nil { diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go index 2d13f5452ef6e..29b13d65ba56a 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go @@ -6,6 +6,7 @@ import ( _ "embed" "encoding/binary" "encoding/json" + "errors" "fmt" "io" "net" @@ -224,7 +225,8 @@ func (c *CiscoTelemetryMDT) acceptTCPClients() { for { conn, err := c.listener.Accept() - if neterr, ok := err.(*net.OpError); ok && (neterr.Timeout() || neterr.Temporary()) { + var neterr *net.OpError + if errors.As(err, &neterr) && (neterr.Timeout() || neterr.Temporary()) { continue } else if err != nil { break // Stop() will close the connection so Accept() will fail here @@ -319,8 +321,8 @@ func (c *CiscoTelemetryMDT) MdtDialout(stream dialout.GRPCMdtDialout_MdtDialoutS for { packet, err := stream.Recv() if err != nil { - if err != io.EOF { - c.acc.AddError(fmt.Errorf("GRPC dialout receive error: %v", err)) + if !errors.Is(err, io.EOF) { + c.acc.AddError(fmt.Errorf("GRPC dialout receive error: %w", err)) } break } @@ -335,7 +337,7 @@ func (c *CiscoTelemetryMDT) MdtDialout(stream dialout.GRPCMdtDialout_MdtDialoutS c.handleTelemetry(packet.Data) } else if int(packet.TotalSize) <= c.MaxMsgSize { if _, err := chunkBuffer.Write(packet.Data); err != nil { - c.acc.AddError(fmt.Errorf("writing packet %q failed: %v", packet.Data, err)) + c.acc.AddError(fmt.Errorf("writing packet %q failed: %w", packet.Data, err)) } if chunkBuffer.Len() >= int(packet.TotalSize) { c.handleTelemetry(chunkBuffer.Bytes()) @@ -358,7 +360,7 @@ func (c *CiscoTelemetryMDT) handleTelemetry(data []byte) { msg := &telemetry.Telemetry{} err := proto.Unmarshal(data, msg) if err != nil { - c.acc.AddError(fmt.Errorf("failed to decode: %v", err)) + c.acc.AddError(fmt.Errorf("failed to decode: %w", err)) return } diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go index 25fb2227b557d..bca9731bd3422 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go @@ -756,7 +756,7 @@ func TestTCPDialoutOverflow(t *testing.T) { require.NoError(t, err) require.NoError(t, binary.Write(conn, binary.BigEndian, hdr)) _, err = conn.Read([]byte{0}) - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) require.NoError(t, conn.Close()) c.Stop() @@ -838,7 +838,7 @@ func TestTCPDialoutMultiple(t *testing.T) { _, err = conn2.Write([]byte{0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}) require.NoError(t, err) _, err = conn2.Read([]byte{0}) - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) require.NoError(t, conn2.Close()) telemetry.EncodingPath = "type:model/other/path" @@ -851,7 +851,7 @@ func TestTCPDialoutMultiple(t *testing.T) { _, err = conn.Write([]byte{0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}) require.NoError(t, err) _, err = conn.Read([]byte{0}) - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) c.Stop() require.NoError(t, conn.Close()) @@ -889,7 +889,7 @@ func TestGRPCDialoutError(t *testing.T) { // Wait for the server to close _, err = stream.Recv() - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) c.Stop() require.Equal(t, acc.Errors, []error{errors.New("GRPC dialout error: foobar")}) @@ -928,7 +928,7 @@ func TestGRPCDialoutMultiple(t *testing.T) { require.NoError(t, stream2.Send(args)) require.NoError(t, stream2.Send(&dialout.MdtDialoutArgs{Errors: "testclose"})) _, err = stream2.Recv() - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) require.NoError(t, conn2.Close()) telemetry.EncodingPath = "type:model/other/path" @@ -938,7 +938,7 @@ func TestGRPCDialoutMultiple(t *testing.T) { require.NoError(t, stream.Send(args)) require.NoError(t, stream.Send(&dialout.MdtDialoutArgs{Errors: "testclose"})) _, err = stream.Recv() - require.True(t, err == nil || err == io.EOF) + require.True(t, err == nil || errors.Is(err, io.EOF)) c.Stop() require.NoError(t, conn.Close()) diff --git a/plugins/inputs/cloud_pubsub/cloud_pubsub.go b/plugins/inputs/cloud_pubsub/cloud_pubsub.go index be52ddde9999e..70e723d59ee83 100644 --- a/plugins/inputs/cloud_pubsub/cloud_pubsub.go +++ b/plugins/inputs/cloud_pubsub/cloud_pubsub.go @@ -102,7 +102,7 @@ func (ps *PubSub) Start(ac telegraf.Accumulator) error { } else { subRef, err := ps.getGCPSubscription(ps.Subscription) if err != nil { - return fmt.Errorf("unable to create subscription handle: %v", err) + return fmt.Errorf("unable to create subscription handle: %w", err) } ps.sub = subRef } @@ -157,11 +157,11 @@ func (ps *PubSub) startReceiver(parentCtx context.Context) error { cctx, ccancel := context.WithCancel(parentCtx) err := ps.sub.Receive(cctx, func(ctx context.Context, msg message) { if err := ps.onMessage(ctx, msg); err != nil { - ps.acc.AddError(fmt.Errorf("unable to add message from subscription %s: %v", ps.sub.ID(), err)) + ps.acc.AddError(fmt.Errorf("unable to add message from subscription %s: %w", ps.sub.ID(), err)) } }) if err != nil { - ps.acc.AddError(fmt.Errorf("receiver for subscription %s exited: %v", ps.sub.ID(), err)) + ps.acc.AddError(fmt.Errorf("receiver for subscription %s exited: %w", ps.sub.ID(), err)) } else { ps.Log.Info("Subscription pull ended (no error, most likely stopped)") } @@ -180,7 +180,7 @@ func (ps *PubSub) onMessage(ctx context.Context, msg message) error { if ps.Base64Data { strData, err := base64.StdEncoding.DecodeString(string(msg.Data())) if err != nil { - return fmt.Errorf("unable to base64 decode message: %v", err) + return fmt.Errorf("unable to base64 decode message: %w", err) } data = strData } else { @@ -266,7 +266,7 @@ func (ps *PubSub) getPubSubClient() (*pubsub.Client, error) { option.WithUserAgent(internal.ProductToken()), ) if err != nil { - return nil, fmt.Errorf("unable to generate PubSub client: %v", err) + return nil, fmt.Errorf("unable to generate PubSub client: %w", err) } return client, nil } diff --git a/plugins/inputs/cloudwatch/cloudwatch.go b/plugins/inputs/cloudwatch/cloudwatch.go index 8c4aaeb2213af..1e26b9d2ba9a0 100644 --- a/plugins/inputs/cloudwatch/cloudwatch.go +++ b/plugins/inputs/cloudwatch/cloudwatch.go @@ -465,7 +465,7 @@ func (c *CloudWatch) gatherMetrics( for { resp, err := c.client.GetMetricData(context.Background(), params) if err != nil { - return nil, fmt.Errorf("failed to get metric data: %v", err) + return nil, fmt.Errorf("failed to get metric data: %w", err) } results = append(results, resp.MetricDataResults...) diff --git a/plugins/inputs/conntrack/conntrack.go b/plugins/inputs/conntrack/conntrack.go index 0e08d269bb6ec..6846dec5b1bae 100644 --- a/plugins/inputs/conntrack/conntrack.go +++ b/plugins/inputs/conntrack/conntrack.go @@ -89,7 +89,7 @@ func (c *Conntrack) Gather(acc telegraf.Accumulator) error { contents, err := os.ReadFile(fName) if err != nil { - acc.AddError(fmt.Errorf("failed to read file '%s': %v", fName, err)) + acc.AddError(fmt.Errorf("failed to read file %q: %w", fName, err)) continue } @@ -106,7 +106,7 @@ func (c *Conntrack) Gather(acc telegraf.Accumulator) error { perCPU := metric == "percpu" stats, err := c.ps.NetConntrack(perCPU) if err != nil { - acc.AddError(fmt.Errorf("failed to retrieve conntrack statistics: %v", err)) + acc.AddError(fmt.Errorf("failed to retrieve conntrack statistics: %w", err)) } if len(stats) == 0 { diff --git a/plugins/inputs/consul_agent/consul_agent.go b/plugins/inputs/consul_agent/consul_agent.go index 37e773fe7810b..0ab05c81c67fb 100644 --- a/plugins/inputs/consul_agent/consul_agent.go +++ b/plugins/inputs/consul_agent/consul_agent.go @@ -60,14 +60,14 @@ func (n *ConsulAgent) Init() error { if n.TokenFile != "" { token, err := os.ReadFile(n.TokenFile) if err != nil { - return fmt.Errorf("reading file failed: %v", err) + return fmt.Errorf("reading file failed: %w", err) } n.Token = strings.TrimSpace(string(token)) } tlsCfg, err := n.ClientConfig.TLSConfig() if err != nil { - return fmt.Errorf("setting up TLS configuration failed: %v", err) + return fmt.Errorf("setting up TLS configuration failed: %w", err) } n.roundTripper = &http.Transport{ @@ -100,7 +100,7 @@ func (n *ConsulAgent) loadJSON(url string) (*AgentInfo, error) { resp, err := n.roundTripper.RoundTrip(req) if err != nil { - return nil, fmt.Errorf("error making HTTP request to %s: %s", url, err) + return nil, fmt.Errorf("error making HTTP request to %q: %w", url, err) } defer resp.Body.Close() @@ -111,7 +111,7 @@ func (n *ConsulAgent) loadJSON(url string) (*AgentInfo, error) { var metrics AgentInfo err = json.NewDecoder(resp.Body).Decode(&metrics) if err != nil { - return nil, fmt.Errorf("error parsing json response: %s", err) + return nil, fmt.Errorf("error parsing json response: %w", err) } return &metrics, nil @@ -121,7 +121,7 @@ func (n *ConsulAgent) loadJSON(url string) (*AgentInfo, error) { func buildConsulAgent(acc telegraf.Accumulator, agentInfo *AgentInfo) error { t, err := time.Parse(timeLayout, agentInfo.Timestamp) if err != nil { - return fmt.Errorf("error parsing time: %s", err) + return fmt.Errorf("error parsing time: %w", err) } for _, counters := range agentInfo.Counters { diff --git a/plugins/inputs/couchdb/couchdb.go b/plugins/inputs/couchdb/couchdb.go index 90088b6a7c302..f035183f4e24d 100644 --- a/plugins/inputs/couchdb/couchdb.go +++ b/plugins/inputs/couchdb/couchdb.go @@ -104,7 +104,7 @@ func (c *CouchDB) Gather(accumulator telegraf.Accumulator) error { go func(host string) { defer wg.Done() if err := c.fetchAndInsertData(accumulator, host); err != nil { - accumulator.AddError(fmt.Errorf("[host=%s]: %s", host, err)) + accumulator.AddError(fmt.Errorf("[host=%s]: %w", host, err)) } }(u) } diff --git a/plugins/inputs/cpu/cpu.go b/plugins/inputs/cpu/cpu.go index ee626e9039867..b26a650d33811 100644 --- a/plugins/inputs/cpu/cpu.go +++ b/plugins/inputs/cpu/cpu.go @@ -47,7 +47,7 @@ func (*CPUStats) SampleConfig() string { func (c *CPUStats) Gather(acc telegraf.Accumulator) error { times, err := c.ps.CPUTimes(c.PerCPU, c.TotalCPU) if err != nil { - return fmt.Errorf("error getting CPU info: %s", err) + return fmt.Errorf("error getting CPU info: %w", err) } now := time.Now() diff --git a/plugins/inputs/dcos/creds.go b/plugins/inputs/dcos/creds.go index 328ce394a4cf6..ded7fa5660f9d 100644 --- a/plugins/inputs/dcos/creds.go +++ b/plugins/inputs/dcos/creds.go @@ -50,7 +50,7 @@ func (c *ServiceAccount) IsExpired() bool { func (c *TokenCreds) Token(_ context.Context, _ Client) (string, error) { octets, err := os.ReadFile(c.Path) if err != nil { - return "", fmt.Errorf("error reading token file %q: %s", c.Path, err) + return "", fmt.Errorf("error reading token file %q: %w", c.Path, err) } if !utf8.Valid(octets) { return "", fmt.Errorf("token file does not contain utf-8 encoded text: %s", c.Path) diff --git a/plugins/inputs/dcos/dcos.go b/plugins/inputs/dcos/dcos.go index c2958122ac7ad..b9977660f07a6 100644 --- a/plugins/inputs/dcos/dcos.go +++ b/plugins/inputs/dcos/dcos.go @@ -4,6 +4,7 @@ package dcos import ( "context" _ "embed" + "errors" "net/url" "os" "sort" @@ -146,7 +147,8 @@ func (d *DCOS) GatherContainers(ctx context.Context, acc telegraf.Accumulator, c defer wg.Done() m, err := d.client.GetContainerMetrics(ctx, node, container) if err != nil { - if err, ok := err.(APIError); ok && err.StatusCode == 404 { + var apiErr APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == 404 { return } acc.AddError(err) @@ -162,7 +164,8 @@ func (d *DCOS) GatherContainers(ctx context.Context, acc telegraf.Accumulator, c defer wg.Done() m, err := d.client.GetAppMetrics(ctx, node, container) if err != nil { - if err, ok := err.(APIError); ok && err.StatusCode == 404 { + var apiErr APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == 404 { return } acc.AddError(err) diff --git a/plugins/inputs/directory_monitor/directory_monitor.go b/plugins/inputs/directory_monitor/directory_monitor.go index 574297edd5dde..e82402afe018f 100644 --- a/plugins/inputs/directory_monitor/directory_monitor.go +++ b/plugins/inputs/directory_monitor/directory_monitor.go @@ -103,7 +103,7 @@ func (monitor *DirectoryMonitor) Gather(_ telegraf.Accumulator) error { return processFile(path) }) // We've been cancelled via Stop(). - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } if err != nil { @@ -123,7 +123,7 @@ func (monitor *DirectoryMonitor) Gather(_ telegraf.Accumulator) error { path := monitor.Directory + "/" + file.Name() err := processFile(path) // We've been cancelled via Stop(). - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } } @@ -199,7 +199,8 @@ func (monitor *DirectoryMonitor) processFile(path string) { func (monitor *DirectoryMonitor) read(filePath string) { // Open, read, and parse the contents of the file. err := monitor.ingestFile(filePath) - if _, isPathError := err.(*os.PathError); isPathError { + var pathErr *os.PathError + if errors.As(err, &pathErr) { return } diff --git a/plugins/inputs/disk/disk.go b/plugins/inputs/disk/disk.go index f90227a495930..f9f33433a7e77 100644 --- a/plugins/inputs/disk/disk.go +++ b/plugins/inputs/disk/disk.go @@ -47,7 +47,7 @@ func (ds *DiskStats) Init() error { func (ds *DiskStats) Gather(acc telegraf.Accumulator) error { disks, partitions, err := ds.ps.DiskUsage(ds.MountPoints, ds.IgnoreMountOpts, ds.IgnoreFS) if err != nil { - return fmt.Errorf("error getting disk usage info: %s", err) + return fmt.Errorf("error getting disk usage info: %w", err) } for i, du := range disks { if du.Total == 0 { diff --git a/plugins/inputs/diskio/diskio.go b/plugins/inputs/diskio/diskio.go index fac62e81c2363..5f2d9993ffd8b 100644 --- a/plugins/inputs/diskio/diskio.go +++ b/plugins/inputs/diskio/diskio.go @@ -48,7 +48,7 @@ func (d *DiskIO) Init() error { if hasMeta(device) { deviceFilter, err := filter.Compile(d.Devices) if err != nil { - return fmt.Errorf("error compiling device pattern: %s", err.Error()) + return fmt.Errorf("error compiling device pattern: %w", err) } d.deviceFilter = deviceFilter } @@ -66,7 +66,7 @@ func (d *DiskIO) Gather(acc telegraf.Accumulator) error { diskio, err := d.ps.DiskIO(devices) if err != nil { - return fmt.Errorf("error getting disk io info: %s", err.Error()) + return fmt.Errorf("error getting disk io info: %w", err) } for _, io := range diskio { diff --git a/plugins/inputs/disque/disque.go b/plugins/inputs/disque/disque.go index d21182bf2332f..f9dc218d0d126 100644 --- a/plugins/inputs/disque/disque.go +++ b/plugins/inputs/disque/disque.go @@ -69,7 +69,7 @@ func (d *Disque) Gather(acc telegraf.Accumulator) error { for _, serv := range d.Servers { u, err := url.Parse(serv) if err != nil { - acc.AddError(fmt.Errorf("unable to parse to address '%s': %s", serv, err)) + acc.AddError(fmt.Errorf("unable to parse to address %q: %w", serv, err)) continue } else if u.Scheme == "" { // fallback to simple string based address (i.e. "10.0.0.1:10000") @@ -100,7 +100,7 @@ func (d *Disque) gatherServer(addr *url.URL, acc telegraf.Accumulator) error { c, err := net.DialTimeout("tcp", addr.Host, defaultTimeout) if err != nil { - return fmt.Errorf("unable to connect to disque server '%s': %s", addr.Host, err) + return fmt.Errorf("unable to connect to disque server %q: %w", addr.Host, err) } if addr.User != nil { @@ -142,7 +142,7 @@ func (d *Disque) gatherServer(addr *url.URL, acc telegraf.Accumulator) error { } if line[0] != '$' { - return fmt.Errorf("bad line start: %s", ErrProtocolError) + return fmt.Errorf("bad line start: %w", ErrProtocolError) } line = strings.TrimSpace(line) @@ -151,7 +151,7 @@ func (d *Disque) gatherServer(addr *url.URL, acc telegraf.Accumulator) error { sz, err := strconv.Atoi(szStr) if err != nil { - return fmt.Errorf("bad size string <<%s>>: %s", szStr, ErrProtocolError) + return fmt.Errorf("bad size string <<%s>>: %w", szStr, ErrProtocolError) } var read int diff --git a/plugins/inputs/dns_query/dns_query.go b/plugins/inputs/dns_query/dns_query.go index b987e5a99affa..c23257707c2c1 100644 --- a/plugins/inputs/dns_query/dns_query.go +++ b/plugins/inputs/dns_query/dns_query.go @@ -3,6 +3,7 @@ package dns_query import ( _ "embed" + "errors" "fmt" "net" "strconv" @@ -87,7 +88,8 @@ func (d *DNSQuery) Gather(acc telegraf.Accumulator) error { fields, tags, err := d.query(domain, server) if err != nil { - if opErr, ok := err.(*net.OpError); !ok || !opErr.Timeout() { + var opErr *net.OpError + if !errors.As(err, &opErr) || !opErr.Timeout() { acc.AddError(err) } } @@ -130,7 +132,8 @@ func (d *DNSQuery) query(domain string, server string) (map[string]interface{}, addr := net.JoinHostPort(server, strconv.Itoa(d.Port)) r, rtt, err := c.Exchange(&msg, addr) if err != nil { - if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Timeout() { tags["result"] = "timeout" fields["result_code"] = uint64(Timeout) return fields, tags, err diff --git a/plugins/inputs/docker/docker.go b/plugins/inputs/docker/docker.go index 3882847feff50..a91769106aec9 100644 --- a/plugins/inputs/docker/docker.go +++ b/plugins/inputs/docker/docker.go @@ -6,6 +6,7 @@ import ( "crypto/tls" _ "embed" "encoding/json" + "errors" "fmt" "io" "regexp" @@ -95,12 +96,12 @@ func (*Docker) SampleConfig() string { func (d *Docker) Init() error { err := choice.CheckSlice(d.PerDeviceInclude, containerMetricClasses) if err != nil { - return fmt.Errorf("error validating 'perdevice_include' setting : %v", err) + return fmt.Errorf("error validating 'perdevice_include' setting: %w", err) } err = choice.CheckSlice(d.TotalInclude, containerMetricClasses) if err != nil { - return fmt.Errorf("error validating 'total_include' setting : %v", err) + return fmt.Errorf("error validating 'total_include' setting: %w", err) } // Temporary logic needed for backwards compatibility until 'perdevice' setting is removed. @@ -188,7 +189,7 @@ func (d *Docker) Gather(acc telegraf.Accumulator) error { defer cancel() containers, err := d.client.ContainerList(ctx, opts) - if err == context.DeadlineExceeded { + if errors.Is(err, context.DeadlineExceeded) { return errListTimeout } if err != nil { @@ -216,7 +217,7 @@ func (d *Docker) gatherSwarmInfo(acc telegraf.Accumulator) error { defer cancel() services, err := d.client.ServiceList(ctx, types.ServiceListOptions{}) - if err == context.DeadlineExceeded { + if errors.Is(err, context.DeadlineExceeded) { return errServiceTimeout } if err != nil { @@ -293,7 +294,7 @@ func (d *Docker) gatherInfo(acc telegraf.Accumulator) error { defer cancel() info, err := d.client.Info(ctx) - if err == context.DeadlineExceeded { + if errors.Is(err, context.DeadlineExceeded) { return errInfoTimeout } if err != nil { @@ -453,20 +454,20 @@ func (d *Docker) gatherContainer( defer cancel() r, err := d.client.ContainerStats(ctx, container.ID, false) - if err == context.DeadlineExceeded { + if errors.Is(err, context.DeadlineExceeded) { return errStatsTimeout } if err != nil { - return fmt.Errorf("error getting docker stats: %v", err) + return fmt.Errorf("error getting docker stats: %w", err) } defer r.Body.Close() dec := json.NewDecoder(r.Body) if err = dec.Decode(&v); err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { return nil } - return fmt.Errorf("error decoding: %v", err) + return fmt.Errorf("error decoding: %w", err) } daemonOSType := r.OSType @@ -491,11 +492,11 @@ func (d *Docker) gatherContainerInspect( defer cancel() info, err := d.client.ContainerInspect(ctx, container.ID) - if err == context.DeadlineExceeded { + if errors.Is(err, context.DeadlineExceeded) { return errInspectTimeout } if err != nil { - return fmt.Errorf("error inspecting docker container: %v", err) + return fmt.Errorf("error inspecting docker container: %w", err) } // Add whitelisted environment variables to tags diff --git a/plugins/inputs/docker_log/docker_log.go b/plugins/inputs/docker_log/docker_log.go index ac27cf22bff3d..552940916f20a 100644 --- a/plugins/inputs/docker_log/docker_log.go +++ b/plugins/inputs/docker_log/docker_log.go @@ -7,6 +7,7 @@ import ( "context" "crypto/tls" _ "embed" + "errors" "fmt" "io" "strings" @@ -189,7 +190,7 @@ func (d *DockerLogs) Gather(acc telegraf.Accumulator) error { defer d.removeFromContainerList(container.ID) err = d.tailContainerLogs(ctx, acc, container, containerName) - if err != nil && err != context.Canceled { + if err != nil && !errors.Is(err, context.Canceled) { acc.AddError(err) } }(container) @@ -284,7 +285,7 @@ func parseLine(line []byte) (time.Time, string, error) { ts, err := time.Parse(time.RFC3339Nano, tsString) if err != nil { - return time.Time{}, "", fmt.Errorf("error parsing timestamp %q: %v", tsString, err) + return time.Time{}, "", fmt.Errorf("error parsing timestamp %q: %w", tsString, err) } return ts, string(message), nil diff --git a/plugins/inputs/dovecot/dovecot.go b/plugins/inputs/dovecot/dovecot.go index 0e35999b2925c..2e2826e12f021 100644 --- a/plugins/inputs/dovecot/dovecot.go +++ b/plugins/inputs/dovecot/dovecot.go @@ -4,6 +4,7 @@ package dovecot import ( "bytes" _ "embed" + "errors" "fmt" "io" "net" @@ -74,19 +75,19 @@ func (d *Dovecot) gatherServer(addr string, acc telegraf.Accumulator, qtype stri _, _, err := net.SplitHostPort(addr) if err != nil { - return fmt.Errorf("%q on url %s", err.Error(), addr) + return fmt.Errorf("%w on url %q", err, addr) } } c, err := net.DialTimeout(proto, addr, defaultTimeout) if err != nil { - return fmt.Errorf("unable to connect to dovecot server '%s': %s", addr, err) + return fmt.Errorf("unable to connect to dovecot server %q: %w", addr, err) } defer c.Close() // Extend connection if err := c.SetDeadline(time.Now().Add(defaultTimeout)); err != nil { - return fmt.Errorf("setting deadline failed for dovecot server '%s': %s", addr, err) + return fmt.Errorf("setting deadline failed for dovecot server %q: %w", addr, err) } msg := fmt.Sprintf("EXPORT\t%s", qtype) @@ -96,15 +97,16 @@ func (d *Dovecot) gatherServer(addr string, acc telegraf.Accumulator, qtype stri msg += "\n" if _, err := c.Write([]byte(msg)); err != nil { - return fmt.Errorf("writing message %q failed for dovecot server '%s': %s", msg, addr, err) + return fmt.Errorf("writing message %q failed for dovecot server %q: %w", msg, addr, err) } var buf bytes.Buffer if _, err := io.Copy(&buf, c); err != nil { // We need to accept the timeout here as reading from the connection will only terminate on EOF // or on a timeout to happen. As EOF for TCP connections will only be sent on connection closing, // the only way to get the whole message is to wait for the timeout to happen. - if nerr, ok := err.(net.Error); !ok || !nerr.Timeout() { - return fmt.Errorf("copying message failed for dovecot server '%s': %s", addr, err) + var nerr net.Error + if !errors.As(err, &nerr) || !nerr.Timeout() { + return fmt.Errorf("copying message failed for dovecot server %q: %w", addr, err) } } diff --git a/plugins/inputs/dpdk/dpdk.go b/plugins/inputs/dpdk/dpdk.go index 7d4daeb37b3d4..e6d225c57bb9d 100644 --- a/plugins/inputs/dpdk/dpdk.go +++ b/plugins/inputs/dpdk/dpdk.go @@ -96,7 +96,7 @@ func (dpdk *dpdk) Init() error { dpdk.ethdevExcludedCommandsFilter, err = filter.Compile(dpdk.EthdevConfig.EthdevExcludeCommands) if err != nil { - return fmt.Errorf("error occurred during filter prepation for ethdev excluded commands - %v", err) + return fmt.Errorf("error occurred during filter prepation for ethdev excluded commands: %w", err) } dpdk.connector = newDpdkConnector(dpdk.SocketPath, dpdk.AccessTimeout) @@ -118,15 +118,15 @@ func (dpdk *dpdk) validateCommands() error { } if commandWithParams[0] != '/' { - return fmt.Errorf("'%v' command should start with '/'", commandWithParams) + return fmt.Errorf("%q command should start with '/'", commandWithParams) } if commandWithoutParams := stripParams(commandWithParams); len(commandWithoutParams) >= maxCommandLength { - return fmt.Errorf("'%v' command is too long. It shall be less than %v characters", commandWithoutParams, maxCommandLength) + return fmt.Errorf("%q command is too long. It shall be less than %v characters", commandWithoutParams, maxCommandLength) } if len(commandWithParams) >= maxCommandLengthWithParams { - return fmt.Errorf("command with parameters '%v' shall be less than %v characters", commandWithParams, maxCommandLengthWithParams) + return fmt.Errorf("command with parameters %q shall be less than %v characters", commandWithParams, maxCommandLengthWithParams) } } @@ -154,7 +154,7 @@ func (dpdk *dpdk) gatherCommands(acc telegraf.Accumulator) []string { ethdevCommands := removeSubset(dpdk.ethdevCommands, dpdk.ethdevExcludedCommandsFilter) ethdevCommands, err := dpdk.appendCommandsWithParamsFromList(ethdevListCommand, ethdevCommands) if err != nil { - acc.AddError(fmt.Errorf("error occurred during fetching of %v params - %v", ethdevListCommand, err)) + acc.AddError(fmt.Errorf("error occurred during fetching of %q params: %w", ethdevListCommand, err)) } commands = append(commands, ethdevCommands...) @@ -163,7 +163,7 @@ func (dpdk *dpdk) gatherCommands(acc telegraf.Accumulator) []string { if choice.Contains("rawdev", dpdk.DeviceTypes) { rawdevCommands, err := dpdk.appendCommandsWithParamsFromList(rawdevListCommand, dpdk.rawdevCommands) if err != nil { - acc.AddError(fmt.Errorf("error occurred during fetching of %v params - %v", rawdevListCommand, err)) + acc.AddError(fmt.Errorf("error occurred during fetching of %q params: %w", rawdevListCommand, err)) } commands = append(commands, rawdevCommands...) @@ -206,21 +206,21 @@ func (dpdk *dpdk) processCommand(acc telegraf.Accumulator, commandWithParams str var parsedResponse map[string]interface{} err = json.Unmarshal(buf, &parsedResponse) if err != nil { - acc.AddError(fmt.Errorf("failed to unmarshall json response from %v command - %v", commandWithParams, err)) + acc.AddError(fmt.Errorf("failed to unmarshall json response from %q command: %w", commandWithParams, err)) return } command := stripParams(commandWithParams) value := parsedResponse[command] if isEmpty(value) { - acc.AddError(fmt.Errorf("got empty json on '%v' command", commandWithParams)) + acc.AddError(fmt.Errorf("got empty json on %q command", commandWithParams)) return } jf := jsonparser.JSONFlattener{} err = jf.FullFlattenJSON("", value, true, true) if err != nil { - acc.AddError(fmt.Errorf("failed to flatten response - %v", err)) + acc.AddError(fmt.Errorf("failed to flatten response: %w", err)) return } diff --git a/plugins/inputs/dpdk/dpdk_connector.go b/plugins/inputs/dpdk/dpdk_connector.go index c8538f77fb3e1..40e9a009123d4 100644 --- a/plugins/inputs/dpdk/dpdk_connector.go +++ b/plugins/inputs/dpdk/dpdk_connector.go @@ -40,14 +40,14 @@ func newDpdkConnector(pathToSocket string, accessTimeout config.Duration) *dpdkC func (conn *dpdkConnector) connect() (*initMessage, error) { connection, err := net.Dial("unixpacket", conn.pathToSocket) if err != nil { - return nil, fmt.Errorf("failed to connect to the socket - %v", err) + return nil, fmt.Errorf("failed to connect to the socket: %w", err) } conn.connection = connection result, err := conn.readMaxOutputLen() if err != nil { if closeErr := conn.tryClose(); closeErr != nil { - return nil, fmt.Errorf("%v and failed to close connection - %v", err, closeErr) + return nil, fmt.Errorf("%w and failed to close connection: %w", err, closeErr) } return nil, err } @@ -61,35 +61,33 @@ func (conn *dpdkConnector) connect() (*initMessage, error) { func (conn *dpdkConnector) getCommandResponse(fullCommand string) ([]byte, error) { connection, err := conn.getConnection() if err != nil { - return nil, fmt.Errorf("failed to get connection to execute %v command - %v", fullCommand, err) + return nil, fmt.Errorf("failed to get connection to execute %q command: %w", fullCommand, err) } err = conn.setTimeout() if err != nil { - return nil, fmt.Errorf("failed to set timeout for %v command - %v", fullCommand, err) + return nil, fmt.Errorf("failed to set timeout for %q command: %w", fullCommand, err) } _, err = connection.Write([]byte(fullCommand)) if err != nil { if closeErr := conn.tryClose(); closeErr != nil { - return nil, fmt.Errorf("failed to send '%v' command - %v and failed to close connection - %v", - fullCommand, err, closeErr) + return nil, fmt.Errorf("failed to send %q command: %w and failed to close connection: %w", fullCommand, err, closeErr) } - return nil, fmt.Errorf("failed to send '%v' command - %v", fullCommand, err) + return nil, fmt.Errorf("failed to send %q command: %w", fullCommand, err) } buf := make([]byte, conn.maxOutputLen) messageLength, err := connection.Read(buf) if err != nil { if closeErr := conn.tryClose(); closeErr != nil { - return nil, fmt.Errorf("failed read response of '%v' command - %v and failed to close connection - %v", - fullCommand, err, closeErr) + return nil, fmt.Errorf("failed read response of %q command: %w and failed to close connection: %w", fullCommand, err, closeErr) } - return nil, fmt.Errorf("failed to read response of '%v' command - %v", fullCommand, err) + return nil, fmt.Errorf("failed to read response of %q command: %w", fullCommand, err) } if messageLength == 0 { - return nil, fmt.Errorf("got empty response during execution of '%v' command", fullCommand) + return nil, fmt.Errorf("got empty response during execution of %q command", fullCommand) } return buf[:messageLength], nil } @@ -134,18 +132,18 @@ func (conn *dpdkConnector) readMaxOutputLen() (*initMessage, error) { buf := make([]byte, maxInitMessageLength) err := conn.setTimeout() if err != nil { - return nil, fmt.Errorf("failed to set timeout - %v", err) + return nil, fmt.Errorf("failed to set timeout: %w", err) } messageLength, err := conn.connection.Read(buf) if err != nil { - return nil, fmt.Errorf("failed to read InitMessage - %v", err) + return nil, fmt.Errorf("failed to read InitMessage: %w", err) } var initMessage initMessage err = json.Unmarshal(buf[:messageLength], &initMessage) if err != nil { - return nil, fmt.Errorf("failed to unmarshal response - %v", err) + return nil, fmt.Errorf("failed to unmarshal response: %w", err) } if initMessage.MaxOutputLen == 0 { diff --git a/plugins/inputs/dpdk/dpdk_connector_test.go b/plugins/inputs/dpdk/dpdk_connector_test.go index d803b43ab9d14..ddffc0cb42140 100644 --- a/plugins/inputs/dpdk/dpdk_connector_test.go +++ b/plugins/inputs/dpdk/dpdk_connector_test.go @@ -126,7 +126,7 @@ func Test_getCommandResponse(t *testing.T) { buf, err := dpdk.connector.getCommandResponse(command) require.Error(t, err) - require.Contains(t, err.Error(), "failed to get connection to execute / command") + require.Contains(t, err.Error(), "failed to get connection to execute \"/\" command") require.Equal(t, 0, len(buf)) }) diff --git a/plugins/inputs/dpdk/dpdk_utils.go b/plugins/inputs/dpdk/dpdk_utils.go index 3db50cc6ecda7..5625dcaeb1366 100644 --- a/plugins/inputs/dpdk/dpdk_utils.go +++ b/plugins/inputs/dpdk/dpdk_utils.go @@ -43,15 +43,15 @@ func getParams(command string) string { func isSocket(path string) error { pathInfo, err := os.Lstat(path) if os.IsNotExist(err) { - return fmt.Errorf("provided path does not exist: '%v'", path) + return fmt.Errorf("provided path does not exist: %q", path) } if err != nil { - return fmt.Errorf("cannot get system information of '%v' file: %v", path, err) + return fmt.Errorf("cannot get system information of %q file: %w", path, err) } if pathInfo.Mode()&os.ModeSocket != os.ModeSocket { - return fmt.Errorf("provided path does not point to a socket file: '%v'", path) + return fmt.Errorf("provided path does not point to a socket file: %q", path) } return nil @@ -72,7 +72,7 @@ func jsonToArray(input []byte, command string) ([]string, error) { var intArray []int64 err = json.Unmarshal(rawMessage[command], &intArray) if err != nil { - return nil, fmt.Errorf("failed to unmarshall json response - %v", err) + return nil, fmt.Errorf("failed to unmarshall json response: %w", err) } stringArray := make([]string, 0, len(intArray)) diff --git a/plugins/inputs/elasticsearch_query/aggregation_query.go b/plugins/inputs/elasticsearch_query/aggregation_query.go index ab97277f4e119..d53a48b0485d8 100644 --- a/plugins/inputs/elasticsearch_query/aggregation_query.go +++ b/plugins/inputs/elasticsearch_query/aggregation_query.go @@ -37,11 +37,11 @@ func (e *ElasticsearchQuery) runAggregationQuery(ctx context.Context, aggregatio src, err := query.Source() if err != nil { - return nil, fmt.Errorf("failed to get query source - %v", err) + return nil, fmt.Errorf("failed to get query source: %w", err) } data, err := json.Marshal(src) if err != nil { - return nil, fmt.Errorf("failed to unmarshal response - %v", err) + return nil, fmt.Errorf("failed to unmarshal response: %w", err) } e.Log.Debugf("{\"query\": %s}", string(data)) @@ -69,7 +69,7 @@ func (e *ElasticsearchQuery) getMetricFields(ctx context.Context, aggregation es for _, metricField := range aggregation.MetricFields { resp, err := e.esClient.GetFieldMapping().Index(aggregation.Index).Field(metricField).Do(ctx) if err != nil { - return mapMetricFields, fmt.Errorf("error retrieving field mappings for %s: %s", aggregation.Index, err.Error()) + return mapMetricFields, fmt.Errorf("error retrieving field mappings for %s: %w", aggregation.Index, err) } for _, index := range resp { diff --git a/plugins/inputs/elasticsearch_query/elasticsearch_query.go b/plugins/inputs/elasticsearch_query/elasticsearch_query.go index b86bef184a44b..bf74a18b00d0b 100644 --- a/plugins/inputs/elasticsearch_query/elasticsearch_query.go +++ b/plugins/inputs/elasticsearch_query/elasticsearch_query.go @@ -95,7 +95,7 @@ func (e *ElasticsearchQuery) initAggregation(ctx context.Context, agg esAggregat // retrieve field mapping and build queries only once agg.mapMetricFields, err = e.getMetricFields(ctx, agg) if err != nil { - return fmt.Errorf("not possible to retrieve fields: %v", err.Error()) + return fmt.Errorf("not possible to retrieve fields: %w", err) } for _, metricField := range agg.MetricFields { @@ -153,7 +153,7 @@ func (e *ElasticsearchQuery) connectToES() error { // check for ES version on first node esVersion, err := client.ElasticsearchVersion(e.URLs[0]) if err != nil { - return fmt.Errorf("elasticsearch version check failed: %s", err) + return fmt.Errorf("elasticsearch version check failed: %w", err) } esVersionSplit := strings.Split(esVersion, ".") @@ -187,7 +187,7 @@ func (e *ElasticsearchQuery) Gather(acc telegraf.Accumulator) error { defer wg.Done() err := e.esAggregationQuery(acc, agg, i) if err != nil { - acc.AddError(fmt.Errorf("elasticsearch query aggregation %s: %s ", agg.MeasurementName, err.Error())) + acc.AddError(fmt.Errorf("elasticsearch query aggregation %s: %w", agg.MeasurementName, err)) } }(agg, i) } diff --git a/plugins/inputs/eventhub_consumer/eventhub_consumer.go b/plugins/inputs/eventhub_consumer/eventhub_consumer.go index d80646a2f03a3..1de2c2afcc704 100644 --- a/plugins/inputs/eventhub_consumer/eventhub_consumer.go +++ b/plugins/inputs/eventhub_consumer/eventhub_consumer.go @@ -146,7 +146,7 @@ func (e *EventHub) Start(acc telegraf.Accumulator) error { for _, partitionID := range partitions { _, err := e.hub.Receive(ctx, partitionID, e.onMessage, receiveOpts...) if err != nil { - return fmt.Errorf("creating receiver for partition %q: %v", partitionID, err) + return fmt.Errorf("creating receiver for partition %q: %w", partitionID, err) } } diff --git a/plugins/inputs/exec/exec.go b/plugins/inputs/exec/exec.go index 3598b9d44a81d..608c13557b0f4 100644 --- a/plugins/inputs/exec/exec.go +++ b/plugins/inputs/exec/exec.go @@ -4,6 +4,7 @@ package exec import ( "bytes" _ "embed" + "errors" "fmt" "io" "os" @@ -68,7 +69,7 @@ func (c CommandRunner) Run( ) ([]byte, []byte, error) { splitCmd, err := shellquote.Split(command) if err != nil || len(splitCmd) == 0 { - return nil, nil, fmt.Errorf("exec: unable to parse command, %s", err) + return nil, nil, fmt.Errorf("exec: unable to parse command: %w", err) } cmd := osExec.Command(splitCmd[0], splitCmd[1:]...) @@ -126,7 +127,7 @@ func removeWindowsCarriageReturns(b bytes.Buffer) bytes.Buffer { if len(byt) > 0 { _, _ = buf.Write(byt) } - if err == io.EOF { + if errors.Is(err, io.EOF) { return buf } } @@ -143,7 +144,7 @@ func (e *Exec) ProcessCommand(command string, acc telegraf.Accumulator, wg *sync out, errBuf, runErr := e.runner.Run(command, e.Environment, time.Duration(e.Timeout)) if !e.parseDespiteError && runErr != nil { - err := fmt.Errorf("exec: %s for command '%s': %s", runErr, command, string(errBuf)) + err := fmt.Errorf("exec: %w for command %q: %s", runErr, command, string(errBuf)) acc.AddError(err) return } diff --git a/plugins/inputs/execd/execd.go b/plugins/inputs/execd/execd.go index 81337987537d0..3d5fd0a0ccae5 100644 --- a/plugins/inputs/execd/execd.go +++ b/plugins/inputs/execd/execd.go @@ -107,10 +107,11 @@ func (e *Execd) cmdReadOutStream(out io.Reader) { for { metric, err := parser.Next() if err != nil { - if err == influx.EOF { + if errors.Is(err, influx.EOF) { break // stream ended } - if parseErr, isParseError := err.(*influx.ParseError); isParseError { + var parseErr *influx.ParseError + if errors.As(err, &parseErr) { // parse error. e.acc.AddError(parseErr) continue diff --git a/plugins/inputs/execd/execd_posix.go b/plugins/inputs/execd/execd_posix.go index 94d0bd47858fc..20fc69525f458 100644 --- a/plugins/inputs/execd/execd_posix.go +++ b/plugins/inputs/execd/execd_posix.go @@ -31,11 +31,11 @@ func (e *Execd) Gather(_ telegraf.Accumulator) error { case "STDIN": if osStdin, ok := e.process.Stdin.(*os.File); ok { if err := osStdin.SetWriteDeadline(time.Now().Add(1 * time.Second)); err != nil { - return fmt.Errorf("setting write deadline failed: %s", err) + return fmt.Errorf("setting write deadline failed: %w", err) } } if _, err := io.WriteString(e.process.Stdin, "\n"); err != nil { - return fmt.Errorf("writing to stdin failed: %s", err) + return fmt.Errorf("writing to stdin failed: %w", err) } case "none": default: