Skip to content

Commit

Permalink
chore(linters): Enable string-format rule for revive (influxdata#15983
Browse files Browse the repository at this point in the history
)
  • Loading branch information
zak-pawel authored Oct 9, 2024
1 parent 56f2d6e commit 0804cce
Show file tree
Hide file tree
Showing 48 changed files with 117 additions and 107 deletions.
17 changes: 17 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions cmd/telegraf/telegraf.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions internal/snmp/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions internal/snmp/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions plugins/common/shim/goshim.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions plugins/common/socket/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/activemq/activemq.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/bond/bond.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
8 changes: 4 additions & 4 deletions plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/google_cloud_storage/google_cloud_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}

Expand Down Expand Up @@ -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 != "" {
Expand Down
3 changes: 2 additions & 1 deletion plugins/inputs/influxdb_listener/influxdb_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 3 additions & 5 deletions plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand All @@ -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)
Expand Down
9 changes: 3 additions & 6 deletions plugins/inputs/intel_pmt/xml_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 6 additions & 4 deletions plugins/inputs/iptables/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/kafka_consumer/kafka_consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 1 addition & 3 deletions plugins/inputs/linux_cpu/linux_cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/nginx_plus_api/nginx_plus_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/opcua/read_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions plugins/inputs/ping/ping_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions plugins/inputs/sflow/packetdecoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading

0 comments on commit 0804cce

Please sign in to comment.