From 0804ccef4efae482d3217f0908c11ebd57bb76a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Wed, 9 Oct 2024 09:07:46 +0200 Subject: [PATCH] chore(linters): Enable `string-format` rule for revive (#15983) --- .golangci.yml | 17 +++++++++++++++++ cmd/telegraf/telegraf.go | 4 ++-- internal/snmp/field.go | 4 ++-- internal/snmp/table.go | 4 ++-- plugins/common/shim/goshim.go | 6 +++--- plugins/common/socket/stream.go | 4 ++-- plugins/inputs/activemq/activemq.go | 2 +- plugins/inputs/bond/bond.go | 2 +- .../cisco_telemetry_mdt/cisco_telemetry_mdt.go | 8 ++++---- .../cisco_telemetry_mdt_test.go | 4 ++-- .../google_cloud_storage.go | 4 ++-- .../influxdb_listener/influxdb_listener.go | 3 ++- .../influxdb_v2_listener.go | 8 +++----- plugins/inputs/intel_pmt/xml_parser.go | 9 +++------ plugins/inputs/iptables/iptables.go | 10 ++++++---- plugins/inputs/kafka_consumer/kafka_consumer.go | 2 +- plugins/inputs/linux_cpu/linux_cpu.go | 4 +--- plugins/inputs/nginx_plus_api/nginx_plus_api.go | 2 +- plugins/inputs/opcua/read_client.go | 2 +- plugins/inputs/ping/ping_windows_test.go | 8 ++++---- plugins/inputs/sflow/packetdecoder.go | 6 +++--- plugins/inputs/smartctl/smartctl.go | 4 ++-- plugins/inputs/supervisor/supervisor.go | 2 +- .../inputs/systemd_units/systemd_units_test.go | 2 +- plugins/inputs/tengine/tengine.go | 2 +- plugins/inputs/unbound/unbound.go | 3 +-- plugins/inputs/zipkin/codec/jsonV1/jsonV1.go | 4 ++-- plugins/inputs/zipkin/handler.go | 4 ++-- plugins/inputs/zipkin/zipkin_test.go | 9 ++++----- plugins/outputs/mongodb/mongodb.go | 4 ++-- plugins/outputs/nats/nats.go | 2 +- plugins/outputs/newrelic/newrelic.go | 2 +- plugins/outputs/opentsdb/opentsdb.go | 8 ++++---- plugins/outputs/socket_writer/socket_writer.go | 4 ++-- plugins/outputs/stackdriver/stackdriver_test.go | 6 +++--- plugins/outputs/timestream/timestream.go | 4 ++-- plugins/outputs/timestream/timestream_test.go | 4 ++-- plugins/parsers/dropwizard/parser.go | 5 +++-- .../parsers/influx/influx_upstream/parser.go | 3 +-- .../influx/influx_upstream/parser_test.go | 6 +++--- plugins/parsers/json/json_flattener.go | 3 +-- plugins/parsers/json/parser.go | 2 +- plugins/parsers/json/parser_test.go | 2 +- plugins/parsers/json_v2/parser.go | 6 +++--- plugins/parsers/nagios/parser_test.go | 4 ++-- plugins/parsers/wavefront/element.go | 6 +++--- plugins/processors/snmp_lookup/lookup_test.go | 8 ++++---- tools/config_includer/generator.go | 2 +- 48 files changed, 117 insertions(+), 107 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 1bdb01fa7..31859c348 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -290,6 +290,23 @@ linters-settings: - name: receiver-naming - name: redefines-builtin-id - name: redundant-import-alias + - name: string-format + arguments: + - - 'fmt.Errorf[0]' + - '/^([^A-Z]|$)/' + - 'Error string must not start with a capital letter.' + - - 'fmt.Errorf[0]' + - '/(^|[^\.!?])$/' + - 'Error string must not end in punctuation.' + - - 'errors.New[0]' + - '/^([^A-Z]|$)/' + - 'Error string must not start with a capital letter.' + - - 'errors.New[0]' + - '/(^|[^\.!?])$/' + - 'Error string must not end in punctuation.' + - - 'panic' + - '/^[^\n]*$/' + - 'Must not contain line breaks.' - name: string-of-int - name: struct-tag - name: superfluous-else diff --git a/cmd/telegraf/telegraf.go b/cmd/telegraf/telegraf.go index fe29de3c9..717efdb9f 100644 --- a/cmd/telegraf/telegraf.go +++ b/cmd/telegraf/telegraf.go @@ -343,10 +343,10 @@ func (t *Telegraf) runAgent(ctx context.Context, reloadConfig bool) error { } if !(t.test || t.testWait != 0) && len(c.Outputs) == 0 { - return errors.New("no outputs found, did you provide a valid config file?") + return errors.New("no outputs found, probably invalid config file provided") } if t.plugindDir == "" && len(c.Inputs) == 0 { - return errors.New("no inputs found, did you provide a valid config file?") + return errors.New("no inputs found, probably invalid config file provided") } if int64(c.Agent.Interval) <= 0 { diff --git a/internal/snmp/field.go b/internal/snmp/field.go index b2ed67b6e..936cc3dda 100644 --- a/internal/snmp/field.go +++ b/internal/snmp/field.go @@ -85,11 +85,11 @@ func (f *Field) Init(tr Translator) error { } if f.SecondaryIndexTable && f.SecondaryIndexUse { - return errors.New("SecondaryIndexTable and UseSecondaryIndex are exclusive") + return errors.New("fields SecondaryIndexTable and UseSecondaryIndex are exclusive") } if !f.SecondaryIndexTable && !f.SecondaryIndexUse && f.SecondaryOuterJoin { - return errors.New("SecondaryOuterJoin set to true, but field is not being used in join") + return errors.New("field SecondaryOuterJoin set to true, but field is not being used in join") } switch f.Conversion { diff --git a/internal/snmp/table.go b/internal/snmp/table.go index aa42b3c11..495ef16ad 100644 --- a/internal/snmp/table.go +++ b/internal/snmp/table.go @@ -51,12 +51,12 @@ type RTableRow struct { Fields map[string]interface{} } -// Init() builds & initializes the nested fields. +// Init builds & initializes the nested fields. func (t *Table) Init(tr Translator) error { // makes sure oid or name is set in config file // otherwise snmp will produce metrics with an empty name if t.Oid == "" && t.Name == "" { - return errors.New("SNMP table in config file is not named. One or both of the oid and name settings must be set") + return errors.New("unnamed SNMP table in config file: one or both of the oid and name settings must be set") } if t.initialized { diff --git a/plugins/common/shim/goshim.go b/plugins/common/shim/goshim.go index 72af49dda..3d329cf04 100644 --- a/plugins/common/shim/goshim.go +++ b/plugins/common/shim/goshim.go @@ -79,17 +79,17 @@ func (s *Shim) Run(pollInterval time.Duration) error { if s.Input != nil { err := s.RunInput(pollInterval) if err != nil { - return fmt.Errorf("RunInput error: %w", err) + return fmt.Errorf("running input failed: %w", err) } } else if s.Processor != nil { err := s.RunProcessor() if err != nil { - return fmt.Errorf("RunProcessor error: %w", err) + return fmt.Errorf("running processor failed: %w", err) } } else if s.Output != nil { err := s.RunOutput() if err != nil { - return fmt.Errorf("RunOutput error: %w", err) + return fmt.Errorf("running output failed: %w", err) } } else { return errors.New("nothing to run") diff --git a/plugins/common/socket/stream.go b/plugins/common/socket/stream.go index 4896bbc87..8b04c9195 100644 --- a/plugins/common/socket/stream.go +++ b/plugins/common/socket/stream.go @@ -100,7 +100,7 @@ func (l *streamListener) setupVsock(u *url.URL) error { // Check address string for containing two tokens if len(addrTuple) < 2 { - return errors.New("CID and/or port number missing") + return errors.New("port and/or CID number missing") } // Parse CID and port number from address string both being 32-bit // source: https://man7.org/linux/man-pages/man7/vsock.7.html @@ -109,7 +109,7 @@ func (l *streamListener) setupVsock(u *url.URL) error { return fmt.Errorf("failed to parse CID %s: %w", addrTuple[0], err) } if (cid >= uint64(math.Pow(2, 32))-1) && (cid <= 0) { - return fmt.Errorf("CID %d is out of range", cid) + return fmt.Errorf("value of CID %d is out of range", cid) } port, err := strconv.ParseUint(addrTuple[1], 10, 32) if err != nil { diff --git a/plugins/inputs/activemq/activemq.go b/plugins/inputs/activemq/activemq.go index 1d08b4571..c7c437912 100644 --- a/plugins/inputs/activemq/activemq.go +++ b/plugins/inputs/activemq/activemq.go @@ -155,7 +155,7 @@ func (a *ActiveMQ) GetMetrics(u string) ([]byte, error) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("GET %s returned status %q", u, resp.Status) + return nil, fmt.Errorf("%s returned HTTP status %s", u, resp.Status) } return io.ReadAll(resp.Body) diff --git a/plugins/inputs/bond/bond.go b/plugins/inputs/bond/bond.go index 929d46951..a7caf1a7d 100644 --- a/plugins/inputs/bond/bond.go +++ b/plugins/inputs/bond/bond.go @@ -137,7 +137,7 @@ func (bond *Bond) gatherBondPart(bondName, rawFile string, acc telegraf.Accumula if err := scanner.Err(); err != nil { return err } - return fmt.Errorf("Couldn't find status info for %q", bondName) + return fmt.Errorf("couldn't find status info for %q", bondName) } func (bond *Bond) readSysFiles(bondDir string) (sysFiles, error) { diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go index b37e3287b..89e3ca76d 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go @@ -304,7 +304,7 @@ func (c *CiscoTelemetryMDT) handleTCPClient(conn net.Conn) error { if err != nil { return err } - return errors.New("TCP dialout premature EOF") + return errors.New("premature EOF during TCP dialout") } c.handleTelemetry(payload.Bytes()) @@ -324,13 +324,13 @@ func (c *CiscoTelemetryMDT) MdtDialout(stream mdtdialout.GRPCMdtDialout_MdtDialo packet, err := stream.Recv() if err != nil { if !errors.Is(err, io.EOF) { - c.acc.AddError(fmt.Errorf("GRPC dialout receive error: %w", err)) + c.acc.AddError(fmt.Errorf("receive error during GRPC dialout: %w", err)) } break } if len(packet.Data) == 0 && len(packet.Errors) != 0 { - c.acc.AddError(fmt.Errorf("GRPC dialout error: %s", packet.Errors)) + c.acc.AddError(fmt.Errorf("error during GRPC dialout: %s", packet.Errors)) break } @@ -763,7 +763,7 @@ func (c *CiscoTelemetryMDT) parseContentField( if len(rn) > 0 { tags[prefix] = rn } else if !dn { // Check for distinguished name being present - c.acc.AddError(errors.New("NX-OS decoding failed: missing dn field")) + c.acc.AddError(errors.New("failed while decoding NX-OS: missing 'dn' field")) 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 68d51d2ae..d9102c152 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt_test.go @@ -1201,7 +1201,7 @@ func TestGRPCDialoutError(t *testing.T) { require.True(t, err == nil || errors.Is(err, io.EOF)) c.Stop() - require.Equal(t, []error{errors.New("GRPC dialout error: foobar")}, acc.Errors) + require.Equal(t, []error{errors.New("error during GRPC dialout: foobar")}, acc.Errors) } func TestGRPCDialoutMultiple(t *testing.T) { @@ -1262,7 +1262,7 @@ func TestGRPCDialoutMultiple(t *testing.T) { c.Stop() require.NoError(t, conn.Close()) - require.Equal(t, []error{errors.New("GRPC dialout error: testclose"), errors.New("GRPC dialout error: testclose")}, acc.Errors) + require.Equal(t, []error{errors.New("error during GRPC dialout: testclose"), errors.New("error during GRPC dialout: testclose")}, acc.Errors) tags := map[string]string{ "path": "type:model/some/path", diff --git a/plugins/inputs/google_cloud_storage/google_cloud_storage.go b/plugins/inputs/google_cloud_storage/google_cloud_storage.go index 2090715c0..c97ad2061 100644 --- a/plugins/inputs/google_cloud_storage/google_cloud_storage.go +++ b/plugins/inputs/google_cloud_storage/google_cloud_storage.go @@ -97,7 +97,7 @@ func (gcs *GCS) Gather(acc telegraf.Accumulator) error { if !gcs.shouldIgnore(name) { if err := gcs.processMeasurementsInObject(name, bucket, acc); err != nil { 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)) + acc.AddError(fmt.Errorf("could not process object %q in bucket %q: %w", name, bucketName, err)) } } @@ -238,7 +238,7 @@ func (gcs *GCS) setUpDefaultClient() error { func (gcs *GCS) setOffset() error { if gcs.client == nil { - return errors.New("CANNOT SET OFFSET IF CLIENT IS NOT SET") + return errors.New("cannot set offset if client is not set") } if gcs.OffsetKey != "" { diff --git a/plugins/inputs/influxdb_listener/influxdb_listener.go b/plugins/inputs/influxdb_listener/influxdb_listener.go index 2c54088b3..fd4b1d1ca 100644 --- a/plugins/inputs/influxdb_listener/influxdb_listener.go +++ b/plugins/inputs/influxdb_listener/influxdb_listener.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net" "net/http" "time" @@ -449,7 +450,7 @@ func (h *InfluxDBListener) handleWriteUpstreamParser(res http.ResponseWriter, re h.acc.AddMetric(m) } - if !errors.Is(err, influx_upstream.ErrEOF) { + if !errors.Is(err, io.EOF) { h.Log.Debugf("Error parsing the request body: %v", err.Error()) if err := badRequest(res, err.Error()); err != nil { h.Log.Debugf("error in bad-request: %v", err) diff --git a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go index 07146192f..442639669 100644 --- a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go +++ b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go @@ -38,8 +38,6 @@ const ( defaultWriteTimeout = 10 * time.Second ) -var ErrEOF = errors.New("EOF") - // The BadRequestCode constants keep standard error messages // see: https://v2.docs.influxdata.com/v2.0/api/#operation/PostWrite type BadRequestCode string @@ -309,7 +307,7 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc { if h.ParserType == "upstream" { parser := influx_upstream.Parser{} err = parser.Init() - if !errors.Is(err, ErrEOF) && err != nil { + if !errors.Is(err, io.EOF) && err != nil { h.Log.Debugf("Error initializing parser: %v", err.Error()) return } @@ -327,7 +325,7 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc { } else { parser := influx.Parser{} err = parser.Init() - if !errors.Is(err, ErrEOF) && err != nil { + if !errors.Is(err, io.EOF) && err != nil { h.Log.Debugf("Error initializing parser: %v", err.Error()) return } @@ -341,7 +339,7 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc { metrics, err = parser.Parse(bytes) } - if !errors.Is(err, ErrEOF) && err != nil { + if !errors.Is(err, io.EOF) && err != nil { h.Log.Debugf("Error parsing the request body: %v", err.Error()) if err := badRequest(res, Invalid, err.Error()); err != nil { h.Log.Debugf("error in bad-request: %v", err) diff --git a/plugins/inputs/intel_pmt/xml_parser.go b/plugins/inputs/intel_pmt/xml_parser.go index 159e84e44..2d0d07143 100644 --- a/plugins/inputs/intel_pmt/xml_parser.go +++ b/plugins/inputs/intel_pmt/xml_parser.go @@ -176,11 +176,8 @@ func (p *IntelPMT) readXMLs() error { p.Log.Warnf("Configured sample metric %q has not been found", sm) } } - err := p.verifyNoEmpty() - if err != nil { - return fmt.Errorf("XMLs empty: %w", err) - } - return nil + + return p.verifyNoEmpty() } // getAllXMLData retrieves two XMLs for given GUID. @@ -254,7 +251,7 @@ func computeMask(msb, lsb uint64) uint64 { func parseXML(source string, sr sourceReader, v interface{}) error { if sr == nil { - return errors.New("XML reader failed to initialize") + return errors.New("xml reader has not been initialized") } reader, err := sr.getReadCloser(source) if err != nil { diff --git a/plugins/inputs/iptables/iptables.go b/plugins/inputs/iptables/iptables.go index e352fbe4d..648b3a8b9 100644 --- a/plugins/inputs/iptables/iptables.go +++ b/plugins/inputs/iptables/iptables.go @@ -82,10 +82,12 @@ func (ipt *Iptables) chainList(table, chain string) (string, error) { const measurement = "iptables" -var errParse = errors.New("Cannot parse iptables list information") -var chainNameRe = regexp.MustCompile(`^Chain\s+(\S+)`) -var fieldsHeaderRe = regexp.MustCompile(`^\s*pkts\s+bytes\s+target`) -var valuesRe = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s+(\w+).*?/\*\s*(.+?)\s*\*/\s*`) +var ( + errParse = errors.New("cannot parse iptables list information") + chainNameRe = regexp.MustCompile(`^Chain\s+(\S+)`) + fieldsHeaderRe = regexp.MustCompile(`^\s*pkts\s+bytes\s+target`) + valuesRe = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s+(\w+).*?/\*\s*(.+?)\s*\*/\s*`) +) func (ipt *Iptables) parseAndGather(data string, acc telegraf.Accumulator) error { lines := strings.Split(data, "\n") diff --git a/plugins/inputs/kafka_consumer/kafka_consumer.go b/plugins/inputs/kafka_consumer/kafka_consumer.go index 9f11c6143..9d262b734 100644 --- a/plugins/inputs/kafka_consumer/kafka_consumer.go +++ b/plugins/inputs/kafka_consumer/kafka_consumer.go @@ -132,7 +132,7 @@ func (k *KafkaConsumer) Init() error { } if err := k.SetConfig(cfg, k.Log); err != nil { - return fmt.Errorf("SetConfig: %w", err) + return fmt.Errorf("setting config failed: %w", err) } switch strings.ToLower(k.Offset) { diff --git a/plugins/inputs/linux_cpu/linux_cpu.go b/plugins/inputs/linux_cpu/linux_cpu.go index f35b31e6e..df2870545 100644 --- a/plugins/inputs/linux_cpu/linux_cpu.go +++ b/plugins/inputs/linux_cpu/linux_cpu.go @@ -182,11 +182,9 @@ func init() { func validatePath(propPath string) error { f, err := os.Open(propPath) - if os.IsNotExist(err) { - return fmt.Errorf("CPU property does not exist: [%s]", propPath) + return fmt.Errorf("file with CPU property does not exist: %q", propPath) } - if err != nil { return fmt.Errorf("cannot get system information for CPU property %q: %w", propPath, err) } diff --git a/plugins/inputs/nginx_plus_api/nginx_plus_api.go b/plugins/inputs/nginx_plus_api/nginx_plus_api.go index 2586722fb..acf3be64a 100644 --- a/plugins/inputs/nginx_plus_api/nginx_plus_api.go +++ b/plugins/inputs/nginx_plus_api/nginx_plus_api.go @@ -74,7 +74,7 @@ func (n *NginxPlusAPI) 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 %q: %w", u, err)) + acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err)) continue } diff --git a/plugins/inputs/opcua/read_client.go b/plugins/inputs/opcua/read_client.go index b765ff72d..9aaf0570c 100644 --- a/plugins/inputs/opcua/read_client.go +++ b/plugins/inputs/opcua/read_client.go @@ -139,7 +139,7 @@ func (o *ReadClient) read() error { resp, err := o.Client.Read(o.ctx, req) if err != nil { o.ReadError.Incr(1) - return fmt.Errorf("RegisterNodes Read failed: %w", err) + return fmt.Errorf("reading registered nodes failed: %w", err) } o.ReadSuccess.Incr(1) for i, d := range resp.Results { diff --git a/plugins/inputs/ping/ping_windows_test.go b/plugins/inputs/ping/ping_windows_test.go index 9c11f2c3c..4517bf8f3 100644 --- a/plugins/inputs/ping/ping_windows_test.go +++ b/plugins/inputs/ping/ping_windows_test.go @@ -104,7 +104,7 @@ Statystyka badania ping dla 195.187.242.157: ` func mockErrorHostPinger(string, float64, ...string) (string, error) { - return errorPingOutput, errors.New("No packets received") + return errorPingOutput, errors.New("no packets received") } // Test that Gather works on a ping with no transmitted packets, even though the @@ -228,7 +228,7 @@ Options: ` func mockFatalHostPinger(string, float64, ...string) (string, error) { - return fatalPingOutput, errors.New("So very bad") + return fatalPingOutput, errors.New("so very bad") } // Test that a fatal ping command does not gather any statistics. @@ -273,7 +273,7 @@ Ping statistics for 8.8.8.8: ` func mockUnreachableHostPinger(string, float64, ...string) (string, error) { - return UnreachablePingOutput, errors.New("So very bad") + return UnreachablePingOutput, errors.New("so very bad") } // Reply from 185.28.251.217: TTL expired in transit. @@ -324,7 +324,7 @@ Ping statistics for 8.8.8.8: ` func mockTTLExpiredPinger(string, float64, ...string) (string, error) { - return TTLExpiredPingOutput, errors.New("So very bad") + return TTLExpiredPingOutput, errors.New("so very bad") } // in case 'Destination net unreachable' ping app return receive packet which is not what we need diff --git a/plugins/inputs/sflow/packetdecoder.go b/plugins/inputs/sflow/packetdecoder.go index b01dee289..d5cc0b493 100644 --- a/plugins/inputs/sflow/packetdecoder.go +++ b/plugins/inputs/sflow/packetdecoder.go @@ -60,7 +60,7 @@ func (d *packetDecoder) DecodeOnePacket(r io.Reader) (*v5Format, error) { return nil, err } if p.Version != 5 { - return nil, fmt.Errorf("Version %d not supported, only version 5", p.Version) + return nil, fmt.Errorf("version %d not supported, only version 5", p.Version) } var addressIPType AddressType if err := read(r, &addressIPType, "address ip type"); err != nil { @@ -74,7 +74,7 @@ func (d *packetDecoder) DecodeOnePacket(r io.Reader) (*v5Format, error) { case AddressTypeIPV6: p.AgentAddress.IP = make([]byte, 16) default: - return nil, fmt.Errorf("Unknown address IP type %d", addressIPType) + return nil, fmt.Errorf("unknown address IP type %d", addressIPType) } if err := read(r, &p.AgentAddress.IP, "Agent Address IP"); err != nil { return nil, err @@ -389,7 +389,7 @@ func (d *packetDecoder) decodeIPv6Header(r io.Reader) (h ipV6Header, err error) } version := fourByteBlock >> 28 if version != 0x6 { - return h, fmt.Errorf("Unexpected IPv6 header version 0x%x", version) + return h, fmt.Errorf("unexpected IPv6 header version 0x%x", version) } h.DSCP = uint8((fourByteBlock & 0xFC00000) >> 22) h.ECN = uint8((fourByteBlock & 0x300000) >> 20) diff --git a/plugins/inputs/smartctl/smartctl.go b/plugins/inputs/smartctl/smartctl.go index 7c82ac78d..b4f34ca2f 100644 --- a/plugins/inputs/smartctl/smartctl.go +++ b/plugins/inputs/smartctl/smartctl.go @@ -70,12 +70,12 @@ func (s *Smartctl) Init() error { func (s *Smartctl) Gather(acc telegraf.Accumulator) error { devices, err := s.scan() if err != nil { - return fmt.Errorf("Error scanning system: %w", err) + return fmt.Errorf("error while scanning system: %w", err) } for _, device := range devices { if err := s.scanDevice(acc, device.Name, device.Type); err != nil { - return fmt.Errorf("Error getting device %s: %w", device, err) + return fmt.Errorf("error while getting device %s: %w", device, err) } } diff --git a/plugins/inputs/supervisor/supervisor.go b/plugins/inputs/supervisor/supervisor.go index d21dd15df..65341832d 100644 --- a/plugins/inputs/supervisor/supervisor.go +++ b/plugins/inputs/supervisor/supervisor.go @@ -144,7 +144,7 @@ func (s *Supervisor) Init() error { // Initializing XML-RPC client s.rpcClient, err = xmlrpc.NewClient(s.Server, nil) if err != nil { - return fmt.Errorf("XML-RPC client initialization failed: %w", err) + return fmt.Errorf("failed to initialize XML-RPC client: %w", err) } // Setting filter for additional metrics s.fieldFilter, err = filter.NewIncludeExcludeFilter(s.MetricsInc, s.MetricsExc) diff --git a/plugins/inputs/systemd_units/systemd_units_test.go b/plugins/inputs/systemd_units/systemd_units_test.go index a9594cbaf..7add99775 100644 --- a/plugins/inputs/systemd_units/systemd_units_test.go +++ b/plugins/inputs/systemd_units/systemd_units_test.go @@ -969,7 +969,7 @@ func (c *fakeClient) GetUnitTypePropertiesContext(_ context.Context, unit, unitT return nil, nil } if u.utype != unitType { - return nil, fmt.Errorf("Unknown interface 'org.freedesktop.systemd1.%s", unitType) + return nil, fmt.Errorf("unknown interface 'org.freedesktop.systemd1.%s", unitType) } return u.properties, nil } diff --git a/plugins/inputs/tengine/tengine.go b/plugins/inputs/tengine/tengine.go index f68a21967..8ec3b4fa7 100644 --- a/plugins/inputs/tengine/tengine.go +++ b/plugins/inputs/tengine/tengine.go @@ -52,7 +52,7 @@ func (n *Tengine) 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 %q: %w", u, err)) + acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err)) continue } diff --git a/plugins/inputs/unbound/unbound.go b/plugins/inputs/unbound/unbound.go index 197fb55d4..e3b5d8edb 100644 --- a/plugins/inputs/unbound/unbound.go +++ b/plugins/inputs/unbound/unbound.go @@ -133,8 +133,7 @@ func (s *Unbound) Gather(acc telegraf.Accumulator) error { fieldValue, err := strconv.ParseFloat(value, 64) if err != nil { - acc.AddError(fmt.Errorf("Expected a numerical value for %s = %v", - stat, value)) + acc.AddError(fmt.Errorf("expected a numerical value for %s = %v", stat, value)) continue } diff --git a/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go b/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go index 1fd08138b..e265540ff 100644 --- a/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go +++ b/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go @@ -220,7 +220,7 @@ func TraceIDFromString(s string) (string, error) { var hi, lo uint64 var err error if len(s) > 32 { - return "", fmt.Errorf("TraceID cannot be longer than 32 hex characters: %s", s) + return "", fmt.Errorf("length of TraceID cannot be greater than 32 hex characters: %s", s) } else if len(s) > 16 { hiLen := len(s) - 16 if hi, err = strconv.ParseUint(s[0:hiLen], 16, 64); err != nil { @@ -243,7 +243,7 @@ func TraceIDFromString(s string) (string, error) { // IDFromString validates the ID and returns it in hexadecimal format. func IDFromString(s string) (string, error) { if len(s) > 16 { - return "", fmt.Errorf("ID cannot be longer than 16 hex characters: %s", s) + return "", fmt.Errorf("length of ID cannot be greater than 16 hex characters: %s", s) } id, err := strconv.ParseUint(s, 16, 64) if err != nil { diff --git a/plugins/inputs/zipkin/handler.go b/plugins/inputs/zipkin/handler.go index 811018a31..50e6a53c4 100644 --- a/plugins/inputs/zipkin/handler.go +++ b/plugins/inputs/zipkin/handler.go @@ -118,7 +118,7 @@ func (s *SpanHandler) Spans(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } -// ContentDecoer returns a Decoder that is able to produce Traces from bytes. +// ContentDecoder returns a Decoder that is able to produce Traces from bytes. // Failure should yield an HTTP 415 (`http.StatusUnsupportedMediaType`) // If a Content-Type is not set, zipkin assumes application/json func ContentDecoder(r *http.Request) (codec.Decoder, error) { @@ -138,5 +138,5 @@ func ContentDecoder(r *http.Request) (codec.Decoder, error) { return &thrift.Thrift{}, nil } } - return nil, fmt.Errorf("Unknown Content-Type: %s", contentType) + return nil, fmt.Errorf("unknown Content-Type: %s", contentType) } diff --git a/plugins/inputs/zipkin/zipkin_test.go b/plugins/inputs/zipkin/zipkin_test.go index 99334bd2f..9eb5f34cc 100644 --- a/plugins/inputs/zipkin/zipkin_test.go +++ b/plugins/inputs/zipkin/zipkin_test.go @@ -2,7 +2,6 @@ package zipkin import ( "bytes" - "errors" "fmt" "net/http" "os" @@ -646,18 +645,18 @@ func postThriftData(datafile, address, contentType string) error { return fmt.Errorf("could not read from data file %s", datafile) } - req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/v1/spans", address), bytes.NewReader(dat)) + endpoint := fmt.Sprintf("http://%s/api/v1/spans", address) + req, err := http.NewRequest("POST", endpoint, bytes.NewReader(dat)) if err != nil { - return errors.New("HTTP request creation failed") + return fmt.Errorf("unable to create new POST request for %q: %w", endpoint, err) } req.Header.Set("Content-Type", contentType) client := &http.Client{} resp, err := client.Do(req) if err != nil { - return fmt.Errorf("HTTP POST request to zipkin endpoint %q failed: %w", address, err) + return fmt.Errorf("error while making HTTP POST request to zipkin endpoint %q: %w", endpoint, err) } - defer resp.Body.Close() return nil diff --git a/plugins/outputs/mongodb/mongodb.go b/plugins/outputs/mongodb/mongodb.go index 67160b2b9..6394494e1 100644 --- a/plugins/outputs/mongodb/mongodb.go +++ b/plugins/outputs/mongodb/mongodb.go @@ -97,10 +97,10 @@ func (s *MongoDB) Init() error { switch s.AuthenticationType { case "SCRAM": if s.Username.Empty() { - return errors.New("SCRAM authentication must specify a username") + return errors.New("authentication for SCRAM must specify a username") } if s.Password.Empty() { - return errors.New("SCRAM authentication must specify a password") + return errors.New("authentication for SCRAM must specify a password") } username, err := s.Username.Get() if err != nil { diff --git a/plugins/outputs/nats/nats.go b/plugins/outputs/nats/nats.go index b2ee4daf3..ace7901fd 100644 --- a/plugins/outputs/nats/nats.go +++ b/plugins/outputs/nats/nats.go @@ -268,7 +268,7 @@ func (n *NATS) Write(metrics []telegraf.Metric) error { // use the same Publish API for nats core and jetstream err = n.conn.Publish(n.Subject, buf) if err != nil { - return fmt.Errorf("FAILED to send NATS message: %w", err) + return fmt.Errorf("failed to send NATS message: %w", err) } } return nil diff --git a/plugins/outputs/newrelic/newrelic.go b/plugins/outputs/newrelic/newrelic.go index fecec5a2e..bceca05da 100644 --- a/plugins/outputs/newrelic/newrelic.go +++ b/plugins/outputs/newrelic/newrelic.go @@ -43,7 +43,7 @@ func (*NewRelic) SampleConfig() string { // Connect to the Output func (nr *NewRelic) Connect() error { if nr.InsightsKey == "" { - return errors.New("InsightKey is a required for newrelic") + return errors.New("'insights_key' is a required for newrelic") } err := nr.initClient() if err != nil { diff --git a/plugins/outputs/opentsdb/opentsdb.go b/plugins/outputs/opentsdb/opentsdb.go index 9396ae998..620107363 100644 --- a/plugins/outputs/opentsdb/opentsdb.go +++ b/plugins/outputs/opentsdb/opentsdb.go @@ -74,11 +74,11 @@ func (o *OpenTSDB) Connect() error { uri := fmt.Sprintf("%s:%d", u.Host, o.Port) tcpAddr, err := net.ResolveTCPAddr("tcp", uri) if err != nil { - return fmt.Errorf("OpenTSDB TCP address cannot be resolved: %w", err) + return fmt.Errorf("failed to resolve TCP address: %w", err) } connection, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { - return fmt.Errorf("OpenTSDB Telnet connect fail: %w", err) + return fmt.Errorf("failed to connect to OpenTSDB: %w", err) } defer connection.Close() return nil @@ -154,11 +154,11 @@ func (o *OpenTSDB) WriteTelnet(metrics []telegraf.Metric, u *url.URL) error { uri := fmt.Sprintf("%s:%d", u.Host, o.Port) tcpAddr, err := net.ResolveTCPAddr("tcp", uri) if err != nil { - return fmt.Errorf("OpenTSDB: Telnet connect fail: %w", err) + return fmt.Errorf("failed to resolve TCP address: %w", err) } connection, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { - return errors.New("OpenTSDB: Telnet connect fail") + return fmt.Errorf("failed to connect to OpenTSDB: %w", err) } defer connection.Close() diff --git a/plugins/outputs/socket_writer/socket_writer.go b/plugins/outputs/socket_writer/socket_writer.go index a12e92659..b2aec04b9 100644 --- a/plugins/outputs/socket_writer/socket_writer.go +++ b/plugins/outputs/socket_writer/socket_writer.go @@ -65,7 +65,7 @@ func (sw *SocketWriter) Connect() error { // Check address string for containing two if len(addrTuple) < 2 { - return errors.New("CID and/or port number missing") + return errors.New("port and/or CID number missing") } // Parse CID and port number from address string both being 32-bit @@ -75,7 +75,7 @@ func (sw *SocketWriter) Connect() error { return fmt.Errorf("failed to parse CID %s: %w", addrTuple[0], err) } if (cid >= uint64(math.Pow(2, 32))-1) && (cid <= 0) { - return fmt.Errorf("CID %d is out of range", cid) + return fmt.Errorf("value of CID %d is out of range", cid) } port, err := strconv.ParseUint(addrTuple[1], 10, 32) if err != nil { diff --git a/plugins/outputs/stackdriver/stackdriver_test.go b/plugins/outputs/stackdriver/stackdriver_test.go index 2c9d362e3..dc9408bea 100644 --- a/plugins/outputs/stackdriver/stackdriver_test.go +++ b/plugins/outputs/stackdriver/stackdriver_test.go @@ -62,7 +62,7 @@ func (s *mockMetricServer) CreateTimeSeries(ctx context.Context, req *monitoring if s.err != nil { var statusResp *status.Status switch s.err.Error() { - case "InvalidArgument": + case "invalid argument": statusResp = status.New(codes.InvalidArgument, s.err.Error()) default: statusResp = status.New(codes.Unknown, s.err.Error()) @@ -616,12 +616,12 @@ func TestWriteIgnoredErrors(t *testing.T) { }{ { name: "other errors reported", - err: errors.New("Unknown"), + err: errors.New("unknown"), expectedErr: true, }, { name: "invalid argument", - err: errors.New("InvalidArgument"), + err: errors.New("invalid argument"), expectedErr: false, }, } diff --git a/plugins/outputs/timestream/timestream.go b/plugins/outputs/timestream/timestream.go index 04d8322e9..2daa05cb2 100644 --- a/plugins/outputs/timestream/timestream.go +++ b/plugins/outputs/timestream/timestream.go @@ -114,11 +114,11 @@ func (*Timestream) SampleConfig() string { func (t *Timestream) Connect() error { if t.DatabaseName == "" { - return errors.New("DatabaseName key is required") + return errors.New("'database_name' key is required") } if t.MappingMode == "" { - return errors.New("MappingMode key is required") + return errors.New("'mapping_mode' key is required") } if t.MappingMode != MappingModeSingleTable && t.MappingMode != MappingModeMultiTable { diff --git a/plugins/outputs/timestream/timestream_test.go b/plugins/outputs/timestream/timestream_test.go index c68422316..4d0f11d94 100644 --- a/plugins/outputs/timestream/timestream_test.go +++ b/plugins/outputs/timestream/timestream_test.go @@ -74,13 +74,13 @@ func TestConnectValidatesConfigParameters(t *testing.T) { } // checking base arguments noDatabaseName := Timestream{Log: testutil.Logger{}} - require.Contains(t, noDatabaseName.Connect().Error(), "DatabaseName") + require.ErrorContains(t, noDatabaseName.Connect(), "'database_name' key is required") noMappingMode := Timestream{ DatabaseName: tsDbName, Log: testutil.Logger{}, } - require.Contains(t, noMappingMode.Connect().Error(), "MappingMode") + require.ErrorContains(t, noMappingMode.Connect(), "'mapping_mode' key is required") incorrectMappingMode := Timestream{ DatabaseName: tsDbName, diff --git a/plugins/parsers/dropwizard/parser.go b/plugins/parsers/dropwizard/parser.go index 31e2db4ed..39c738bf6 100644 --- a/plugins/parsers/dropwizard/parser.go +++ b/plugins/parsers/dropwizard/parser.go @@ -2,6 +2,7 @@ package dropwizard import ( "encoding/json" + "errors" "fmt" "time" @@ -97,8 +98,8 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) { } // ParseLine is not supported by the dropwizard format -func (p *Parser) ParseLine(line string) (telegraf.Metric, error) { - return nil, fmt.Errorf("ParseLine not supported: %s, for data format: dropwizard", line) +func (p *Parser) ParseLine(_ string) (telegraf.Metric, error) { + return nil, errors.New("parsing line is not supported by the dropwizard format") } // SetDefaultTags sets the default tags diff --git a/plugins/parsers/influx/influx_upstream/parser.go b/plugins/parsers/influx/influx_upstream/parser.go index 6924b4b8b..9485e00db 100644 --- a/plugins/parsers/influx/influx_upstream/parser.go +++ b/plugins/parsers/influx/influx_upstream/parser.go @@ -21,7 +21,6 @@ const ( var ( ErrNoMetric = errors.New("no metric in line") - ErrEOF = errors.New("EOF") ) type TimeFunc func() time.Time @@ -259,7 +258,7 @@ func (sp *StreamParser) Next() (telegraf.Metric, error) { return nil, err } - return nil, ErrEOF + return nil, io.EOF } m, err := nextMetric(sp.decoder, sp.precision, sp.defaultTime, false) diff --git a/plugins/parsers/influx/influx_upstream/parser_test.go b/plugins/parsers/influx/influx_upstream/parser_test.go index d9ad173bd..b96bf0b47 100644 --- a/plugins/parsers/influx/influx_upstream/parser_test.go +++ b/plugins/parsers/influx/influx_upstream/parser_test.go @@ -660,7 +660,7 @@ func TestStreamParser(t *testing.T) { for { m, err := parser.Next() if err != nil { - if errors.Is(err, ErrEOF) { + if errors.Is(err, io.EOF) { break } require.Equal(t, tt.err.Error(), err.Error()) @@ -958,7 +958,7 @@ func TestStreamParserErrorString(t *testing.T) { var errs []error for i := 0; i < 20; i++ { _, err := parser.Next() - if errors.Is(err, ErrEOF) { + if errors.Is(err, io.EOF) { break } @@ -997,7 +997,7 @@ func TestStreamParserReaderError(t *testing.T) { require.Equal(t, err, readerErr) _, err = parser.Next() - require.Equal(t, err, ErrEOF) + require.Equal(t, err, io.EOF) } func TestStreamParserProducesAllAvailableMetrics(t *testing.T) { diff --git a/plugins/parsers/json/json_flattener.go b/plugins/parsers/json/json_flattener.go index ee201b90e..f003039f0 100644 --- a/plugins/parsers/json/json_flattener.go +++ b/plugins/parsers/json/json_flattener.go @@ -64,8 +64,7 @@ func (f *JSONFlattener) FullFlattenJSON(fieldName string, v interface{}, convert case nil: return nil default: - return fmt.Errorf("JSON Flattener: got unexpected type %T with value %v (%s)", - t, t, fieldName) + return fmt.Errorf("json flattener: got unexpected type %T with value %v (%s)", t, t, fieldName) } return nil } diff --git a/plugins/parsers/json/parser.go b/plugins/parsers/json/parser.go index 4f6bc687a..d6c913732 100644 --- a/plugins/parsers/json/parser.go +++ b/plugins/parsers/json/parser.go @@ -92,7 +92,7 @@ func (p *Parser) parseObject(data map[string]interface{}, timestamp time.Time) ( } if f.Fields[p.TimeKey] == nil { - err := errors.New("JSON time key could not be found") + err := errors.New("'json_time_key' could not be found") return nil, err } diff --git a/plugins/parsers/json/parser_test.go b/plugins/parsers/json/parser_test.go index b69615dbf..70f108167 100644 --- a/plugins/parsers/json/parser_test.go +++ b/plugins/parsers/json/parser_test.go @@ -840,7 +840,7 @@ func TestTimeErrors(t *testing.T) { actual, err = parser.Parse([]byte(testString2)) require.Error(t, err) require.Empty(t, actual) - require.Equal(t, errors.New("JSON time key could not be found"), err) + require.Equal(t, errors.New("'json_time_key' could not be found"), err) } func TestShareTimestamp(t *testing.T) { diff --git a/plugins/parsers/json_v2/parser.go b/plugins/parsers/json_v2/parser.go index 0381a2a14..f4def6f34 100644 --- a/plugins/parsers/json_v2/parser.go +++ b/plugins/parsers/json_v2/parser.go @@ -230,7 +230,7 @@ func (p *Parser) processMetric(input []byte, data []DataSet, tag bool, timestamp metrics := make([][]telegraf.Metric, 0, len(data)) for _, c := range data { if c.Path == "" { - return nil, errors.New("GJSON path is required") + return nil, errors.New("the GJSON path is required") } result := gjson.GetBytes(input, c.Path) if err := p.checkResult(result, c.Path); err != nil { @@ -477,7 +477,7 @@ func (p *Parser) processObjects(input []byte, objects []Object, timestamp time.T p.objectConfig = c if c.Path == "" { - return nil, errors.New("GJSON path is required") + return nil, errors.New("the GJSON path is required") } result := gjson.GetBytes(input, c.Path) @@ -649,7 +649,7 @@ func (p *Parser) isExcluded(key string) bool { } func (p *Parser) ParseLine(_ string) (telegraf.Metric, error) { - return nil, errors.New("ParseLine is designed for parsing influx line protocol, therefore not implemented for parsing JSON") + return nil, errors.New("parsing line is not supported by JSON format") } func (p *Parser) SetDefaultTags(tags map[string]string) { diff --git a/plugins/parsers/nagios/parser_test.go b/plugins/parsers/nagios/parser_test.go index c7a111c0c..939a2c187 100644 --- a/plugins/parsers/nagios/parser_test.go +++ b/plugins/parsers/nagios/parser_test.go @@ -30,10 +30,10 @@ func TestGetExitCode(t *testing.T) { { name: "unexpected error type", errF: func() error { - return errors.New("I am not *exec.ExitError") + return errors.New("not *exec.ExitError") }, expCode: 3, - expErr: errors.New("I am not *exec.ExitError"), + expErr: errors.New("not *exec.ExitError"), }, } diff --git a/plugins/parsers/wavefront/element.go b/plugins/parsers/wavefront/element.go index a456d1595..1b78b4449 100644 --- a/plugins/parsers/wavefront/element.go +++ b/plugins/parsers/wavefront/element.go @@ -3,12 +3,12 @@ package wavefront import ( "errors" "fmt" + "io" "strconv" "time" ) var ( - errEOF = errors.New("EOF") errInvalidTimestamp = errors.New("invalid timestamp") ) @@ -130,7 +130,7 @@ func (ep *loopedParser) parse(p *PointParser, pt *Point) error { return err } err = ep.wsParser.parse(p, pt) - if errors.Is(err, errEOF) { + if errors.Is(err, io.EOF) { break } } @@ -170,7 +170,7 @@ func (ep *whiteSpaceParser) parse(p *PointParser, _ *Point) error { if tok == EOF { if !ep.nextOptional { - return errEOF + return io.EOF } return nil } diff --git a/plugins/processors/snmp_lookup/lookup_test.go b/plugins/processors/snmp_lookup/lookup_test.go index b4ab67e33..68ae011b0 100644 --- a/plugins/processors/snmp_lookup/lookup_test.go +++ b/plugins/processors/snmp_lookup/lookup_test.go @@ -27,13 +27,13 @@ func (tsc *testSNMPConnection) Host() string { } func (tsc *testSNMPConnection) Get(_ []string) (*gosnmp.SnmpPacket, error) { - return &gosnmp.SnmpPacket{}, errors.New("Not implemented") + return &gosnmp.SnmpPacket{}, errors.New("not implemented") } func (tsc *testSNMPConnection) Walk(oid string, wf gosnmp.WalkFunc) error { tsc.calls.Add(1) if len(tsc.values) == 0 { - return errors.New("No values") + return errors.New("no values") } for void, v := range tsc.values { if void == oid || (len(void) > len(oid) && void[:len(oid)+1] == oid+".") { @@ -49,7 +49,7 @@ func (tsc *testSNMPConnection) Walk(oid string, wf gosnmp.WalkFunc) error { } func (tsc *testSNMPConnection) Reconnect() error { - return errors.New("Not implemented") + return errors.New("not implemented") } func TestRegistry(t *testing.T) { @@ -242,7 +242,7 @@ func TestUpdateAgent(t *testing.T) { t.Run("connection fail", func(t *testing.T) { p.getConnectionFunc = func(string) (snmp.Connection, error) { - return nil, errors.New("Random connection error") + return nil, errors.New("random connection error") } start := time.Now() diff --git a/tools/config_includer/generator.go b/tools/config_includer/generator.go index d4686cc98..bca1ce9dc 100644 --- a/tools/config_includer/generator.go +++ b/tools/config_includer/generator.go @@ -28,7 +28,7 @@ func absolutePath(root, fn string) (string, error) { } pwd, err = filepath.Rel(root, filepath.Dir(pwd)) if err != nil { - return "", fmt.Errorf("Cannot determine location of %q relative to %q: %w", pwd, root, err) + return "", fmt.Errorf("cannot determine location of %q relative to %q: %w", pwd, root, err) } return string(filepath.Separator) + pwd, nil }