diff --git a/agent/accumulator_test.go b/agent/accumulator_test.go index d8a697eaf..254fea36e 100644 --- a/agent/accumulator_test.go +++ b/agent/accumulator_test.go @@ -2,7 +2,7 @@ package agent import ( "bytes" - "fmt" + "errors" "log" "os" "testing" @@ -55,9 +55,9 @@ func TestAccAddError(t *testing.T) { defer close(metrics) a := NewAccumulator(&TestMetricMaker{}, metrics) - a.AddError(fmt.Errorf("foo")) - a.AddError(fmt.Errorf("bar")) - a.AddError(fmt.Errorf("baz")) + a.AddError(errors.New("foo")) + a.AddError(errors.New("bar")) + a.AddError(errors.New("baz")) errs := bytes.Split(errBuf.Bytes(), []byte{'\n'}) require.Len(t, errs, 4) // 4 because of trailing newline diff --git a/config/config.go b/config/config.go index e2245fb1f..33ebf5d25 100644 --- a/config/config.go +++ b/config/config.go @@ -503,7 +503,7 @@ func (c *Config) LoadConfigData(data []byte) error { if val, ok := tbl.Fields["agent"]; ok { subTable, ok := val.(*ast.Table) if !ok { - return fmt.Errorf("invalid configuration, error parsing agent table") + return errors.New("invalid configuration, error parsing agent table") } if err = c.toml.UnmarshalTable(subTable, c.Agent); err != nil { return fmt.Errorf("error parsing [agent]: %w", err) @@ -794,7 +794,7 @@ func (c *Config) addAggregator(name string, table *ast.Table) error { // Handle removed, deprecated plugins if di, deprecated := aggregators.Deprecations[name]; deprecated { printHistoricPluginDeprecationNotice("aggregators", name, di) - return fmt.Errorf("plugin deprecated") + return errors.New("plugin deprecated") } return fmt.Errorf("undefined but requested aggregator: %s", name) } @@ -980,7 +980,7 @@ func (c *Config) addProcessor(name string, table *ast.Table) error { // Handle removed, deprecated plugins if di, deprecated := processors.Deprecations[name]; deprecated { printHistoricPluginDeprecationNotice("processors", name, di) - return fmt.Errorf("plugin deprecated") + return errors.New("plugin deprecated") } return fmt.Errorf("undefined but requested processor: %s", name) } @@ -1109,7 +1109,7 @@ func (c *Config) addOutput(name string, table *ast.Table) error { // Handle removed, deprecated plugins if di, deprecated := outputs.Deprecations[name]; deprecated { printHistoricPluginDeprecationNotice("outputs", name, di) - return fmt.Errorf("plugin deprecated") + return errors.New("plugin deprecated") } return fmt.Errorf("undefined but requested output: %s", name) } @@ -1191,7 +1191,7 @@ func (c *Config) addInput(name string, table *ast.Table) error { // Handle removed, deprecated plugins if di, deprecated := inputs.Deprecations[name]; deprecated { printHistoricPluginDeprecationNotice("inputs", name, di) - return fmt.Errorf("plugin deprecated") + return errors.New("plugin deprecated") } return fmt.Errorf("undefined but requested input: %s", name) diff --git a/config/deprecation.go b/config/deprecation.go index 52c315c38..f06f20b6a 100644 --- a/config/deprecation.go +++ b/config/deprecation.go @@ -1,6 +1,7 @@ package config import ( + "errors" "fmt" "log" "reflect" @@ -171,7 +172,7 @@ func (c *Config) printUserDeprecation(category, name string, plugin interface{}) models.PrintPluginDeprecationNotice(info.LogLevel, info.Name, info.info) if info.LogLevel == telegraf.Error { - return fmt.Errorf("plugin deprecated") + return errors.New("plugin deprecated") } // Print deprecated options diff --git a/internal/snmp/translate.go b/internal/snmp/translate.go index da3e641d7..dc3798254 100644 --- a/internal/snmp/translate.go +++ b/internal/snmp/translate.go @@ -1,6 +1,7 @@ package snmp import ( + "errors" "fmt" "os" "path/filepath" @@ -271,7 +272,7 @@ func SnmpTranslateCall(oid string) (mibName string, oidNum string, oidText strin oidText = out.RenderQualified() i := strings.Index(oidText, "::") if i == -1 { - return "", oid, oid, oid, out, fmt.Errorf("not found") + return "", oid, oid, oid, out, errors.New("not found") } mibName = oidText[:i] oidText = oidText[i+2:] + end diff --git a/internal/snmp/wrapper.go b/internal/snmp/wrapper.go index 88fa3d65f..a6082e463 100644 --- a/internal/snmp/wrapper.go +++ b/internal/snmp/wrapper.go @@ -1,6 +1,7 @@ package snmp import ( + "errors" "fmt" "net/url" "strconv" @@ -46,7 +47,7 @@ func NewWrapper(s ClientConfig) (GosnmpWrapper, error) { case 1: gs.Version = gosnmp.Version1 default: - return GosnmpWrapper{}, fmt.Errorf("invalid version") + return GosnmpWrapper{}, errors.New("invalid version") } if s.Version < 3 { @@ -74,7 +75,7 @@ func NewWrapper(s ClientConfig) (GosnmpWrapper, error) { case "authpriv": gs.MsgFlags = gosnmp.AuthPriv default: - return GosnmpWrapper{}, fmt.Errorf("invalid secLevel") + return GosnmpWrapper{}, errors.New("invalid secLevel") } sp.UserName = s.SecName @@ -95,7 +96,7 @@ func NewWrapper(s ClientConfig) (GosnmpWrapper, error) { case "": sp.AuthenticationProtocol = gosnmp.NoAuth default: - return GosnmpWrapper{}, fmt.Errorf("invalid authProtocol") + return GosnmpWrapper{}, errors.New("invalid authProtocol") } sp.AuthenticationPassphrase = s.AuthPassword @@ -116,7 +117,7 @@ func NewWrapper(s ClientConfig) (GosnmpWrapper, error) { case "": sp.PrivacyProtocol = gosnmp.NoPriv default: - return GosnmpWrapper{}, fmt.Errorf("invalid privProtocol") + return GosnmpWrapper{}, errors.New("invalid privProtocol") } sp.PrivacyPassphrase = s.PrivPassword diff --git a/internal/syslog/framing.go b/internal/syslog/framing.go index 13932c802..aad9b58d2 100644 --- a/internal/syslog/framing.go +++ b/internal/syslog/framing.go @@ -1,7 +1,7 @@ package syslog import ( - "fmt" + "errors" "strings" ) @@ -50,7 +50,7 @@ func (f *Framing) UnmarshalText(data []byte) error { return nil } *f = -1 - return fmt.Errorf("unknown framing") + return errors.New("unknown framing") } // MarshalText implements encoding.TextMarshaller @@ -59,5 +59,5 @@ func (f Framing) MarshalText() ([]byte, error) { if s != "" { return []byte(s), nil } - return nil, fmt.Errorf("unknown framing") + return nil, errors.New("unknown framing") } diff --git a/models/running_output_test.go b/models/running_output_test.go index c12028ebc..013ecbe60 100644 --- a/models/running_output_test.go +++ b/models/running_output_test.go @@ -1,7 +1,7 @@ package models import ( - "fmt" + "errors" "sync" "testing" "time" @@ -532,7 +532,7 @@ func (m *mockOutput) Write(metrics []telegraf.Metric) error { m.Lock() defer m.Unlock() if m.failWrite { - return fmt.Errorf("failed write") + return errors.New("failed write") } if m.metrics == nil { @@ -572,7 +572,7 @@ func (m *perfOutput) SampleConfig() string { func (m *perfOutput) Write(_ []telegraf.Metric) error { if m.failWrite { - return fmt.Errorf("failed write") + return errors.New("failed write") } return nil } diff --git a/plugins/common/cookie/cookie_test.go b/plugins/common/cookie/cookie_test.go index 24c527024..0436de1ee 100644 --- a/plugins/common/cookie/cookie_test.go +++ b/plugins/common/cookie/cookie_test.go @@ -2,7 +2,7 @@ package cookie import ( "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -12,9 +12,10 @@ import ( clockutil "github.com/benbjohnson/clock" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) const ( @@ -189,7 +190,7 @@ func TestAuthConfig_Start(t *testing.T) { renewal: renewal, endpoint: authEndpointWithBasicAuth, }, - wantErr: fmt.Errorf("cookie auth renewal received status code: 401 (Unauthorized) []"), + wantErr: errors.New("cookie auth renewal received status code: 401 (Unauthorized) []"), firstAuthCount: 0, lastAuthCount: 0, firstHTTPResponse: http.StatusForbidden, @@ -220,7 +221,7 @@ func TestAuthConfig_Start(t *testing.T) { renewal: renewal, endpoint: authEndpointWithBody, }, - wantErr: fmt.Errorf("cookie auth renewal received status code: 401 (Unauthorized) []"), + wantErr: errors.New("cookie auth renewal received status code: 401 (Unauthorized) []"), firstAuthCount: 0, lastAuthCount: 0, firstHTTPResponse: http.StatusForbidden, diff --git a/plugins/common/kafka/config.go b/plugins/common/kafka/config.go index cd3fd432a..76931aa65 100644 --- a/plugins/common/kafka/config.go +++ b/plugins/common/kafka/config.go @@ -1,12 +1,13 @@ package kafka import ( - "fmt" + "errors" "math" "strings" "time" "github.com/IBM/sarama" + "github.com/influxdata/telegraf" tgConf "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/common/tls" @@ -141,7 +142,7 @@ func (k *Config) SetConfig(config *sarama.Config, log telegraf.Logger) error { switch strings.ToLower(k.MetadataRetryType) { default: - return fmt.Errorf("invalid metadata retry type") + return errors.New("invalid metadata retry type") case "exponential": if k.MetadataRetryBackoff == 0 { k.MetadataRetryBackoff = tgConf.Duration(250 * time.Millisecond) diff --git a/plugins/common/opcua/client.go b/plugins/common/opcua/client.go index 600c9276a..52dc132fa 100644 --- a/plugins/common/opcua/client.go +++ b/plugins/common/opcua/client.go @@ -2,6 +2,7 @@ package opcua import ( "context" + "errors" "fmt" "log" //nolint:depguard // just for debug "net/url" @@ -67,12 +68,12 @@ func (o *OpcUAClientConfig) validateOptionalFields() error { func (o *OpcUAClientConfig) validateEndpoint() error { if o.Endpoint == "" { - return fmt.Errorf("endpoint url is empty") + return errors.New("endpoint url is empty") } _, err := url.Parse(o.Endpoint) if err != nil { - return fmt.Errorf("endpoint url is invalid") + return errors.New("endpoint url is invalid") } switch o.SecurityPolicy { @@ -224,7 +225,7 @@ func (o *OpcUAClient) Disconnect(ctx context.Context) error { o.Client = nil return err default: - return fmt.Errorf("invalid controller") + return errors.New("invalid controller") } } diff --git a/plugins/common/opcua/input/input_client.go b/plugins/common/opcua/input/input_client.go index b463c8ad2..1412f011a 100644 --- a/plugins/common/opcua/input/input_client.go +++ b/plugins/common/opcua/input/input_client.go @@ -95,7 +95,7 @@ type InputClientConfig struct { func (o *InputClientConfig) Validate() error { if o.MetricName == "" { - return fmt.Errorf("metric name is empty") + return errors.New("metric name is empty") } err := choice.Check(string(o.Timestamp), []string{"", "gather", "server", "source"}) @@ -278,11 +278,11 @@ func validateNodeToAdd(existing map[metricParts]struct{}, nmm *NodeMetricMapping } if len(nmm.Tag.Namespace) == 0 { - return fmt.Errorf("empty node namespace not allowed") + return errors.New("empty node namespace not allowed") } if len(nmm.Tag.Identifier) == 0 { - return fmt.Errorf("empty node identifier not allowed") + return errors.New("empty node identifier not allowed") } mp := newMP(nmm) diff --git a/plugins/common/opcua/input/input_client_test.go b/plugins/common/opcua/input/input_client_test.go index a55735f61..5a2299809 100644 --- a/plugins/common/opcua/input/input_client_test.go +++ b/plugins/common/opcua/input/input_client_test.go @@ -2,7 +2,6 @@ package input import ( "errors" - "fmt" "testing" "time" @@ -39,9 +38,9 @@ func TestTagsSliceToMap_dupeKey(t *testing.T) { func TestTagsSliceToMap_empty(t *testing.T) { _, err := tagsSliceToMap([][]string{{"foo", ""}}) - require.Equal(t, fmt.Errorf("tag 1 has empty value"), err) + require.Equal(t, errors.New("tag 1 has empty value"), err) _, err = tagsSliceToMap([][]string{{"", "bar"}}) - require.Equal(t, fmt.Errorf("tag 1 has empty name"), err) + require.Equal(t, errors.New("tag 1 has empty name"), err) } func TestValidateOPCTags(t *testing.T) { @@ -91,7 +90,7 @@ func TestValidateOPCTags(t *testing.T) { }, }, }, - fmt.Errorf("tag 1 has empty value"), + errors.New("tag 1 has empty value"), }, { "empty tag name not allowed", @@ -105,7 +104,7 @@ func TestValidateOPCTags(t *testing.T) { }, }, }, - fmt.Errorf("tag 1 has empty name"), + errors.New("tag 1 has empty name"), }, { "different metric tag names", @@ -370,7 +369,7 @@ func TestValidateNodeToAdd(t *testing.T) { }, map[string]string{}) return nmm }(), - err: fmt.Errorf("empty node namespace not allowed"), + err: errors.New("empty node namespace not allowed"), }, { name: "empty identifier type not allowed", diff --git a/plugins/common/opcua/opcua_util.go b/plugins/common/opcua/opcua_util.go index 035c2353f..192c36306 100644 --- a/plugins/common/opcua/opcua_util.go +++ b/plugins/common/opcua/opcua_util.go @@ -8,6 +8,7 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/pem" + "errors" "fmt" "math/big" "net" @@ -34,7 +35,7 @@ func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.D dir, _ := newTempDir() if len(host) == 0 { - return "", "", fmt.Errorf("missing required host parameter") + return "", "", errors.New("missing required host parameter") } if rsaBits == 0 { rsaBits = 2048 @@ -181,7 +182,7 @@ func (o *OpcUAClient) generateClientOpts(endpoints []*ua.EndpointDescription) ([ } else { pk, ok := c.PrivateKey.(*rsa.PrivateKey) if !ok { - return nil, fmt.Errorf("invalid private key") + return nil, errors.New("invalid private key") } cert = c.Certificate[0] opts = append(opts, opcua.PrivateKey(pk), opcua.Certificate(cert)) @@ -276,7 +277,7 @@ func (o *OpcUAClient) generateClientOpts(endpoints []*ua.EndpointDescription) ([ } if serverEndpoint == nil { // Didn't find an endpoint with matching policy and mode. - return nil, fmt.Errorf("unable to find suitable server endpoint with selected sec-policy and sec-mode") + return nil, errors.New("unable to find suitable server endpoint with selected sec-policy and sec-mode") } secPolicy = serverEndpoint.SecurityPolicyURI diff --git a/plugins/common/shim/goshim.go b/plugins/common/shim/goshim.go index 2205bdce7..57095a3d9 100644 --- a/plugins/common/shim/goshim.go +++ b/plugins/common/shim/goshim.go @@ -2,6 +2,7 @@ package shim import ( "context" + "errors" "fmt" "io" "os" @@ -90,7 +91,7 @@ func (s *Shim) Run(pollInterval time.Duration) error { return fmt.Errorf("RunOutput error: %w", err) } } else { - return fmt.Errorf("nothing to run") + return errors.New("nothing to run") } return nil diff --git a/plugins/common/starlark/field_dict.go b/plugins/common/starlark/field_dict.go index 50b3ca388..bcb0793cc 100644 --- a/plugins/common/starlark/field_dict.go +++ b/plugins/common/starlark/field_dict.go @@ -2,7 +2,6 @@ package starlark import ( "errors" - "fmt" "reflect" "strings" @@ -97,7 +96,7 @@ func (d FieldDict) Get(key starlark.Value) (v starlark.Value, found bool, err er // using x[k]=v syntax, like a dictionary. func (d FieldDict) SetKey(k, v starlark.Value) error { if d.fieldIterCount > 0 { - return fmt.Errorf("cannot insert during iteration") + return errors.New("cannot insert during iteration") } key, ok := k.(starlark.String) @@ -131,7 +130,7 @@ func (d FieldDict) Items() []starlark.Tuple { func (d FieldDict) Clear() error { if d.fieldIterCount > 0 { - return fmt.Errorf("cannot delete during iteration") + return errors.New("cannot delete during iteration") } keys := make([]string, 0, len(d.metric.FieldList())) @@ -147,7 +146,7 @@ func (d FieldDict) Clear() error { func (d FieldDict) PopItem() (starlark.Value, error) { if d.fieldIterCount > 0 { - return nil, fmt.Errorf("cannot delete during iteration") + return nil, errors.New("cannot delete during iteration") } if len(d.metric.FieldList()) == 0 { @@ -163,7 +162,7 @@ func (d FieldDict) PopItem() (starlark.Value, error) { sk := starlark.String(k) sv, err := asStarlarkValue(v) if err != nil { - return nil, fmt.Errorf("could not convert to starlark value") + return nil, errors.New("could not convert to starlark value") } return starlark.Tuple{sk, sv}, nil @@ -171,7 +170,7 @@ func (d FieldDict) PopItem() (starlark.Value, error) { func (d FieldDict) Delete(k starlark.Value) (v starlark.Value, found bool, err error) { if d.fieldIterCount > 0 { - return nil, false, fmt.Errorf("cannot delete during iteration") + return nil, false, errors.New("cannot delete during iteration") } if key, ok := k.(starlark.String); ok { diff --git a/plugins/common/starlark/metric.go b/plugins/common/starlark/metric.go index 93634e6fd..2a8f9c34d 100644 --- a/plugins/common/starlark/metric.go +++ b/plugins/common/starlark/metric.go @@ -97,7 +97,7 @@ func (m *Metric) Attr(name string) (starlark.Value, error) { // SetField implements the starlark.HasSetField interface. func (m *Metric) SetField(name string, value starlark.Value) error { if m.frozen { - return fmt.Errorf("cannot modify frozen metric") + return errors.New("cannot modify frozen metric") } switch name { diff --git a/plugins/common/starlark/tag_dict.go b/plugins/common/starlark/tag_dict.go index 4def1d4ba..48c63196f 100644 --- a/plugins/common/starlark/tag_dict.go +++ b/plugins/common/starlark/tag_dict.go @@ -2,7 +2,6 @@ package starlark import ( "errors" - "fmt" "strings" "go.starlark.net/starlark" @@ -91,7 +90,7 @@ func (d TagDict) Get(key starlark.Value) (v starlark.Value, found bool, err erro // using x[k]=v syntax, like a dictionary. func (d TagDict) SetKey(k, v starlark.Value) error { if d.tagIterCount > 0 { - return fmt.Errorf("cannot insert during iteration") + return errors.New("cannot insert during iteration") } key, ok := k.(starlark.String) @@ -122,7 +121,7 @@ func (d TagDict) Items() []starlark.Tuple { func (d TagDict) Clear() error { if d.tagIterCount > 0 { - return fmt.Errorf("cannot delete during iteration") + return errors.New("cannot delete during iteration") } keys := make([]string, 0, len(d.metric.TagList())) @@ -138,7 +137,7 @@ func (d TagDict) Clear() error { func (d TagDict) PopItem() (v starlark.Value, err error) { if d.tagIterCount > 0 { - return nil, fmt.Errorf("cannot delete during iteration") + return nil, errors.New("cannot delete during iteration") } for _, tag := range d.metric.TagList() { @@ -157,7 +156,7 @@ func (d TagDict) PopItem() (v starlark.Value, err error) { func (d TagDict) Delete(k starlark.Value) (v starlark.Value, found bool, err error) { if d.tagIterCount > 0 { - return nil, false, fmt.Errorf("cannot delete during iteration") + return nil, false, errors.New("cannot delete during iteration") } if key, ok := k.(starlark.String); ok { diff --git a/plugins/common/tls/config.go b/plugins/common/tls/config.go index 631ae342c..8f2edc2c0 100644 --- a/plugins/common/tls/config.go +++ b/plugins/common/tls/config.go @@ -10,8 +10,9 @@ import ( "os" "strings" - "github.com/influxdata/telegraf/internal/choice" "github.com/youmark/pkcs8" + + "github.com/influxdata/telegraf/internal/choice" ) const TLSMinVersionDefault = tls.VersionTLS12 @@ -254,7 +255,7 @@ func loadCertificate(config *tls.Config, certFile, keyFile, privateKeyPassphrase } else if keyPEMBlock.Headers["Proc-Type"] == "4,ENCRYPTED" { // The key is an encrypted private key with the DEK-Info header. // This is currently unsupported because of the deprecation of x509.IsEncryptedPEMBlock and x509.DecryptPEMBlock. - return fmt.Errorf("password-protected keys in pkcs#1 format are not supported") + return errors.New("password-protected keys in pkcs#1 format are not supported") } else { cert, err = tls.X509KeyPair(certBytes, keyBytes) if err != nil { diff --git a/plugins/inputs/azure_monitor/azure_monitor_test.go b/plugins/inputs/azure_monitor/azure_monitor_test.go index ef93675ee..707f78e9e 100644 --- a/plugins/inputs/azure_monitor/azure_monitor_test.go +++ b/plugins/inputs/azure_monitor/azure_monitor_test.go @@ -3,16 +3,18 @@ package azure_monitor import ( "context" "encoding/json" + "errors" "fmt" "os" "testing" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/monitor/armmonitor" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" - "github.com/influxdata/telegraf/testutil" "github.com/influxdata/toml" receiver "github.com/logzio/azure-monitor-metrics-receiver" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf/testutil" ) type mockAzureClientsManager struct{} @@ -98,7 +100,7 @@ func (marc *mockAzureResourcesClient) ListByResourceGroup( return responses, nil } - return nil, fmt.Errorf("resource group was not found") + return nil, errors.New("resource group was not found") } func (mamdc *mockAzureMetricDefinitionsClient) List( @@ -139,7 +141,7 @@ func (mamdc *mockAzureMetricDefinitionsClient) List( }, nil } - return armmonitor.MetricDefinitionsClientListResponse{}, fmt.Errorf("resource ID was not found") + return armmonitor.MetricDefinitionsClientListResponse{}, errors.New("resource ID was not found") } func (mamc *mockAzureMetricsClient) List( @@ -192,7 +194,7 @@ func (mamc *mockAzureMetricsClient) List( }, nil } - return armmonitor.MetricsClientListResponse{}, fmt.Errorf("resource ID was not found") + return armmonitor.MetricsClientListResponse{}, errors.New("resource ID was not found") } func TestInit_ResourceTargetsOnly(t *testing.T) { diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go index 910b8071c..f52533fcb 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 fmt.Errorf("TCP dialout premature EOF") + return errors.New("TCP dialout premature EOF") } c.handleTelemetry(payload.Bytes()) @@ -752,7 +752,7 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie if len(rn) > 0 { tags[prefix] = rn } else if !dn { // Check for distinguished name being present - c.acc.AddError(fmt.Errorf("NX-OS decoding failed: missing dn field")) + c.acc.AddError(errors.New("NX-OS decoding failed: missing dn field")) return } diff --git a/plugins/inputs/cloud_pubsub/cloud_pubsub.go b/plugins/inputs/cloud_pubsub/cloud_pubsub.go index a232300e1..0d0c2b686 100644 --- a/plugins/inputs/cloud_pubsub/cloud_pubsub.go +++ b/plugins/inputs/cloud_pubsub/cloud_pubsub.go @@ -5,6 +5,7 @@ import ( "context" _ "embed" "encoding/base64" + "errors" "fmt" "sync" "time" @@ -309,11 +310,11 @@ func (ps *PubSub) getGCPSubscription(subID string) (subscription, error) { func (ps *PubSub) Init() error { if ps.Subscription == "" { - return fmt.Errorf(`"subscription" is required`) + return errors.New(`"subscription" is required`) } if ps.Project == "" { - return fmt.Errorf(`"project" is required`) + return errors.New(`"project" is required`) } switch ps.ContentEncoding { diff --git a/plugins/inputs/cloud_pubsub_push/cloud_pubsub_push_test.go b/plugins/inputs/cloud_pubsub_push/cloud_pubsub_push_test.go index 8064d3b1e..11e594f9c 100644 --- a/plugins/inputs/cloud_pubsub_push/cloud_pubsub_push_test.go +++ b/plugins/inputs/cloud_pubsub_push/cloud_pubsub_push_test.go @@ -4,7 +4,7 @@ package cloud_pubsub_push import ( "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -256,7 +256,7 @@ func (*testOutput) SampleConfig() string { func (t *testOutput) Write(_ []telegraf.Metric) error { if t.failWrite { - return fmt.Errorf("failed write") + return errors.New("failed write") } return nil } diff --git a/plugins/inputs/conntrack/conntrack.go b/plugins/inputs/conntrack/conntrack.go index cd622cd74..d8e29aa10 100644 --- a/plugins/inputs/conntrack/conntrack.go +++ b/plugins/inputs/conntrack/conntrack.go @@ -5,6 +5,7 @@ package conntrack import ( _ "embed" + "errors" "fmt" "os" "path/filepath" @@ -110,7 +111,7 @@ func (c *Conntrack) Gather(acc telegraf.Accumulator) error { } if len(stats) == 0 { - acc.AddError(fmt.Errorf("conntrack input failed to collect stats")) + acc.AddError(errors.New("conntrack input failed to collect stats")) } cpuTag := "all" @@ -146,8 +147,7 @@ func (c *Conntrack) Gather(acc telegraf.Accumulator) error { } if len(fields) == 0 { - return fmt.Errorf("Conntrack input failed to collect metrics. " + - "Is the conntrack kernel module loaded?") + return errors.New("conntrack input failed to collect metrics, make sure that the kernel module is loaded") } acc.AddFields(inputName, fields, nil) diff --git a/plugins/inputs/conntrack/conntrack_test.go b/plugins/inputs/conntrack/conntrack_test.go index 3e7310f99..b23f9426a 100644 --- a/plugins/inputs/conntrack/conntrack_test.go +++ b/plugins/inputs/conntrack/conntrack_test.go @@ -31,8 +31,7 @@ func TestNoFilesFound(t *testing.T) { acc := &testutil.Accumulator{} err := c.Gather(acc) - require.EqualError(t, err, "Conntrack input failed to collect metrics. "+ - "Is the conntrack kernel module loaded?") + require.EqualError(t, err, "conntrack input failed to collect metrics, make sure that the kernel module is loaded") } func TestDefaultsUsed(t *testing.T) { diff --git a/plugins/inputs/cpu/cpu.go b/plugins/inputs/cpu/cpu.go index 90cfa2449..72c348bc0 100644 --- a/plugins/inputs/cpu/cpu.go +++ b/plugins/inputs/cpu/cpu.go @@ -3,6 +3,7 @@ package cpu import ( _ "embed" + "errors" "fmt" "time" @@ -92,7 +93,7 @@ func (c *CPUStats) Gather(acc telegraf.Accumulator) error { totalDelta := total - lastTotal if totalDelta < 0 { - err = fmt.Errorf("current total CPU time is less than previous total CPU time") + err = errors.New("current total CPU time is less than previous total CPU time") break } diff --git a/plugins/inputs/dmcache/dmcache_linux.go b/plugins/inputs/dmcache/dmcache_linux.go index 309df1494..ee82f0da9 100644 --- a/plugins/inputs/dmcache/dmcache_linux.go +++ b/plugins/inputs/dmcache/dmcache_linux.go @@ -3,12 +3,11 @@ package dmcache import ( + "errors" "os/exec" "strconv" "strings" - "errors" - "github.com/influxdata/telegraf" ) diff --git a/plugins/inputs/dpdk/dpdk_test.go b/plugins/inputs/dpdk/dpdk_test.go index 84c921729..320c9007a 100644 --- a/plugins/inputs/dpdk/dpdk_test.go +++ b/plugins/inputs/dpdk/dpdk_test.go @@ -4,6 +4,7 @@ package dpdk import ( "encoding/json" + "errors" "fmt" "math/rand" "net" @@ -524,7 +525,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { t.Run("when ethdev commands are enabled but params fetching command returns error then error should be logged in accumulator", func(t *testing.T) { mockConn, dpdk, mockAcc := prepareEnvironment() defer mockConn.AssertExpectations(t) - simulateResponse(mockConn, `{notAJson}`, fmt.Errorf("some error")) + simulateResponse(mockConn, `{notAJson}`, errors.New("some error")) dpdk.DeviceTypes = []string{"ethdev"} dpdk.ethdevCommands = []string{"/ethdev/stats", "/ethdev/xstats"} diff --git a/plugins/inputs/elasticsearch_query/elasticsearch_query.go b/plugins/inputs/elasticsearch_query/elasticsearch_query.go index 366008999..8e2fc7cc2 100644 --- a/plugins/inputs/elasticsearch_query/elasticsearch_query.go +++ b/plugins/inputs/elasticsearch_query/elasticsearch_query.go @@ -4,6 +4,7 @@ package elasticsearch_query import ( "context" _ "embed" + "errors" "fmt" "net/http" "strconv" @@ -63,7 +64,7 @@ func (*ElasticsearchQuery) SampleConfig() string { // Init the plugin. func (e *ElasticsearchQuery) Init() error { if e.URLs == nil { - return fmt.Errorf("elasticsearch urls is not defined") + return errors.New("elasticsearch urls is not defined") } err := e.connectToES() @@ -77,10 +78,10 @@ func (e *ElasticsearchQuery) Init() error { for i, agg := range e.Aggregations { if agg.MeasurementName == "" { - return fmt.Errorf("field 'measurement_name' is not set") + return errors.New("field 'measurement_name' is not set") } if agg.DateField == "" { - return fmt.Errorf("field 'date_field' is not set") + return errors.New("field 'date_field' is not set") } err = e.initAggregation(ctx, agg, i) if err != nil { @@ -160,7 +161,7 @@ func (e *ElasticsearchQuery) connectToES() error { // quit if ES version is not supported if len(esVersionSplit) == 0 { - return fmt.Errorf("elasticsearch version check failed") + return errors.New("elasticsearch version check failed") } i, err := strconv.Atoi(esVersionSplit[0]) diff --git a/plugins/inputs/example/example.go b/plugins/inputs/example/example.go index 996d426d3..ed2d09c80 100644 --- a/plugins/inputs/example/example.go +++ b/plugins/inputs/example/example.go @@ -4,6 +4,7 @@ package example import ( "crypto/rand" _ "embed" + "errors" "fmt" "math" "math/big" @@ -51,7 +52,7 @@ func (*Example) SampleConfig() string { func (m *Example) Init() error { // Check your options according to your requirements if m.DeviceName == "" { - return fmt.Errorf("device name cannot be empty") + return errors.New("device name cannot be empty") } // Set your defaults. @@ -85,7 +86,7 @@ func (m *Example) Init() error { func (m *Example) Gather(acc telegraf.Accumulator) error { // Imagine some completely arbitrary error occurring here if m.NumberFields > 10 { - return fmt.Errorf("too many fields") + return errors.New("too many fields") } // For illustration, we gather three metrics in one go @@ -95,7 +96,7 @@ func (m *Example) Gather(acc telegraf.Accumulator) error { // all later metrics. Simply accumulate errors in this case // and ignore the metric. if m.EnableRandomVariable && m.DeviceName == "flappy" && run > 1 { - acc.AddError(fmt.Errorf("too many runs for random values")) + acc.AddError(errors.New("too many runs for random values")) continue } diff --git a/plugins/inputs/exec/exec_test.go b/plugins/inputs/exec/exec_test.go index ac4a926cd..1d9499e34 100644 --- a/plugins/inputs/exec/exec_test.go +++ b/plugins/inputs/exec/exec_test.go @@ -7,7 +7,7 @@ package exec import ( "bytes" - "fmt" + "errors" "runtime" "testing" "time" @@ -133,7 +133,7 @@ func TestCommandError(t *testing.T) { require.NoError(t, parser.Init()) e := &Exec{ Log: testutil.Logger{}, - runner: newRunnerMock(nil, nil, fmt.Errorf("exit status code 1")), + runner: newRunnerMock(nil, nil, errors.New("exit status code 1")), Commands: []string{"badcommand"}, parser: parser, } diff --git a/plugins/inputs/fibaro/fibaro.go b/plugins/inputs/fibaro/fibaro.go index db0dd3798..4f5113f32 100644 --- a/plugins/inputs/fibaro/fibaro.go +++ b/plugins/inputs/fibaro/fibaro.go @@ -3,6 +3,7 @@ package fibaro import ( _ "embed" + "errors" "fmt" "io" "net/http" @@ -71,7 +72,7 @@ func (f *Fibaro) Init() error { f.DeviceType = "HC2" case "HC2", "HC3": default: - return fmt.Errorf("invalid option for device type") + return errors.New("invalid option for device type") } return nil diff --git a/plugins/inputs/fireboard/fireboard.go b/plugins/inputs/fireboard/fireboard.go index 3cb44e1c2..091e54c2b 100644 --- a/plugins/inputs/fireboard/fireboard.go +++ b/plugins/inputs/fireboard/fireboard.go @@ -4,6 +4,7 @@ package fireboard import ( _ "embed" "encoding/json" + "errors" "fmt" "net/http" "strconv" @@ -57,7 +58,7 @@ func (*Fireboard) SampleConfig() string { // Init the things func (r *Fireboard) Init() error { if len(r.AuthToken) == 0 { - return fmt.Errorf("you must specify an authToken") + return errors.New("you must specify an authToken") } if len(r.URL) == 0 { r.URL = "https://fireboard.io/api/v1/devices.json" diff --git a/plugins/inputs/fluentd/fluentd.go b/plugins/inputs/fluentd/fluentd.go index 143cebab8..2bdbc15c4 100644 --- a/plugins/inputs/fluentd/fluentd.go +++ b/plugins/inputs/fluentd/fluentd.go @@ -4,6 +4,7 @@ package fluentd import ( _ "embed" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -63,7 +64,7 @@ func parse(data []byte) (datapointArray []pluginData, err error) { var endpointData endpointInfo if err = json.Unmarshal(data, &endpointData); err != nil { - err = fmt.Errorf("processing JSON structure") + err = errors.New("processing JSON structure") return nil, err } @@ -110,13 +111,13 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error { } if resp.StatusCode != http.StatusOK { - return fmt.Errorf("http status ok not met") + return errors.New("http status ok not met") } dataPoints, err := parse(body) if err != nil { - return fmt.Errorf("problem with parsing") + return errors.New("problem with parsing") } // Go through all plugins one by one diff --git a/plugins/inputs/gnmi/gnmi.go b/plugins/inputs/gnmi/gnmi.go index f46530494..9894c1b0a 100644 --- a/plugins/inputs/gnmi/gnmi.go +++ b/plugins/inputs/gnmi/gnmi.go @@ -4,6 +4,7 @@ package gnmi import ( "context" _ "embed" + "errors" "fmt" "strings" "sync" @@ -98,7 +99,7 @@ func (*GNMI) SampleConfig() string { func (c *GNMI) Init() error { // Check options if time.Duration(c.Redial) <= 0 { - return fmt.Errorf("redial duration must be positive") + return errors.New("redial duration must be positive") } // Check vendor_specific options configured by user @@ -144,7 +145,7 @@ func (c *GNMI) Init() error { return err } if c.TagSubscriptions[idx].TagOnly != c.TagSubscriptions[0].TagOnly { - return fmt.Errorf("do not mix legacy tag_only subscriptions and tag subscriptions") + return errors.New("do not mix legacy tag_only subscriptions and tag subscriptions") } switch c.TagSubscriptions[idx].Match { case "": @@ -157,7 +158,7 @@ func (c *GNMI) Init() error { case "name": case "elements": if len(c.TagSubscriptions[idx].Elements) == 0 { - return fmt.Errorf("tag_subscription must have at least one element") + return errors.New("tag_subscription must have at least one element") } default: return fmt.Errorf("unknown match type %q for tag-subscription %q", c.TagSubscriptions[idx].Match, c.TagSubscriptions[idx].Name) diff --git a/plugins/inputs/gnmi/gnmi_test.go b/plugins/inputs/gnmi/gnmi_test.go index 9c027632b..40fd00d7f 100644 --- a/plugins/inputs/gnmi/gnmi_test.go +++ b/plugins/inputs/gnmi/gnmi_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "net" "os" "path/filepath" @@ -75,7 +74,7 @@ func TestWaitError(t *testing.T) { grpcServer := grpc.NewServer() gnmiServer := &MockServer{ SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error { - return fmt.Errorf("testerror") + return errors.New("testerror") }, GRPCServer: grpcServer, } diff --git a/plugins/inputs/google_cloud_storage/google_cloud_storage.go b/plugins/inputs/google_cloud_storage/google_cloud_storage.go index 11e30e58e..e1539fd76 100644 --- a/plugins/inputs/google_cloud_storage/google_cloud_storage.go +++ b/plugins/inputs/google_cloud_storage/google_cloud_storage.go @@ -238,7 +238,7 @@ func (gcs *GCS) setUpDefaultClient() error { func (gcs *GCS) setOffset() error { if gcs.client == nil { - return fmt.Errorf("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/haproxy/haproxy.go b/plugins/inputs/haproxy/haproxy.go index 6a9c06d47..6d9bfb34a 100644 --- a/plugins/inputs/haproxy/haproxy.go +++ b/plugins/inputs/haproxy/haproxy.go @@ -204,7 +204,7 @@ func (h *haproxy) importCsvResult(r io.Reader, acc telegraf.Accumulator, host st return err } if len(headers[0]) <= 2 || headers[0][:2] != "# " { - return fmt.Errorf("did not receive standard haproxy headers") + return errors.New("did not receive standard haproxy headers") } headers[0] = headers[0][2:] diff --git a/plugins/inputs/http/http.go b/plugins/inputs/http/http.go index 9916b2afe..58cc93881 100644 --- a/plugins/inputs/http/http.go +++ b/plugins/inputs/http/http.go @@ -5,6 +5,7 @@ package http import ( "context" _ "embed" + "errors" "fmt" "io" "net/http" @@ -54,14 +55,14 @@ func (*HTTP) SampleConfig() string { func (h *HTTP) Init() error { // For backward compatibility if h.TokenFile != "" && h.BearerToken != "" && h.TokenFile != h.BearerToken { - return fmt.Errorf("conflicting settings for 'bearer_token' and 'token_file'") + return errors.New("conflicting settings for 'bearer_token' and 'token_file'") } else if h.TokenFile == "" && h.BearerToken != "" { h.TokenFile = h.BearerToken } // We cannot use multiple sources for tokens if h.TokenFile != "" && !h.Token.Empty() { - return fmt.Errorf("either use 'token_file' or 'token' not both") + return errors.New("either use 'token_file' or 'token' not both") } // Create the client diff --git a/plugins/inputs/hugepages/hugepages.go b/plugins/inputs/hugepages/hugepages.go index fdb38106e..ea615d0f5 100644 --- a/plugins/inputs/hugepages/hugepages.go +++ b/plugins/inputs/hugepages/hugepages.go @@ -6,6 +6,7 @@ package hugepages import ( "bytes" _ "embed" + "errors" "fmt" "os" "path/filepath" @@ -258,7 +259,7 @@ func (h *Hugepages) parseHugepagesConfig() error { // empty array if len(h.Types) == 0 { - return fmt.Errorf("plugin was configured with nothing to read") + return errors.New("plugin was configured with nothing to read") } for _, hugepagesType := range h.Types { diff --git a/plugins/inputs/infiniband/infiniband_linux.go b/plugins/inputs/infiniband/infiniband_linux.go index 974a659cd..7f95e8be7 100644 --- a/plugins/inputs/infiniband/infiniband_linux.go +++ b/plugins/inputs/infiniband/infiniband_linux.go @@ -3,10 +3,11 @@ package infiniband import ( - "fmt" + "errors" "strconv" "github.com/Mellanox/rdmamap" + "github.com/influxdata/telegraf" ) @@ -15,7 +16,7 @@ func (i *Infiniband) Gather(acc telegraf.Accumulator) error { rdmaDevices := rdmamap.GetRdmaDeviceList() if len(rdmaDevices) == 0 { - return fmt.Errorf("no InfiniBand devices found in /sys/class/infiniband/") + return errors.New("no InfiniBand devices found in /sys/class/infiniband/") } for _, dev := range rdmaDevices { diff --git a/plugins/inputs/intel_baseband/intel_baseband.go b/plugins/inputs/intel_baseband/intel_baseband.go index 152238b0f..05bcc781c 100644 --- a/plugins/inputs/intel_baseband/intel_baseband.go +++ b/plugins/inputs/intel_baseband/intel_baseband.go @@ -63,12 +63,12 @@ func (b *Baseband) SampleConfig() string { // Init performs one time setup of the plugin func (b *Baseband) Init() error { if b.SocketAccessTimeout < 0 { - return fmt.Errorf("socket_access_timeout should be positive number or equal to 0 (to disable timeouts)") + return errors.New("socket_access_timeout should be positive number or equal to 0 (to disable timeouts)") } waitForTelemetryDuration := time.Duration(b.WaitForTelemetryTimeout) if waitForTelemetryDuration < 50*time.Millisecond { - return fmt.Errorf("wait_for_telemetry_timeout should be equal or larger than 50ms") + return errors.New("wait_for_telemetry_timeout should be equal or larger than 50ms") } // Filling default values diff --git a/plugins/inputs/intel_baseband/log_connector.go b/plugins/inputs/intel_baseband/log_connector.go index ca6b96796..f9379198b 100644 --- a/plugins/inputs/intel_baseband/log_connector.go +++ b/plugins/inputs/intel_baseband/log_connector.go @@ -144,13 +144,13 @@ func (lc *logConnector) readNumVFs() error { return nil } - return fmt.Errorf("numVFs data wasn't found in the log file") + return errors.New("numVFs data wasn't found in the log file") } // Find a line which contains a substring in the log file func (lc *logConnector) getSubstringLine(offsetLine int, substring string) (int, string, error) { if len(substring) == 0 { - return 0, "", fmt.Errorf("substring is empty") + return 0, "", errors.New("substring is empty") } for i := offsetLine; i < len(lc.lines); i++ { @@ -208,13 +208,13 @@ func (lc *logConnector) getMetric(offsetLine int, name string) (int, *logMetric, dataRaw := strings.TrimSpace(infoData[1]) if len(dataRaw) == 0 { - return offsetLine, nil, fmt.Errorf("the content of the log file is incorrect, metric's data is incorrect") + return offsetLine, nil, errors.New("the content of the log file is incorrect, metric's data is incorrect") } data := strings.Split(dataRaw, " ") for i := range data { if len(data[i]) == 0 { - return offsetLine, nil, fmt.Errorf("the content of the log file is incorrect, metric's data is empty") + return offsetLine, nil, errors.New("the content of the log file is incorrect, metric's data is empty") } } return i + 2, &logMetric{operationName: operationName, data: data}, nil @@ -224,18 +224,18 @@ func (lc *logConnector) getMetric(offsetLine int, name string) (int, *logMetric, func (lc *logConnector) parseNumVFs(s string) (int, error) { i := strings.LastIndex(s, deviceStatusStartPrefix) if i == -1 { - return 0, fmt.Errorf("couldn't find device status prefix in line") + return 0, errors.New("couldn't find device status prefix in line") } j := strings.Index(s[i:], deviceStatusEndPrefix) if j == -1 { - return 0, fmt.Errorf("couldn't find device end prefix in line") + return 0, errors.New("couldn't find device end prefix in line") } startIndex := i + len(deviceStatusStartPrefix) + 1 endIndex := i + j - 1 if len(s) < startIndex || startIndex >= endIndex { - return 0, fmt.Errorf("incorrect format of the line") + return 0, errors.New("incorrect format of the line") } return strconv.Atoi(s[startIndex:endIndex]) diff --git a/plugins/inputs/intel_baseband/sock_connector.go b/plugins/inputs/intel_baseband/sock_connector.go index dc98f3bba..1f4389329 100644 --- a/plugins/inputs/intel_baseband/sock_connector.go +++ b/plugins/inputs/intel_baseband/sock_connector.go @@ -3,6 +3,7 @@ package intel_baseband import ( + "errors" "fmt" "net" "time" @@ -50,7 +51,7 @@ func (sc *socketConnector) sendCommandToSocket(c byte) error { func (sc *socketConnector) writeCommandToSocket(c byte) error { if sc.connection == nil { - return fmt.Errorf("connection had not been established before") + return errors.New("connection had not been established before") } var err error if sc.accessTimeout == 0 { diff --git a/plugins/inputs/intel_baseband/sock_connector_test.go b/plugins/inputs/intel_baseband/sock_connector_test.go index 5965d4762..76b6eb2a6 100644 --- a/plugins/inputs/intel_baseband/sock_connector_test.go +++ b/plugins/inputs/intel_baseband/sock_connector_test.go @@ -3,7 +3,7 @@ package intel_baseband import ( - "fmt" + "errors" "testing" "time" @@ -36,7 +36,7 @@ func TestWriteCommandToSocket(t *testing.T) { t.Run("handling timeout setting error", func(t *testing.T) { conn := &mocks.Conn{} - conn.On("SetWriteDeadline", mock.Anything).Return(fmt.Errorf("deadline set error")) + conn.On("SetWriteDeadline", mock.Anything).Return(errors.New("deadline set error")) connector := socketConnector{connection: conn} err := connector.writeCommandToSocket(0x00) @@ -50,7 +50,7 @@ func TestWriteCommandToSocket(t *testing.T) { t.Run("handling net.Write error", func(t *testing.T) { var unsupportedCommand byte = 0x99 conn := &mocks.Conn{} - conn.On("Write", []byte{unsupportedCommand, 0x00}).Return(0, fmt.Errorf("unsupported command")) + conn.On("Write", []byte{unsupportedCommand, 0x00}).Return(0, errors.New("unsupported command")) conn.On("SetWriteDeadline", mock.Anything).Return(nil) connector := socketConnector{connection: conn} diff --git a/plugins/inputs/intel_baseband/utils.go b/plugins/inputs/intel_baseband/utils.go index 3d54eb25f..75b7d5c23 100644 --- a/plugins/inputs/intel_baseband/utils.go +++ b/plugins/inputs/intel_baseband/utils.go @@ -74,7 +74,7 @@ func logMetricDataToValue(data string) (int, error) { } if value < 0 { - return 0, fmt.Errorf("metric can't be negative") + return 0, errors.New("metric can't be negative") } return value, nil diff --git a/plugins/inputs/intel_baseband/utils_test.go b/plugins/inputs/intel_baseband/utils_test.go index 204f9a027..c22719b75 100644 --- a/plugins/inputs/intel_baseband/utils_test.go +++ b/plugins/inputs/intel_baseband/utils_test.go @@ -4,7 +4,6 @@ package intel_baseband import ( "errors" - "fmt" "testing" "github.com/stretchr/testify/require" @@ -164,8 +163,8 @@ func TestLogMetricDataToValue(t *testing.T) { {"00", 0, nil}, {"5", 5, nil}, {"-010", 0, errors.New("metric can't be negative")}, - {"", 0, fmt.Errorf("invalid syntax")}, - {"0Nax10", 0, fmt.Errorf("invalid syntax")}, + {"", 0, errors.New("invalid syntax")}, + {"0Nax10", 0, errors.New("invalid syntax")}, } t.Run("check correct returned values", func(t *testing.T) { diff --git a/plugins/inputs/intel_dlb/intel_dlb.go b/plugins/inputs/intel_dlb/intel_dlb.go index f9fa0687d..66fc5657c 100644 --- a/plugins/inputs/intel_dlb/intel_dlb.go +++ b/plugins/inputs/intel_dlb/intel_dlb.go @@ -7,6 +7,7 @@ package intel_dlb import ( _ "embed" "encoding/json" + "errors" "fmt" "net" "os" @@ -308,7 +309,7 @@ func (d *IntelDLB) setInitMessageLength() error { return d.closeSocketAndThrowError("custom", fmt.Errorf("failed to read InitMessage from socket: %w", err)) } if messageLength > len(buf) { - return d.closeSocketAndThrowError("custom", fmt.Errorf("socket reply length is bigger than default buffer length")) + return d.closeSocketAndThrowError("custom", errors.New("socket reply length is bigger than default buffer length")) } var initMsg initMessage @@ -339,7 +340,7 @@ func (d *IntelDLB) writeReadSocketMessage(messageToWrite string) (int, []byte, e } if replyMsgLen == 0 { - return 0, nil, d.closeSocketAndThrowError("message", fmt.Errorf("message length is empty")) + return 0, nil, d.closeSocketAndThrowError("message", errors.New("message length is empty")) } return replyMsgLen, socketReply, nil @@ -347,13 +348,13 @@ func (d *IntelDLB) writeReadSocketMessage(messageToWrite string) (int, []byte, e func (d *IntelDLB) parseJSON(replyMsgLen int, socketReply []byte, parsedDeviceInfo interface{}) error { if len(socketReply) == 0 { - return d.closeSocketAndThrowError("json", fmt.Errorf("socket reply is empty")) + return d.closeSocketAndThrowError("json", errors.New("socket reply is empty")) } if replyMsgLen > len(socketReply) { - return d.closeSocketAndThrowError("json", fmt.Errorf("socket reply length is bigger than it should be")) + return d.closeSocketAndThrowError("json", errors.New("socket reply length is bigger than it should be")) } if replyMsgLen == 0 { - return d.closeSocketAndThrowError("json", fmt.Errorf("socket reply message is empty")) + return d.closeSocketAndThrowError("json", errors.New("socket reply message is empty")) } // Assign reply to variable, e.g.: {"/eventdev/dev_list": [0, 1]} jsonDeviceIndexes := socketReply[:replyMsgLen] @@ -405,7 +406,7 @@ func (d *IntelDLB) closeSocketAndThrowError(errType string, err error) error { func (d *IntelDLB) checkAndAddDLBDevice() error { if d.rasReader == nil { - return fmt.Errorf("rasreader was not initialized") + return errors.New("rasreader was not initialized") } filePaths, err := d.rasReader.gatherPaths(dlbDeviceIDLocation) if err != nil { diff --git a/plugins/inputs/intel_dlb/intel_dlb_test.go b/plugins/inputs/intel_dlb/intel_dlb_test.go index 2873eb926..8177cc75f 100644 --- a/plugins/inputs/intel_dlb/intel_dlb_test.go +++ b/plugins/inputs/intel_dlb/intel_dlb_test.go @@ -5,6 +5,7 @@ package intel_dlb import ( "encoding/json" + "errors" "fmt" "net" "os" @@ -132,7 +133,7 @@ func TestDLB_Init(t *testing.T) { Log: testutil.Logger{}, } const emptyPath = "" - fileMock.On("gatherPaths", mock.Anything).Return([]string{emptyPath}, fmt.Errorf("can't find device folder")).Once() + fileMock.On("gatherPaths", mock.Anything).Return([]string{emptyPath}, errors.New("can't find device folder")).Once() err := dlb.Init() require.Error(t, err) require.Contains(t, err.Error(), "can't find device folder") @@ -147,7 +148,7 @@ func TestDLB_writeReadSocketMessage(t *testing.T) { connection: mockConn, Log: testutil.Logger{}, } - mockConn.On("Write", []byte{}).Return(0, fmt.Errorf("write error")).Once(). + mockConn.On("Write", []byte{}).Return(0, errors.New("write error")).Once(). On("Close").Return(nil).Once() _, _, err := dlb.writeReadSocketMessage("") @@ -163,7 +164,7 @@ func TestDLB_writeReadSocketMessage(t *testing.T) { connection: mockConn, Log: testutil.Logger{}, } - simulateResponse(mockConn, "", fmt.Errorf("read error")) + simulateResponse(mockConn, "", errors.New("read error")) _, _, err := dlb.writeReadSocketMessage("") @@ -584,7 +585,7 @@ func TestDLB_processCommandResult(t *testing.T) { mockConn.On("Read", mock.Anything).Run(func(arg mock.Arguments) { elem := arg.Get(0).([]byte) copy(elem, response) - }).Return(len(response), fmt.Errorf("read error")).Once() + }).Return(len(response), errors.New("read error")).Once() mockConn.On("Close").Return(nil) err := dlb.gatherMetricsFromSocket(mockAcc) @@ -652,7 +653,7 @@ func Test_checkAndAddDLBDevice(t *testing.T) { rasReader: fileMock, Log: testutil.Logger{}, } - fileMock.On("gatherPaths", mock.AnythingOfType("string")).Return(nil, fmt.Errorf("can't find device folder")).Once() + fileMock.On("gatherPaths", mock.AnythingOfType("string")).Return(nil, errors.New("can't find device folder")).Once() err := dlb.checkAndAddDLBDevice() @@ -670,7 +671,7 @@ func Test_checkAndAddDLBDevice(t *testing.T) { } const globPath = "/sys/devices/pci0000:00/0000:00:00.0/device" fileMock.On("gatherPaths", mock.Anything).Return([]string{globPath}, nil).Once(). - On("readFromFile", mock.Anything).Return([]byte("0x2710"), fmt.Errorf("read error while getting device folders")).Once() + On("readFromFile", mock.Anything).Return([]byte("0x2710"), errors.New("read error while getting device folders")).Once() err := dlb.checkAndAddDLBDevice() @@ -701,7 +702,7 @@ func Test_checkAndAddDLBDevice(t *testing.T) { } const globPath = "/sys/devices/pci0000:00/0000:00:00.0/device" fileMock.On("gatherPaths", mock.Anything).Return([]string{globPath}, nil).Once(). - On("readFromFile", mock.Anything).Return([]byte("0x2710"), fmt.Errorf("read error while getting device folders")).Once() + On("readFromFile", mock.Anything).Return([]byte("0x2710"), errors.New("read error while getting device folders")).Once() err := dlb.checkAndAddDLBDevice() @@ -778,7 +779,7 @@ func Test_readRasMetrics(t *testing.T) { err error errMsg string }{ - {"error when reading fails", []byte(aerCorrectableData), fmt.Errorf("read error"), "read error"}, + {"error when reading fails", []byte(aerCorrectableData), errors.New("read error"), "read error"}, {"error when empty data is given", []byte(""), nil, "no value to parse"}, {"error when trying to split empty data", []byte("x1 x2"), nil, "failed to parse value"}, } diff --git a/plugins/inputs/intel_pmt/intel_pmt.go b/plugins/inputs/intel_pmt/intel_pmt.go index d569139ca..2b05823b4 100644 --- a/plugins/inputs/intel_pmt/intel_pmt.go +++ b/plugins/inputs/intel_pmt/intel_pmt.go @@ -384,7 +384,7 @@ func eval(eq string, params map[string]interface{}) (interface{}, error) { // gval doesn't support hexadecimals eq = hexToDecRegex.ReplaceAllStringFunc(eq, hexToDec) if eq == "" { - return nil, fmt.Errorf("error during hex to decimal conversion") + return nil, errors.New("error during hex to decimal conversion") } result, err := gval.Evaluate(eq, params) if err != nil { diff --git a/plugins/inputs/intel_pmu/activators.go b/plugins/inputs/intel_pmu/activators.go index 735ed7f41..8d02a88b3 100644 --- a/plugins/inputs/intel_pmu/activators.go +++ b/plugins/inputs/intel_pmu/activators.go @@ -88,10 +88,10 @@ func (ea *iaEntitiesActivator) activateEntities(coreEntities []*CoreEventEntity, func (ea *iaEntitiesActivator) activateCoreEvents(entity *CoreEventEntity) error { if entity == nil { - return fmt.Errorf("core events entity is nil") + return errors.New("core events entity is nil") } if ea.placementMaker == nil { - return fmt.Errorf("placement maker is nil") + return errors.New("placement maker is nil") } if entity.PerfGroup { err := ea.activateCoreEventsGroup(entity) @@ -101,7 +101,7 @@ func (ea *iaEntitiesActivator) activateCoreEvents(entity *CoreEventEntity) error } else { for _, event := range entity.parsedEvents { if event == nil { - return fmt.Errorf("core parsed event is nil") + return errors.New("core parsed event is nil") } placements, err := ea.placementMaker.makeCorePlacements(entity.parsedCores, event.custom.Event) if err != nil { @@ -119,14 +119,14 @@ func (ea *iaEntitiesActivator) activateCoreEvents(entity *CoreEventEntity) error func (ea *iaEntitiesActivator) activateUncoreEvents(entity *UncoreEventEntity) error { if entity == nil { - return fmt.Errorf("uncore events entity is nil") + return errors.New("uncore events entity is nil") } if ea.perfActivator == nil || ea.placementMaker == nil { - return fmt.Errorf("events activator or placement maker is nil") + return errors.New("events activator or placement maker is nil") } for _, event := range entity.parsedEvents { if event == nil { - return fmt.Errorf("uncore parsed event is nil") + return errors.New("uncore parsed event is nil") } perfEvent := event.custom.Event if perfEvent == nil { @@ -152,16 +152,16 @@ func (ea *iaEntitiesActivator) activateUncoreEvents(entity *UncoreEventEntity) e func (ea *iaEntitiesActivator) activateCoreEventsGroup(entity *CoreEventEntity) error { if ea.perfActivator == nil || ea.placementMaker == nil { - return fmt.Errorf("missing perf activator or placement maker") + return errors.New("missing perf activator or placement maker") } if entity == nil || len(entity.parsedEvents) < 1 { - return fmt.Errorf("missing parsed events") + return errors.New("missing parsed events") } events := make([]ia.CustomizableEvent, 0, len(entity.parsedEvents)) for _, event := range entity.parsedEvents { if event == nil { - return fmt.Errorf("core event is nil") + return errors.New("core event is nil") } events = append(events, event.custom) } @@ -184,10 +184,10 @@ func (ea *iaEntitiesActivator) activateCoreEventsGroup(entity *CoreEventEntity) func (ea *iaEntitiesActivator) activateEventForPlacements(event *eventWithQuals, placements []ia.PlacementProvider) ([]*ia.ActiveEvent, error) { if event == nil { - return nil, fmt.Errorf("core event is nil") + return nil, errors.New("core event is nil") } if ea.perfActivator == nil { - return nil, fmt.Errorf("missing perf activator") + return nil, errors.New("missing perf activator") } activeEvents := make([]*ia.ActiveEvent, 0, len(placements)) diff --git a/plugins/inputs/intel_pmu/activators_test.go b/plugins/inputs/intel_pmu/activators_test.go index d9da88f05..fee5d556c 100644 --- a/plugins/inputs/intel_pmu/activators_test.go +++ b/plugins/inputs/intel_pmu/activators_test.go @@ -58,7 +58,7 @@ func TestActivateEntities(t *testing.T) { func TestActivateUncoreEvents(t *testing.T) { mActivator := &mockEventsActivator{} mMaker := &mockPlacementMaker{} - errMock := fmt.Errorf("error mock") + errMock := errors.New("error mock") t.Run("entity is nil", func(t *testing.T) { mEntitiesActivator := &iaEntitiesActivator{placementMaker: mMaker, perfActivator: mActivator} @@ -155,7 +155,7 @@ func TestActivateUncoreEvents(t *testing.T) { func TestActivateCoreEvents(t *testing.T) { mMaker := &mockPlacementMaker{} mActivator := &mockEventsActivator{} - errMock := fmt.Errorf("error mock") + errMock := errors.New("error mock") t.Run("entity is nil", func(t *testing.T) { mEntitiesActivator := &iaEntitiesActivator{placementMaker: mMaker, perfActivator: mActivator} diff --git a/plugins/inputs/intel_pmu/config.go b/plugins/inputs/intel_pmu/config.go index 99ff73a83..58cf42455 100644 --- a/plugins/inputs/intel_pmu/config.go +++ b/plugins/inputs/intel_pmu/config.go @@ -3,6 +3,7 @@ package intel_pmu import ( + "errors" "fmt" "strconv" "strings" @@ -24,12 +25,12 @@ type configParser struct { func (cp *configParser) parseEntities(coreEntities []*CoreEventEntity, uncoreEntities []*UncoreEventEntity) (err error) { if len(coreEntities) == 0 && len(uncoreEntities) == 0 { - return fmt.Errorf("neither core nor uncore entities configured") + return errors.New("neither core nor uncore entities configured") } for _, coreEntity := range coreEntities { if coreEntity == nil { - return fmt.Errorf("core entity is nil") + return errors.New("core entity is nil") } if coreEntity.Events == nil { if cp.log != nil { @@ -39,7 +40,7 @@ func (cp *configParser) parseEntities(coreEntities []*CoreEventEntity, uncoreEnt } else { events := cp.parseEvents(coreEntity.Events) if events == nil { - return fmt.Errorf("an empty list of core events was provided") + return errors.New("an empty list of core events was provided") } coreEntity.parsedEvents = events } @@ -52,7 +53,7 @@ func (cp *configParser) parseEntities(coreEntities []*CoreEventEntity, uncoreEnt for _, uncoreEntity := range uncoreEntities { if uncoreEntity == nil { - return fmt.Errorf("uncore entity is nil") + return errors.New("uncore entity is nil") } if uncoreEntity.Events == nil { if cp.log != nil { @@ -62,7 +63,7 @@ func (cp *configParser) parseEntities(coreEntities []*CoreEventEntity, uncoreEnt } else { events := cp.parseEvents(uncoreEntity.Events) if events == nil { - return fmt.Errorf("an empty list of uncore events was provided") + return errors.New("an empty list of uncore events was provided") } uncoreEntity.parsedEvents = events } @@ -95,7 +96,7 @@ func (cp *configParser) parseCores(cores []string) ([]int, error) { cp.log.Debug("all possible cores will be configured") } if cp.sys == nil { - return nil, fmt.Errorf("system info provider is nil") + return nil, errors.New("system info provider is nil") } cores, err := cp.sys.allCPUs() if err != nil { @@ -104,7 +105,7 @@ func (cp *configParser) parseCores(cores []string) ([]int, error) { return cores, nil } if len(cores) == 0 { - return nil, fmt.Errorf("an empty list of cores was provided") + return nil, errors.New("an empty list of cores was provided") } result, err := cp.parseIntRanges(cores) @@ -120,7 +121,7 @@ func (cp *configParser) parseSockets(sockets []string) ([]int, error) { cp.log.Debug("all possible sockets will be configured") } if cp.sys == nil { - return nil, fmt.Errorf("system info provider is nil") + return nil, errors.New("system info provider is nil") } sockets, err := cp.sys.allSockets() if err != nil { @@ -129,7 +130,7 @@ func (cp *configParser) parseSockets(sockets []string) ([]int, error) { return sockets, nil } if len(sockets) == 0 { - return nil, fmt.Errorf("an empty list of sockets was provided") + return nil, errors.New("an empty list of sockets was provided") } result, err := cp.parseIntRanges(sockets) diff --git a/plugins/inputs/intel_pmu/intel_pmu.go b/plugins/inputs/intel_pmu/intel_pmu.go index 16170b095..0467092c7 100644 --- a/plugins/inputs/intel_pmu/intel_pmu.go +++ b/plugins/inputs/intel_pmu/intel_pmu.go @@ -148,7 +148,7 @@ func (i *IntelPMU) Init() error { func (i *IntelPMU) initialization(parser entitiesParser, resolver entitiesResolver, activator entitiesActivator) error { if parser == nil || resolver == nil || activator == nil { - return fmt.Errorf("entities parser and/or resolver and/or activator is nil") + return errors.New("entities parser and/or resolver and/or activator is nil") } err := parser.parseEntities(i.CoreEntities, i.UncoreEntities) @@ -183,7 +183,7 @@ func (i *IntelPMU) checkFileDescriptors() error { return fmt.Errorf("failed to estimate number of uncore events file descriptors: %w", err) } if coreFd > math.MaxUint64-uncoreFd { - return fmt.Errorf("requested number of file descriptors exceeds uint64") + return errors.New("requested number of file descriptors exceeds uint64") } allFd := coreFd + uncoreFd @@ -210,7 +210,7 @@ func (i *IntelPMU) checkFileDescriptors() error { func (i *IntelPMU) Gather(acc telegraf.Accumulator) error { if i.entitiesReader == nil { - return fmt.Errorf("entities reader is nil") + return errors.New("entities reader is nil") } coreMetrics, uncoreMetrics, err := i.entitiesReader.readEntities(i.CoreEntities, i.UncoreEntities) if err != nil { @@ -342,7 +342,7 @@ func multiplyAndAdd(factorA uint64, factorB uint64, sum uint64) (uint64, error) func readMaxFD(reader fileInfoProvider) (uint64, error) { if reader == nil { - return 0, fmt.Errorf("file reader is nil") + return 0, errors.New("file reader is nil") } buf, err := reader.readFile(fileMaxPath) if err != nil { @@ -358,10 +358,10 @@ func readMaxFD(reader fileInfoProvider) (uint64, error) { func checkFiles(paths []string, fileInfo fileInfoProvider) error { // No event definition JSON locations present if len(paths) == 0 { - return fmt.Errorf("no paths were given") + return errors.New("no paths were given") } if fileInfo == nil { - return fmt.Errorf("file info provider is nil") + return errors.New("file info provider is nil") } // Wrong files for _, path := range paths { diff --git a/plugins/inputs/intel_pmu/intel_pmu_test.go b/plugins/inputs/intel_pmu/intel_pmu_test.go index 53f588c69..08bb23df2 100644 --- a/plugins/inputs/intel_pmu/intel_pmu_test.go +++ b/plugins/inputs/intel_pmu/intel_pmu_test.go @@ -10,9 +10,10 @@ import ( "testing" "time" - "github.com/influxdata/telegraf/testutil" ia "github.com/intel/iaevents" "github.com/stretchr/testify/require" + + "github.com/influxdata/telegraf/testutil" ) func TestInitialization(t *testing.T) { @@ -135,7 +136,7 @@ func TestGather(t *testing.T) { }) t.Run("error while reading entities", func(t *testing.T) { - errMock := fmt.Errorf("houston we have a problem") + errMock := errors.New("houston we have a problem") mEntitiesValuesReader.On("readEntities", mIntelPMU.CoreEntities, mIntelPMU.UncoreEntities). Return(nil, nil, errMock).Once() @@ -440,7 +441,7 @@ func TestReadMaxFD(t *testing.T) { maxFD uint64 failMsg string }{ - {"read file error", fmt.Errorf("mock error"), nil, 0, openErrorMsg}, + {"read file error", errors.New("mock error"), nil, 0, openErrorMsg}, {"file content parse error", nil, []byte("wrong format"), 0, parseErrorMsg}, {"negative value reading", nil, []byte("-10000"), 0, parseErrorMsg}, {"max uint exceeded", nil, []byte("18446744073709551616"), 0, parseErrorMsg}, diff --git a/plugins/inputs/intel_pmu/reader.go b/plugins/inputs/intel_pmu/reader.go index 9b13618b5..d34083e3c 100644 --- a/plugins/inputs/intel_pmu/reader.go +++ b/plugins/inputs/intel_pmu/reader.go @@ -3,6 +3,7 @@ package intel_pmu import ( + "errors" "fmt" "time" @@ -88,10 +89,10 @@ func (ie *iaEntitiesValuesReader) readEntities(coreEntities []*CoreEventEntity, func (ie *iaEntitiesValuesReader) readCoreEvents(entity *CoreEventEntity) ([]coreMetric, error) { if ie.eventReader == nil || ie.timer == nil { - return nil, fmt.Errorf("event values reader or timer is nil") + return nil, errors.New("event values reader or timer is nil") } if entity == nil { - return nil, fmt.Errorf("entity is nil") + return nil, errors.New("entity is nil") } metrics := make([]coreMetric, len(entity.activeEvents)) errGroup := errgroup.Group{} @@ -101,7 +102,7 @@ func (ie *iaEntitiesValuesReader) readCoreEvents(entity *CoreEventEntity) ([]cor actualEvent := event if event == nil || event.PerfEvent == nil { - return nil, fmt.Errorf("active event or corresponding perf event is nil") + return nil, errors.New("active event or corresponding perf event is nil") } errGroup.Go(func() error { @@ -130,7 +131,7 @@ func (ie *iaEntitiesValuesReader) readCoreEvents(entity *CoreEventEntity) ([]cor func (ie *iaEntitiesValuesReader) readUncoreEvents(entity *UncoreEventEntity) ([]uncoreMetric, error) { if entity == nil { - return nil, fmt.Errorf("entity is nil") + return nil, errors.New("entity is nil") } var uncoreMetrics []uncoreMetric @@ -158,10 +159,10 @@ func (ie *iaEntitiesValuesReader) readUncoreEvents(entity *UncoreEventEntity) ([ func (ie *iaEntitiesValuesReader) readMultiEventSeparately(multiEvent multiEvent) ([]uncoreMetric, error) { if ie.eventReader == nil || ie.timer == nil { - return nil, fmt.Errorf("event values reader or timer is nil") + return nil, errors.New("event values reader or timer is nil") } if len(multiEvent.activeEvents) < 1 || multiEvent.perfEvent == nil { - return nil, fmt.Errorf("no active events or perf event is nil") + return nil, errors.New("no active events or perf event is nil") } activeEvents := multiEvent.activeEvents perfEvent := multiEvent.perfEvent @@ -199,10 +200,10 @@ func (ie *iaEntitiesValuesReader) readMultiEventSeparately(multiEvent multiEvent func (ie *iaEntitiesValuesReader) readMultiEventAgg(multiEvent multiEvent) (uncoreMetric, error) { if ie.eventReader == nil || ie.timer == nil { - return uncoreMetric{}, fmt.Errorf("event values reader or timer is nil") + return uncoreMetric{}, errors.New("event values reader or timer is nil") } if len(multiEvent.activeEvents) < 1 || multiEvent.perfEvent == nil { - return uncoreMetric{}, fmt.Errorf("no active events or perf event is nil") + return uncoreMetric{}, errors.New("no active events or perf event is nil") } activeEvents := multiEvent.activeEvents perfEvent := multiEvent.perfEvent diff --git a/plugins/inputs/intel_pmu/reader_test.go b/plugins/inputs/intel_pmu/reader_test.go index 3c0b0579e..ba55f136f 100644 --- a/plugins/inputs/intel_pmu/reader_test.go +++ b/plugins/inputs/intel_pmu/reader_test.go @@ -3,6 +3,7 @@ package intel_pmu import ( + "errors" "fmt" "math" "testing" @@ -61,7 +62,7 @@ func TestReadCoreEvents(t *testing.T) { }) t.Run("reading failed", func(t *testing.T) { - errMock := fmt.Errorf("mock error") + errMock := errors.New("mock error") event := &ia.ActiveEvent{PerfEvent: &ia.PerfEvent{Name: "event1"}} entity := &CoreEventEntity{} @@ -138,7 +139,7 @@ func TestReadMultiEventSeparately(t *testing.T) { }) t.Run("reading failed", func(t *testing.T) { - errMock := fmt.Errorf("mock error") + errMock := errors.New("mock error") perfEvent := &ia.PerfEvent{Name: "event"} event := &ia.ActiveEvent{PerfEvent: perfEvent} @@ -190,7 +191,7 @@ func TestReadMultiEventAgg(t *testing.T) { mReader := &mockValuesReader{} mTimer := &moonClock{} mEntitiesReader := &iaEntitiesValuesReader{mReader, mTimer} - errMock := fmt.Errorf("mock error") + errMock := errors.New("mock error") t.Run("event reader is nil", func(t *testing.T) { event := multiEvent{} @@ -294,7 +295,7 @@ func TestReadMultiEventAgg(t *testing.T) { } func TestReadUncoreEvents(t *testing.T) { - errMock := fmt.Errorf("mock error") + errMock := errors.New("mock error") t.Run("entity is nil", func(t *testing.T) { metrics, err := (&iaEntitiesValuesReader{}).readUncoreEvents(nil) diff --git a/plugins/inputs/intel_pmu/resolver.go b/plugins/inputs/intel_pmu/resolver.go index 953fc7b4b..b24219c2d 100644 --- a/plugins/inputs/intel_pmu/resolver.go +++ b/plugins/inputs/intel_pmu/resolver.go @@ -7,8 +7,9 @@ import ( "fmt" "strings" - "github.com/influxdata/telegraf" ia "github.com/intel/iaevents" + + "github.com/influxdata/telegraf" ) type entitiesResolver interface { @@ -24,7 +25,7 @@ type iaEntitiesResolver struct { func (e *iaEntitiesResolver) resolveEntities(coreEntities []*CoreEventEntity, uncoreEntities []*UncoreEventEntity) error { for _, entity := range coreEntities { if entity == nil { - return fmt.Errorf("core entity is nil") + return errors.New("core entity is nil") } if entity.allEvents { newEvents, _, err := e.resolveAllEvents() @@ -36,7 +37,7 @@ func (e *iaEntitiesResolver) resolveEntities(coreEntities []*CoreEventEntity, un } for _, event := range entity.parsedEvents { if event == nil { - return fmt.Errorf("parsed core event is nil") + return errors.New("parsed core event is nil") } customEvent, err := e.resolveEvent(event.name, event.qualifiers) if err != nil { @@ -50,7 +51,7 @@ func (e *iaEntitiesResolver) resolveEntities(coreEntities []*CoreEventEntity, un } for _, entity := range uncoreEntities { if entity == nil { - return fmt.Errorf("uncore entity is nil") + return errors.New("uncore entity is nil") } if entity.allEvents { _, newEvents, err := e.resolveAllEvents() @@ -62,7 +63,7 @@ func (e *iaEntitiesResolver) resolveEntities(coreEntities []*CoreEventEntity, un } for _, event := range entity.parsedEvents { if event == nil { - return fmt.Errorf("parsed uncore event is nil") + return errors.New("parsed uncore event is nil") } customEvent, err := e.resolveEvent(event.name, event.qualifiers) if err != nil { diff --git a/plugins/inputs/intel_rdt/intel_rdt.go b/plugins/inputs/intel_rdt/intel_rdt.go index 1b927d96b..33f9d1761 100644 --- a/plugins/inputs/intel_rdt/intel_rdt.go +++ b/plugins/inputs/intel_rdt/intel_rdt.go @@ -115,10 +115,10 @@ func (r *IntelRDT) Initialize() error { return err } if len(r.Cores) != 0 && len(r.Processes) != 0 { - return fmt.Errorf("monitoring start error, process and core tracking can not be done simultaneously") + return errors.New("monitoring start error, process and core tracking can not be done simultaneously") } if len(r.Cores) == 0 && len(r.Processes) == 0 { - return fmt.Errorf("monitoring start error, at least one of cores or processes must be provided in config") + return errors.New("monitoring start error, at least one of cores or processes must be provided in config") } if r.SamplingInterval == 0 { r.SamplingInterval = defaultSamplingInterval @@ -206,7 +206,7 @@ func (r *IntelRDT) associateProcessesWithPIDs(providedProcesses []string) (map[s availableProcesses, err := r.Processor.getAllProcesses() if err != nil { - return nil, fmt.Errorf("cannot gather information of all available processes") + return nil, errors.New("cannot gather information of all available processes") } for _, availableProcess := range availableProcesses { if choice.Contains(availableProcess.Name, providedProcesses) { @@ -388,14 +388,14 @@ func createArgsForGroups(coresOrPIDs []string) string { func validatePqosPath(pqosPath string) error { if len(pqosPath) == 0 { - return fmt.Errorf("monitoring start error, can not find pqos executable") + return errors.New("monitoring start error, can not find pqos executable") } pathInfo, err := os.Stat(pqosPath) if os.IsNotExist(err) { - return fmt.Errorf("monitoring start error, provided pqos path not exist") + return errors.New("monitoring start error, provided pqos path not exist") } if mode := pathInfo.Mode(); !mode.IsRegular() { - return fmt.Errorf("monitoring start error, provided pqos path does not point to a regular file") + return errors.New("monitoring start error, provided pqos path does not point to a regular file") } return nil } @@ -431,7 +431,7 @@ func validateAndParseCores(coreStr string) ([]int, error) { rangeValues := strings.Split(coreStr, "-") if len(rangeValues) != 2 { - return nil, fmt.Errorf("more than two values in range") + return nil, errors.New("more than two values in range") } startValue, err := strconv.Atoi(rangeValues[0]) @@ -444,7 +444,7 @@ func validateAndParseCores(coreStr string) ([]int, error) { } if startValue > stopValue { - return nil, fmt.Errorf("first value cannot be higher than second") + return nil, errors.New("first value cannot be higher than second") } rangeOfCores := makeRange(startValue, stopValue) @@ -464,7 +464,7 @@ func findPIDsInMeasurement(measurements string) (string, error) { var insideQuoteRegex = regexp.MustCompile(`"(.*?)"`) pidsMatch := insideQuoteRegex.FindStringSubmatch(measurements) if len(pidsMatch) < 2 { - return "", fmt.Errorf("cannot find PIDs in measurement line") + return "", errors.New("cannot find PIDs in measurement line") } pids := pidsMatch[1] return pids, nil @@ -489,7 +489,7 @@ func splitCSVLineIntoValues(line string) (splitCSVLine, error) { func validateInterval(interval int32) error { if interval < 0 { - return fmt.Errorf("interval cannot be lower than 0") + return errors.New("interval cannot be lower than 0") } return nil } diff --git a/plugins/inputs/internet_speed/internet_speed.go b/plugins/inputs/internet_speed/internet_speed.go index a28c04b0a..ccd992b17 100644 --- a/plugins/inputs/internet_speed/internet_speed.go +++ b/plugins/inputs/internet_speed/internet_speed.go @@ -4,6 +4,7 @@ package internet_speed import ( "context" _ "embed" + "errors" "fmt" "math" "os" @@ -142,7 +143,7 @@ func (is *InternetSpeed) findClosestServer() error { } if len(is.servers) < 1 { - return fmt.Errorf("no servers found") + return errors.New("no servers found") } // Return the first match or the server with the lowest latency @@ -168,7 +169,7 @@ func (is *InternetSpeed) findClosestServer() error { return nil } - return fmt.Errorf("no server set: filter excluded all servers or no available server found") + return errors.New("no server set: filter excluded all servers or no available server found") } func init() { diff --git a/plugins/inputs/ipmi_sensor/ipmi_sensor.go b/plugins/inputs/ipmi_sensor/ipmi_sensor.go index f90398e04..025740050 100644 --- a/plugins/inputs/ipmi_sensor/ipmi_sensor.go +++ b/plugins/inputs/ipmi_sensor/ipmi_sensor.go @@ -5,6 +5,7 @@ import ( "bufio" "bytes" _ "embed" + "errors" "fmt" "os" "os/exec" @@ -77,7 +78,7 @@ func (m *Ipmi) Init() error { // Gather is the main execution function for the plugin func (m *Ipmi) Gather(acc telegraf.Accumulator) error { if len(m.Path) == 0 { - return fmt.Errorf("ipmitool not found: verify that ipmitool is installed and that ipmitool is in your PATH") + return errors.New("ipmitool not found: verify that ipmitool is installed and that ipmitool is in your PATH") } if len(m.Servers) > 0 { diff --git a/plugins/inputs/ipset/ipset_test.go b/plugins/inputs/ipset/ipset_test.go index 117fcc3ea..77a3b76ea 100644 --- a/plugins/inputs/ipset/ipset_test.go +++ b/plugins/inputs/ipset/ipset_test.go @@ -3,7 +3,6 @@ package ipset import ( "bytes" "errors" - "fmt" "reflect" "testing" @@ -40,7 +39,7 @@ func TestIpset(t *testing.T) { value: `create hash:net family inet hashsize 1024 maxelem 65536 counters add myset 4.5.6.7 packets 123 bytes `, - err: fmt.Errorf("error parsing line (expected at least 7 fields): \t\t\t\tadd myset 4.5.6.7 packets 123 bytes"), + err: errors.New("error parsing line (expected at least 7 fields): \t\t\t\tadd myset 4.5.6.7 packets 123 bytes"), }, { name: "Non-empty sets, counters, no comment", diff --git a/plugins/inputs/jenkins/jenkins.go b/plugins/inputs/jenkins/jenkins.go index 7c2326d79..dfaa7f43f 100644 --- a/plugins/inputs/jenkins/jenkins.go +++ b/plugins/inputs/jenkins/jenkins.go @@ -4,6 +4,7 @@ package jenkins import ( "context" _ "embed" + "errors" "fmt" "net/http" "net/url" @@ -147,7 +148,7 @@ func (j *Jenkins) initialize(client *http.Client) error { func (j *Jenkins) gatherNodeData(n node, acc telegraf.Accumulator) error { tags := map[string]string{} if n.DisplayName == "" { - return fmt.Errorf("error empty node name") + return errors.New("error empty node name") } tags["node_name"] = n.DisplayName diff --git a/plugins/inputs/jolokia/jolokia.go b/plugins/inputs/jolokia/jolokia.go index 58fc42934..06d8fd3ed 100644 --- a/plugins/inputs/jolokia/jolokia.go +++ b/plugins/inputs/jolokia/jolokia.go @@ -5,6 +5,7 @@ import ( "bytes" _ "embed" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -235,14 +236,14 @@ func (j *Jolokia) Gather(acc telegraf.Accumulator) error { server.Host, server.Port, metrics[i].Mbean, metrics[i].Attribute, status)) continue } else if !ok { - acc.AddError(fmt.Errorf("missing status in response body")) + acc.AddError(errors.New("missing status in response body")) continue } if values, ok := resp["value"]; ok { j.extractValues(metrics[i].Name, values, fields) } else { - acc.AddError(fmt.Errorf("missing key 'value' in output response")) + acc.AddError(errors.New("missing key 'value' in output response")) } } diff --git a/plugins/inputs/jolokia/jolokia_test.go b/plugins/inputs/jolokia/jolokia_test.go index 6c4e76a5f..1b4280fb9 100644 --- a/plugins/inputs/jolokia/jolokia_test.go +++ b/plugins/inputs/jolokia/jolokia_test.go @@ -1,7 +1,6 @@ package jolokia import ( - _ "fmt" "io" "net/http" "strings" diff --git a/plugins/inputs/jti_openconfig_telemetry/jti_openconfig_telemetry.go b/plugins/inputs/jti_openconfig_telemetry/jti_openconfig_telemetry.go index 9abf1f199..10eecceba 100644 --- a/plugins/inputs/jti_openconfig_telemetry/jti_openconfig_telemetry.go +++ b/plugins/inputs/jti_openconfig_telemetry/jti_openconfig_telemetry.go @@ -4,6 +4,7 @@ package jti_openconfig_telemetry import ( "context" _ "embed" + "errors" "fmt" "net" "regexp" @@ -368,7 +369,7 @@ func (m *OpenConfigTelemetry) authenticate(ctx context.Context, server string, g func (m *OpenConfigTelemetry) Start(acc telegraf.Accumulator) error { // Build sensors config if m.splitSensorConfig() == 0 { - return fmt.Errorf("no valid sensor configuration available") + return errors.New("no valid sensor configuration available") } // Parse TLS config diff --git a/plugins/inputs/kinesis_consumer/kinesis_consumer.go b/plugins/inputs/kinesis_consumer/kinesis_consumer.go index 1846aaf3b..73486f739 100644 --- a/plugins/inputs/kinesis_consumer/kinesis_consumer.go +++ b/plugins/inputs/kinesis_consumer/kinesis_consumer.go @@ -7,6 +7,7 @@ import ( "compress/zlib" "context" _ "embed" + "errors" "fmt" "io" "math/big" @@ -261,7 +262,7 @@ func (k *KinesisConsumer) GetCheckpoint(streamName, shardID string) (string, err // Set wraps the checkpoint's SetCheckpoint function (called by consumer library) func (k *KinesisConsumer) SetCheckpoint(streamName, shardID, sequenceNumber string) error { if sequenceNumber == "" { - return fmt.Errorf("sequence number should not be empty") + return errors.New("sequence number should not be empty") } k.checkpointTex.Lock() diff --git a/plugins/inputs/leofs/leofs.go b/plugins/inputs/leofs/leofs.go index d2a41e910..116ef2f30 100644 --- a/plugins/inputs/leofs/leofs.go +++ b/plugins/inputs/leofs/leofs.go @@ -4,6 +4,7 @@ package leofs import ( "bufio" _ "embed" + "errors" "fmt" "os/exec" "strconv" @@ -206,7 +207,7 @@ func (l *LeoFS) gatherServer( defer internal.WaitTimeout(cmd, time.Second*5) //nolint:errcheck // ignore the returned error as we cannot do anything about it anyway scanner := bufio.NewScanner(stdout) if !scanner.Scan() { - return fmt.Errorf("unable to retrieve the node name") + return errors.New("unable to retrieve the node name") } nodeName, err := retrieveTokenAfterColon(scanner.Text()) if err != nil { diff --git a/plugins/inputs/libvirt/libvirt.go b/plugins/inputs/libvirt/libvirt.go index 181d052e8..e5a4b663b 100644 --- a/plugins/inputs/libvirt/libvirt.go +++ b/plugins/inputs/libvirt/libvirt.go @@ -3,13 +3,13 @@ package libvirt import ( _ "embed" + "errors" "fmt" "sync" - "golang.org/x/sync/errgroup" - golibvirt "github.com/digitalocean/go-libvirt" libvirtutils "github.com/thomasklein94/packer-plugin-libvirt/libvirt-utils" + "golang.org/x/sync/errgroup" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/inputs" @@ -84,7 +84,7 @@ func (l *Libvirt) Init() error { } if !l.isThereAnythingToGather() { - return fmt.Errorf("all configuration options are empty or invalid. Did not find anything to gather") + return errors.New("all configuration options are empty or invalid. Did not find anything to gather") } return nil diff --git a/plugins/inputs/libvirt/libvirt_test.go b/plugins/inputs/libvirt/libvirt_test.go index eb137a031..f13808fec 100644 --- a/plugins/inputs/libvirt/libvirt_test.go +++ b/plugins/inputs/libvirt/libvirt_test.go @@ -1,7 +1,7 @@ package libvirt import ( - "fmt" + "errors" "testing" "time" @@ -68,7 +68,7 @@ func TestLibvirt_Gather(t *testing.T) { Log: testutil.Logger{}, utils: &mockLibvirtUtils, } - mockLibvirtUtils.On("EnsureConnected", mock.Anything).Return(fmt.Errorf("failed to connect")).Once() + mockLibvirtUtils.On("EnsureConnected", mock.Anything).Return(errors.New("failed to connect")).Once() err := l.Gather(&acc) require.Error(t, err) require.Contains(t, err.Error(), "failed to connect") @@ -84,7 +84,7 @@ func TestLibvirt_Gather(t *testing.T) { StatisticsGroups: []string{"state"}, } mockLibvirtUtils.On("EnsureConnected", mock.Anything).Return(nil).Once(). - On("GatherAllDomains", mock.Anything).Return(nil, fmt.Errorf("gather domain error")).Once(). + On("GatherAllDomains", mock.Anything).Return(nil, errors.New("gather domain error")).Once(). On("Disconnect").Return(nil).Once() err := l.Gather(&acc) @@ -120,7 +120,7 @@ func TestLibvirt_Gather(t *testing.T) { mockLibvirtUtils.On("EnsureConnected", mock.Anything).Return(nil).Once(). On("GatherAllDomains", mock.Anything).Return(domains, nil).Once(). On("GatherStatsForDomains", mock.Anything, mock.Anything). - Return(nil, fmt.Errorf("gathering metric by number error")).Once(). + Return(nil, errors.New("gathering metric by number error")).Once(). On("Disconnect").Return(nil).Once() err := l.Init() diff --git a/plugins/inputs/linux_cpu/linux_cpu.go b/plugins/inputs/linux_cpu/linux_cpu.go index 90c9e19c4..f35b31e6e 100644 --- a/plugins/inputs/linux_cpu/linux_cpu.go +++ b/plugins/inputs/linux_cpu/linux_cpu.go @@ -58,7 +58,7 @@ func (g *LinuxCPU) Init() error { if len(g.Metrics) == 0 { // The user has not enabled any of the metrics - return fmt.Errorf("no metrics selected") + return errors.New("no metrics selected") } cpus, err := g.discoverCpus() @@ -66,7 +66,7 @@ func (g *LinuxCPU) Init() error { return err } else if len(cpus) == 0 { // Although the user has specified metrics to collect, `discoverCpus` failed to find the required metrics - return fmt.Errorf("no CPUs detected to track") + return errors.New("no CPUs detected to track") } g.cpus = cpus @@ -208,7 +208,7 @@ func readUintFromFile(propPath string) (uint64, error) { if err != nil && !errors.Is(err, io.EOF) { return 0, fmt.Errorf("error on reading file: %w", err) } else if n == 0 { - return 0, fmt.Errorf("error on reading file: file is empty") + return 0, errors.New("error on reading file: file is empty") } return strconv.ParseUint(string(buffer[:n-1]), 10, 64) diff --git a/plugins/inputs/mcrouter/mcrouter.go b/plugins/inputs/mcrouter/mcrouter.go index 950e3c6c6..05e9a3c2f 100644 --- a/plugins/inputs/mcrouter/mcrouter.go +++ b/plugins/inputs/mcrouter/mcrouter.go @@ -5,6 +5,7 @@ import ( "bufio" "context" _ "embed" + "errors" "fmt" "net" "net/url" @@ -145,24 +146,24 @@ func (m *Mcrouter) ParseAddress(address string) (parsedAddress string, protocol u, parseError := url.Parse(parsedAddress) if parseError != nil { - return "", "", fmt.Errorf("invalid server address") + return "", "", errors.New("invalid server address") } if u.Scheme != "tcp" && u.Scheme != "unix" { - return "", "", fmt.Errorf("invalid server protocol") + return "", "", errors.New("invalid server protocol") } protocol = u.Scheme if protocol == "unix" { if u.Path == "" { - return "", "", fmt.Errorf("invalid unix socket path") + return "", "", errors.New("invalid unix socket path") } parsedAddress = u.Path } else { if u.Host == "" { - return "", "", fmt.Errorf("invalid host") + return "", "", errors.New("invalid host") } host = u.Hostname() diff --git a/plugins/inputs/memcached/memcached.go b/plugins/inputs/memcached/memcached.go index 163b2692c..2175e8fb7 100644 --- a/plugins/inputs/memcached/memcached.go +++ b/plugins/inputs/memcached/memcached.go @@ -6,6 +6,7 @@ import ( "bytes" "crypto/tls" _ "embed" + "errors" "fmt" "net" "strconv" @@ -145,7 +146,7 @@ func (m *Memcached) gatherServer( } if conn == nil { - return fmt.Errorf("Failed to create net connection") + return errors.New("failed to create net connection") } // Extend connection diff --git a/plugins/inputs/modbus/modbus.go b/plugins/inputs/modbus/modbus.go index 2bbdf6803..463020672 100644 --- a/plugins/inputs/modbus/modbus.go +++ b/plugins/inputs/modbus/modbus.go @@ -128,11 +128,11 @@ func (m *Modbus) SampleConfig() string { func (m *Modbus) Init() error { //check device name if m.Name == "" { - return fmt.Errorf("device name is empty") + return errors.New("device name is empty") } if m.Retries < 0 { - return fmt.Errorf("retries cannot be negative") + return errors.New("retries cannot be negative") } // Determine the configuration style diff --git a/plugins/inputs/mongodb/mongodb.go b/plugins/inputs/mongodb/mongodb.go index 21acdb0e4..17c0773f7 100644 --- a/plugins/inputs/mongodb/mongodb.go +++ b/plugins/inputs/mongodb/mongodb.go @@ -6,6 +6,7 @@ import ( "crypto/tls" "crypto/x509" _ "embed" + "errors" "fmt" "net/url" "strings" @@ -68,13 +69,13 @@ func (m *MongoDB) Init() error { InsecureSkipVerify: m.ClientConfig.InsecureSkipVerify, } if len(m.Ssl.CaCerts) == 0 { - return fmt.Errorf("you must explicitly set insecure_skip_verify to skip certificate validation") + return errors.New("you must explicitly set insecure_skip_verify to skip certificate validation") } roots := x509.NewCertPool() for _, caCert := range m.Ssl.CaCerts { if ok := roots.AppendCertsFromPEM([]byte(caCert)); !ok { - return fmt.Errorf("failed to parse root certificate") + return errors.New("failed to parse root certificate") } } m.tlsConfig.RootCAs = roots diff --git a/plugins/inputs/mongodb/mongodb_server.go b/plugins/inputs/mongodb/mongodb_server.go index e26c73fc2..1b64c3747 100644 --- a/plugins/inputs/mongodb/mongodb_server.go +++ b/plugins/inputs/mongodb/mongodb_server.go @@ -2,6 +2,7 @@ package mongodb import ( "context" + "errors" "fmt" "strconv" "strings" @@ -106,13 +107,13 @@ func (s *Server) gatherTopStatData() (*TopStats, error) { totals, ok := dest["totals"].(map[string]interface{}) if !ok { - return nil, fmt.Errorf("collection totals not found or not a map") + return nil, errors.New("collection totals not found or not a map") } delete(totals, "note") recorded, err := bson.Marshal(totals) if err != nil { - return nil, fmt.Errorf("unable to marshal totals") + return nil, errors.New("unable to marshal totals") } topInfo := make(map[string]TopStatCollection) diff --git a/plugins/inputs/mqtt_consumer/mqtt_consumer.go b/plugins/inputs/mqtt_consumer/mqtt_consumer.go index 69aa74a0a..7282196d3 100644 --- a/plugins/inputs/mqtt_consumer/mqtt_consumer.go +++ b/plugins/inputs/mqtt_consumer/mqtt_consumer.go @@ -147,15 +147,15 @@ func (m *MQTTConsumer) Init() error { m.TopicParsing[i].SplitTopic = strings.Split(p.Topic, "/") if len(splitMeasurement) != len(m.TopicParsing[i].SplitTopic) && len(splitMeasurement) != 1 { - return fmt.Errorf("config error topic parsing: measurement length does not equal topic length") + return errors.New("config error topic parsing: measurement length does not equal topic length") } if len(m.TopicParsing[i].SplitFields) != len(m.TopicParsing[i].SplitTopic) && p.Fields != "" { - return fmt.Errorf("config error topic parsing: fields length does not equal topic length") + return errors.New("config error topic parsing: fields length does not equal topic length") } if len(m.TopicParsing[i].SplitTags) != len(m.TopicParsing[i].SplitTopic) && p.Tags != "" { - return fmt.Errorf("config error topic parsing: tags length does not equal topic length") + return errors.New("config error topic parsing: tags length does not equal topic length") } } @@ -383,7 +383,7 @@ func (m *MQTTConsumer) createOpts() (*mqtt.ClientOptions, error) { password.Destroy() } if len(m.Servers) == 0 { - return opts, fmt.Errorf("could not get host information") + return opts, errors.New("could not get host information") } for _, server := range m.Servers { // Preserve support for host:port style servers; deprecated in Telegraf 1.4.4 diff --git a/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go b/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go index f01cf9868..69d23946a 100644 --- a/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go +++ b/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go @@ -1,7 +1,7 @@ package mqtt_consumer import ( - "fmt" + "errors" "testing" "time" @@ -325,7 +325,7 @@ func TestTopicTag(t *testing.T) { tag := "" return &tag }, - expectedError: fmt.Errorf("config error topic parsing: fields length does not equal topic length"), + expectedError: errors.New("config error topic parsing: fields length does not equal topic length"), topicParsing: []TopicParsingConfig{ { Topic: "telegraf/+/test/hello", diff --git a/plugins/inputs/nsq_consumer/nsq_consumer.go b/plugins/inputs/nsq_consumer/nsq_consumer.go index 1ee22924d..47a81f275 100644 --- a/plugins/inputs/nsq_consumer/nsq_consumer.go +++ b/plugins/inputs/nsq_consumer/nsq_consumer.go @@ -5,7 +5,6 @@ import ( "context" _ "embed" "errors" - "fmt" "sync" "github.com/nsqio/go-nsq" @@ -112,7 +111,7 @@ func (n *NSQConsumer) Start(ac telegraf.Accumulator) error { // Check if we have anything to connect to if len(n.Nsqlookupd) == 0 && len(n.Nsqd) == 0 { - return fmt.Errorf("either 'nsqd' or 'nsqlookupd' needs to be specified") + return errors.New("either 'nsqd' or 'nsqlookupd' needs to be specified") } if len(n.Nsqlookupd) > 0 { diff --git a/plugins/inputs/opcua_listener/subscribe_client.go b/plugins/inputs/opcua_listener/subscribe_client.go index bec753eec..ac8373a28 100644 --- a/plugins/inputs/opcua_listener/subscribe_client.go +++ b/plugins/inputs/opcua_listener/subscribe_client.go @@ -2,6 +2,7 @@ package opcua_listener import ( "context" + "errors" "fmt" "reflect" "time" @@ -44,9 +45,9 @@ func checkDataChangeFilterParameters(params *input.DataChangeFilter) error { params.DeadbandType != input.Percent: return fmt.Errorf("deadband_type '%s' not supported", params.DeadbandType) case params.DeadbandValue == nil: - return fmt.Errorf("deadband_value was not set") + return errors.New("deadband_value was not set") case *params.DeadbandValue < 0: - return fmt.Errorf("negative deadband_value not supported") + return errors.New("negative deadband_value not supported") default: return nil } diff --git a/plugins/inputs/opensearch_query/aggregation.bucket.go b/plugins/inputs/opensearch_query/aggregation.bucket.go index 358c015ea..87669e5c7 100644 --- a/plugins/inputs/opensearch_query/aggregation.bucket.go +++ b/plugins/inputs/opensearch_query/aggregation.bucket.go @@ -1,6 +1,9 @@ package opensearch_query -import "fmt" +import ( + "errors" + "fmt" +) type BucketAggregationRequest map[string]*aggregationFunction @@ -25,7 +28,7 @@ func (b BucketAggregationRequest) AddNestedAggregation(name string, a Aggregatio func (b BucketAggregationRequest) BucketSize(name string, size int) error { if size <= 0 { - return fmt.Errorf("invalid size; must be integer value > 0") + return errors.New("invalid size; must be integer value > 0") } if _, ok := b[name]; !ok { diff --git a/plugins/inputs/opensearch_query/opensearch_query.go b/plugins/inputs/opensearch_query/opensearch_query.go index 10f2e4406..f3d4eab63 100644 --- a/plugins/inputs/opensearch_query/opensearch_query.go +++ b/plugins/inputs/opensearch_query/opensearch_query.go @@ -6,6 +6,7 @@ import ( "crypto/tls" _ "embed" "encoding/json" + "errors" "fmt" "net/http" "strings" @@ -65,7 +66,7 @@ func (*OpensearchQuery) SampleConfig() string { // Init the plugin. func (o *OpensearchQuery) Init() error { if o.URLs == nil { - return fmt.Errorf("no urls defined") + return errors.New("no urls defined") } err := o.newClient() @@ -75,10 +76,10 @@ func (o *OpensearchQuery) Init() error { for i, agg := range o.Aggregations { if agg.MeasurementName == "" { - return fmt.Errorf("field 'measurement_name' is not set") + return errors.New("field 'measurement_name' is not set") } if agg.DateField == "" { - return fmt.Errorf("field 'date_field' is not set") + return errors.New("field 'date_field' is not set") } err = o.initAggregation(agg, i) if err != nil { diff --git a/plugins/inputs/openstack/openstack.go b/plugins/inputs/openstack/openstack.go index 80306fecf..10ae233c5 100644 --- a/plugins/inputs/openstack/openstack.go +++ b/plugins/inputs/openstack/openstack.go @@ -13,6 +13,7 @@ package openstack import ( "context" _ "embed" + "errors" "fmt" "regexp" "sort" @@ -113,10 +114,10 @@ func (o *OpenStack) Init() error { } sort.Strings(o.EnabledServices) if o.Username == "" || o.Password == "" { - return fmt.Errorf("username or password can not be empty string") + return errors.New("username or password can not be empty string") } if o.TagValue == "" { - return fmt.Errorf("tag_value option can not be empty string") + return errors.New("tag_value option can not be empty string") } // Check the enabled services diff --git a/plugins/inputs/p4runtime/p4runtime_test.go b/plugins/inputs/p4runtime/p4runtime_test.go index 3bb297e38..c797fa274 100644 --- a/plugins/inputs/p4runtime/p4runtime_test.go +++ b/plugins/inputs/p4runtime/p4runtime_test.go @@ -76,10 +76,8 @@ func TestErrorGetP4Info(t *testing.T) { getForwardingPipelineConfigResponseError error }{ { - getForwardingPipelineConfigResponse: nil, - getForwardingPipelineConfigResponseError: fmt.Errorf( - "error when retrieving forwarding pipeline config", - ), + getForwardingPipelineConfigResponse: nil, + getForwardingPipelineConfigResponseError: errors.New("error when retrieving forwarding pipeline config"), }, { getForwardingPipelineConfigResponse: &p4v1.GetForwardingPipelineConfigResponse{ Config: nil, @@ -583,7 +581,7 @@ func TestFailReadCounterEntryFromEntry(t *testing.T) { func TestFailReadAllEntries(t *testing.T) { p4RtClient := &fakeP4RuntimeClient{ readFn: func(ctx context.Context, in *p4v1.ReadRequest, opts ...grpc.CallOption) (p4v1.P4Runtime_ReadClient, error) { - return nil, errors.New("Connection error") + return nil, errors.New("connection error") }, getForwardingPipelineConfigFn: func( ctx context.Context, @@ -617,8 +615,7 @@ func TestFailReadAllEntries(t *testing.T) { require.Equal( t, acc.Errors[0], - fmt.Errorf("reading counter entries with ID=1111 failed with error: %w", - errors.New("Connection error")), + fmt.Errorf("reading counter entries with ID=1111 failed with error: %w", errors.New("connection error")), ) testutil.RequireMetricsEqual( t, diff --git a/plugins/inputs/ping/ping.go b/plugins/inputs/ping/ping.go index 2487d8056..68cbb08e0 100644 --- a/plugins/inputs/ping/ping.go +++ b/plugins/inputs/ping/ping.go @@ -160,10 +160,10 @@ func (p *Ping) nativePing(destination string) (*pingStats, error) { if err != nil { if strings.Contains(err.Error(), "operation not permitted") { if runtime.GOOS == "linux" { - return nil, fmt.Errorf("permission changes required, enable CAP_NET_RAW capabilities (refer to the ping plugin's README.md for more info)") + return nil, errors.New("permission changes required, enable CAP_NET_RAW capabilities (refer to the ping plugin's README.md for more info)") } - return nil, fmt.Errorf("permission changes required, refer to the ping plugin's README.md for more info") + return nil, errors.New("permission changes required, refer to the ping plugin's README.md for more info") } return nil, err } diff --git a/plugins/inputs/ping/ping_test.go b/plugins/inputs/ping/ping_test.go index 205420e22..6033c79d7 100644 --- a/plugins/inputs/ping/ping_test.go +++ b/plugins/inputs/ping/ping_test.go @@ -4,7 +4,6 @@ package ping import ( "errors" - "fmt" "sort" "testing" "time" @@ -518,7 +517,7 @@ func TestDNSLookupError(t *testing.T) { Method: "native", IPv6: false, nativePingFunc: func(destination string) (*pingStats, error) { - return nil, fmt.Errorf("unknown") + return nil, errors.New("unknown") }, } diff --git a/plugins/inputs/powerdns_recursor/protocol_commons.go b/plugins/inputs/powerdns_recursor/protocol_commons.go index ac6f75cf9..712d78b8c 100644 --- a/plugins/inputs/powerdns_recursor/protocol_commons.go +++ b/plugins/inputs/powerdns_recursor/protocol_commons.go @@ -1,6 +1,7 @@ package powerdns_recursor import ( + "errors" "fmt" "net" "strconv" @@ -57,7 +58,7 @@ func writeNativeUIntToConn(conn net.Conn, value uint) error { case 8: internal.HostEndianness.PutUint64(intData, uint64(value)) default: - return fmt.Errorf("unsupported system configuration") + return errors.New("unsupported system configuration") } _, err := conn.Write(intData) @@ -83,6 +84,6 @@ func readNativeUIntFromConn(conn net.Conn) (uint, error) { case 8: return uint(internal.HostEndianness.Uint64(intData)), nil default: - return 0, fmt.Errorf("unsupported system configuration") + return 0, errors.New("unsupported system configuration") } } diff --git a/plugins/inputs/powerdns_recursor/protocol_v1.go b/plugins/inputs/powerdns_recursor/protocol_v1.go index e166a9f7f..6e9391a18 100644 --- a/plugins/inputs/powerdns_recursor/protocol_v1.go +++ b/plugins/inputs/powerdns_recursor/protocol_v1.go @@ -1,6 +1,7 @@ package powerdns_recursor import ( + "errors" "fmt" "net" "os" @@ -64,7 +65,7 @@ func (p *PowerdnsRecursor) gatherFromV1Server(address string, acc telegraf.Accum return err } if n == 0 { - return fmt.Errorf("no data received") + return errors.New("no data received") } metrics := string(buf) diff --git a/plugins/inputs/powerdns_recursor/protocol_v2.go b/plugins/inputs/powerdns_recursor/protocol_v2.go index dbeb4c96b..9473581ac 100644 --- a/plugins/inputs/powerdns_recursor/protocol_v2.go +++ b/plugins/inputs/powerdns_recursor/protocol_v2.go @@ -1,6 +1,7 @@ package powerdns_recursor import ( + "errors" "fmt" "net" "os" @@ -68,7 +69,7 @@ func (p *PowerdnsRecursor) gatherFromV2Server(address string, acc telegraf.Accum return err } if n == 0 { - return fmt.Errorf("no status code received") + return errors.New("no status code received") } // Read the response data. @@ -78,7 +79,7 @@ func (p *PowerdnsRecursor) gatherFromV2Server(address string, acc telegraf.Accum return err } if n == 0 { - return fmt.Errorf("no data received") + return errors.New("no data received") } metrics := string(buf) diff --git a/plugins/inputs/powerdns_recursor/protocol_v3.go b/plugins/inputs/powerdns_recursor/protocol_v3.go index 857f851df..b6e04e5ea 100644 --- a/plugins/inputs/powerdns_recursor/protocol_v3.go +++ b/plugins/inputs/powerdns_recursor/protocol_v3.go @@ -1,6 +1,7 @@ package powerdns_recursor import ( + "errors" "fmt" "net" "time" @@ -49,7 +50,7 @@ func (p *PowerdnsRecursor) gatherFromV3Server(address string, acc telegraf.Accum return err } if n == 0 { - return fmt.Errorf("no status code received") + return errors.New("no status code received") } responseLength, err := readNativeUIntFromConn(conn) @@ -57,7 +58,7 @@ func (p *PowerdnsRecursor) gatherFromV3Server(address string, acc telegraf.Accum return err } if responseLength == 0 { - return fmt.Errorf("received data length was '0'") + return errors.New("received data length was '0'") } // Don't allow more than 64kb of data to prevent DOS / issues diff --git a/plugins/inputs/processes/processes_test.go b/plugins/inputs/processes/processes_test.go index 4f107512e..2e4c1b0b6 100644 --- a/plugins/inputs/processes/processes_test.go +++ b/plugins/inputs/processes/processes_test.go @@ -3,6 +3,7 @@ package processes import ( + "errors" "fmt" "runtime" "testing" @@ -192,7 +193,7 @@ func (t *tester) testProcFile2(_ string) ([]byte, error) { } func testExecPSError(_ bool) ([]byte, error) { - return []byte("\nSTAT\nD\nI\nL\nR\nR+\nS\nS+\nSNs\nSs\nU\nZ\n"), fmt.Errorf("error") + return []byte("\nSTAT\nD\nI\nL\nR\nR+\nS\nS+\nSNs\nSs\nU\nZ\n"), errors.New("error") } const testProcStat = `10 (rcuob/0) %s 2 0 0 0 -1 2129984 0 0 0 0 0 0 0 0 20 0 %s 0 11 0 0 18446744073709551615 0 0 0 0 0 0 0 ` + diff --git a/plugins/inputs/procstat/process.go b/plugins/inputs/procstat/process.go index 53e4b941d..74342d50c 100644 --- a/plugins/inputs/procstat/process.go +++ b/plugins/inputs/procstat/process.go @@ -1,14 +1,15 @@ package procstat import ( - "fmt" + "errors" "runtime" "strconv" "time" + "github.com/shirou/gopsutil/v3/process" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/shirou/gopsutil/v3/process" ) type Process interface { @@ -59,7 +60,7 @@ func (p *Proc) percent(_ time.Duration) (float64, error) { cpuPerc, err := p.Process.Percent(time.Duration(0)) if !p.hasCPUTimes && err == nil { p.hasCPUTimes = true - return 0, fmt.Errorf("must call Percent twice to compute percent cpu") + return 0, errors.New("must call Percent twice to compute percent cpu") } return cpuPerc, err } diff --git a/plugins/inputs/procstat/procstat_test.go b/plugins/inputs/procstat/procstat_test.go index 0d7d4b050..50d7bfbb4 100644 --- a/plugins/inputs/procstat/procstat_test.go +++ b/plugins/inputs/procstat/procstat_test.go @@ -1,6 +1,7 @@ package procstat import ( + "errors" "fmt" "os" "os/exec" @@ -269,7 +270,7 @@ func TestGather_CreateProcessErrorOk(t *testing.T) { Log: testutil.Logger{}, finder: newTestFinder([]PID{pid}), createProcess: func(PID) (Process, error) { - return nil, fmt.Errorf("createProcess error") + return nil, errors.New("createProcess error") }, } require.NoError(t, p.Init()) diff --git a/plugins/inputs/rabbitmq/rabbitmq.go b/plugins/inputs/rabbitmq/rabbitmq.go index 917f9310d..01110b9dd 100644 --- a/plugins/inputs/rabbitmq/rabbitmq.go +++ b/plugins/inputs/rabbitmq/rabbitmq.go @@ -404,7 +404,7 @@ func gatherOverview(r *RabbitMQ, acc telegraf.Accumulator) { } if overview.QueueTotals == nil || overview.ObjectTotals == nil || overview.MessageStats == nil { - acc.AddError(fmt.Errorf("Wrong answer from rabbitmq. Probably auth issue")) + acc.AddError(errors.New("wrong answer from rabbitmq, probably auth issue")) return } diff --git a/plugins/inputs/rabbitmq/rabbitmq_test.go b/plugins/inputs/rabbitmq/rabbitmq_test.go index bf77afc87..8e0722802 100644 --- a/plugins/inputs/rabbitmq/rabbitmq_test.go +++ b/plugins/inputs/rabbitmq/rabbitmq_test.go @@ -1,6 +1,7 @@ package rabbitmq import ( + "errors" "fmt" "net/http" "net/http/httptest" @@ -598,7 +599,7 @@ func TestRabbitMQGeneratesMetricsSet2(t *testing.T) { ), } expectedErrors := []error{ - fmt.Errorf("error response trying to get \"/api/federation-links\": \"Object Not Found\" (reason: \"Not Found\")"), + errors.New("error response trying to get \"/api/federation-links\": \"Object Not Found\" (reason: \"Not Found\")"), } // Run the test @@ -625,11 +626,11 @@ func TestRabbitMQMetricFilerts(t *testing.T) { defer ts.Close() metricErrors := map[string]error{ - "exchange": fmt.Errorf("getting \"/api/exchanges\" failed: 404 Not Found"), - "federation": fmt.Errorf("getting \"/api/federation-links\" failed: 404 Not Found"), - "node": fmt.Errorf("getting \"/api/nodes\" failed: 404 Not Found"), - "overview": fmt.Errorf("getting \"/api/overview\" failed: 404 Not Found"), - "queue": fmt.Errorf("getting \"/api/queues\" failed: 404 Not Found"), + "exchange": errors.New("getting \"/api/exchanges\" failed: 404 Not Found"), + "federation": errors.New("getting \"/api/federation-links\" failed: 404 Not Found"), + "node": errors.New("getting \"/api/nodes\" failed: 404 Not Found"), + "overview": errors.New("getting \"/api/overview\" failed: 404 Not Found"), + "queue": errors.New("getting \"/api/queues\" failed: 404 Not Found"), } // Include test diff --git a/plugins/inputs/redfish/redfish.go b/plugins/inputs/redfish/redfish.go index 9e01a712b..894ecdbe5 100644 --- a/plugins/inputs/redfish/redfish.go +++ b/plugins/inputs/redfish/redfish.go @@ -4,6 +4,7 @@ package redfish import ( _ "embed" "encoding/json" + "errors" "fmt" "io" "net" @@ -158,19 +159,19 @@ func (*Redfish) SampleConfig() string { func (r *Redfish) Init() error { if r.Address == "" { - return fmt.Errorf("did not provide IP") + return errors.New("did not provide IP") } if r.Username == "" && r.Password == "" { - return fmt.Errorf("did not provide username and password") + return errors.New("did not provide username and password") } if r.ComputerSystemID == "" { - return fmt.Errorf("did not provide the computer system ID of the resource") + return errors.New("did not provide the computer system ID of the resource") } if len(r.IncludeMetrics) == 0 { - return fmt.Errorf("no metrics specified to collect") + return errors.New("no metrics specified to collect") } for _, metric := range r.IncludeMetrics { switch metric { diff --git a/plugins/inputs/redis_sentinel/redis_sentinel.go b/plugins/inputs/redis_sentinel/redis_sentinel.go index e30054a12..2edc589a3 100644 --- a/plugins/inputs/redis_sentinel/redis_sentinel.go +++ b/plugins/inputs/redis_sentinel/redis_sentinel.go @@ -4,6 +4,7 @@ package redis_sentinel import ( "bufio" _ "embed" + "errors" "fmt" "io" "net/url" @@ -238,14 +239,14 @@ func (client *RedisSentinelClient) gatherMasterStats(acc telegraf.Accumulator) ( for _, master := range masters { master, ok := master.([]interface{}) if !ok { - return masterNames, fmt.Errorf("unable to process master response") + return masterNames, errors.New("unable to process master response") } m := toMap(master) masterName, ok := m["name"] if !ok { - return masterNames, fmt.Errorf("unable to resolve master name") + return masterNames, errors.New("unable to resolve master name") } masterNames = append(masterNames, masterName) @@ -279,7 +280,7 @@ func (client *RedisSentinelClient) gatherReplicaStats(acc telegraf.Accumulator, for _, replica := range replicas { replica, ok := replica.([]interface{}) if !ok { - return fmt.Errorf("unable to process replica response") + return errors.New("unable to process replica response") } rm := toMap(replica) @@ -311,7 +312,7 @@ func (client *RedisSentinelClient) gatherSentinelStats(acc telegraf.Accumulator, for _, sentinel := range sentinels { sentinel, ok := sentinel.([]interface{}) if !ok { - return fmt.Errorf("unable to process sentinel response") + return errors.New("unable to process sentinel response") } sm := toMap(sentinel) diff --git a/plugins/inputs/smart/smart.go b/plugins/inputs/smart/smart.go index 55c9318c5..17750a4ad 100644 --- a/plugins/inputs/smart/smart.go +++ b/plugins/inputs/smart/smart.go @@ -1031,7 +1031,7 @@ func parseCommaSeparatedInt(fields, _ map[string]interface{}, str string) error // '16 829 004' --> 16829004 numRegex, err := regexp.Compile(`[^0-9\-]+`) if err != nil { - return fmt.Errorf("failed to compile numeric regex") + return errors.New("failed to compile numeric regex") } value = numRegex.ReplaceAllString(value, "") diff --git a/plugins/inputs/snmp/gosmi_test.go b/plugins/inputs/snmp/gosmi_test.go index 57ff77b15..3e247739a 100644 --- a/plugins/inputs/snmp/gosmi_test.go +++ b/plugins/inputs/snmp/gosmi_test.go @@ -1,7 +1,7 @@ package snmp import ( - "fmt" + "errors" "path/filepath" "testing" "time" @@ -612,7 +612,7 @@ func TestSnmpTranslateCache_hitGosmi(t *testing.T) { oidNum: "b", oidText: "c", conversion: "d", - err: fmt.Errorf("e"), + err: errors.New("e"), }, } mibName, oidNum, oidText, conversion, err := getGosmiTr(t).SnmpTranslate("foo") @@ -620,7 +620,7 @@ func TestSnmpTranslateCache_hitGosmi(t *testing.T) { require.Equal(t, "b", oidNum) require.Equal(t, "c", oidText) require.Equal(t, "d", conversion) - require.Equal(t, fmt.Errorf("e"), err) + require.Equal(t, errors.New("e"), err) gosmiSnmpTranslateCaches = nil } @@ -645,7 +645,7 @@ func TestSnmpTableCache_hitGosmi(t *testing.T) { oidNum: "b", oidText: "c", fields: []Field{{Name: "d"}}, - err: fmt.Errorf("e"), + err: errors.New("e"), }, } mibName, oidNum, oidText, fields, err := getGosmiTr(t).SnmpTable("foo") @@ -653,7 +653,7 @@ func TestSnmpTableCache_hitGosmi(t *testing.T) { require.Equal(t, "b", oidNum) require.Equal(t, "c", oidText) require.Equal(t, []Field{{Name: "d"}}, fields) - require.Equal(t, fmt.Errorf("e"), err) + require.Equal(t, errors.New("e"), err) } func TestTableJoin_walkGosmi(t *testing.T) { diff --git a/plugins/inputs/snmp/netsnmp.go b/plugins/inputs/snmp/netsnmp.go index 7a9ef5f6c..6943fc511 100644 --- a/plugins/inputs/snmp/netsnmp.go +++ b/plugins/inputs/snmp/netsnmp.go @@ -132,7 +132,7 @@ func (n *netsnmpTranslator) snmpTableCall(oid string) ( scanner.Scan() cols := scanner.Text() if len(cols) == 0 { - return "", "", "", nil, fmt.Errorf("could not find any columns in table") + return "", "", "", nil, errors.New("could not find any columns in table") } for _, col := range strings.Split(cols, " ") { if len(col) == 0 { diff --git a/plugins/inputs/snmp/snmp.go b/plugins/inputs/snmp/snmp.go index f6af70c31..4a571bc9a 100644 --- a/plugins/inputs/snmp/snmp.go +++ b/plugins/inputs/snmp/snmp.go @@ -89,7 +89,7 @@ func (s *Snmp) Init() error { case "netsnmp": s.translator = NewNetsnmpTranslator() default: - return fmt.Errorf("invalid translator value") + return errors.New("invalid translator value") } s.connectionCache = make([]snmpConnection, len(s.Agents)) @@ -146,7 +146,7 @@ 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 fmt.Errorf("SNMP table in config file is not named. One or both of the oid and name settings must be set") + return errors.New("SNMP table in config file is not named. One or both of the oid and name settings must be set") } if t.initialized { @@ -165,7 +165,7 @@ func (t *Table) Init(tr Translator) error { } if t.Fields[i].SecondaryIndexTable { if secondaryIndexTablePresent { - return fmt.Errorf("only one field can be SecondaryIndexTable") + return errors.New("only one field can be SecondaryIndexTable") } secondaryIndexTablePresent = true } @@ -270,11 +270,11 @@ func (f *Field) init(tr Translator) error { } if f.SecondaryIndexTable && f.SecondaryIndexUse { - return fmt.Errorf("SecondaryIndexTable and UseSecondaryIndex are exclusive") + return errors.New("SecondaryIndexTable and UseSecondaryIndex are exclusive") } if !f.SecondaryIndexTable && !f.SecondaryIndexUse && f.SecondaryOuterJoin { - return fmt.Errorf("SecondaryOuterJoin set to true, but field is not being used in join") + return errors.New("SecondaryOuterJoin set to true, but field is not being used in join") } f.initialized = true @@ -425,13 +425,13 @@ func (t Table) Build(gs snmpConnection, walk bool, tr Translator) (*RTable, erro // index, and being added on the same row. if pkt, err := gs.Get([]string{oid}); err != nil { if errors.Is(err, gosnmp.ErrUnknownSecurityLevel) { - return nil, fmt.Errorf("unknown security level (sec_level)") + return nil, errors.New("unknown security level (sec_level)") } else if errors.Is(err, gosnmp.ErrUnknownUsername) { - return nil, fmt.Errorf("unknown username (sec_name)") + return nil, errors.New("unknown username (sec_name)") } else if errors.Is(err, gosnmp.ErrWrongDigest) { - return nil, fmt.Errorf("wrong digest (auth_protocol, auth_password)") + return nil, errors.New("wrong digest (auth_protocol, auth_password)") } else if errors.Is(err, gosnmp.ErrDecryption) { - return nil, fmt.Errorf("decryption error (priv_protocol, priv_password)") + return nil, errors.New("decryption error (priv_protocol, priv_password)") } return nil, fmt.Errorf("performing get on field %s: %w", f.Name, err) } else if pkt != nil && len(pkt.Variables) > 0 && pkt.Variables[0].Type != gosnmp.NoSuchObject && pkt.Variables[0].Type != gosnmp.NoSuchInstance { diff --git a/plugins/inputs/snmp/snmp_test.go b/plugins/inputs/snmp/snmp_test.go index 44aec0ae9..e94aae868 100644 --- a/plugins/inputs/snmp/snmp_test.go +++ b/plugins/inputs/snmp/snmp_test.go @@ -2,6 +2,7 @@ package snmp import ( + "errors" "fmt" "net" "os/exec" @@ -908,7 +909,7 @@ func TestSnmpTranslateCache_hit(t *testing.T) { oidNum: "b", oidText: "c", conversion: "d", - err: fmt.Errorf("e"), + err: errors.New("e"), }, } mibName, oidNum, oidText, conversion, err := NewNetsnmpTranslator().SnmpTranslate("foo") @@ -916,7 +917,7 @@ func TestSnmpTranslateCache_hit(t *testing.T) { require.Equal(t, "b", oidNum) require.Equal(t, "c", oidText) require.Equal(t, "d", conversion) - require.Equal(t, fmt.Errorf("e"), err) + require.Equal(t, errors.New("e"), err) snmpTranslateCaches = nil } @@ -941,7 +942,7 @@ func TestSnmpTableCache_hit(t *testing.T) { oidNum: "b", oidText: "c", fields: []Field{{Name: "d"}}, - err: fmt.Errorf("e"), + err: errors.New("e"), }, } mibName, oidNum, oidText, fields, err := NewNetsnmpTranslator().SnmpTable("foo") @@ -949,7 +950,7 @@ func TestSnmpTableCache_hit(t *testing.T) { require.Equal(t, "b", oidNum) require.Equal(t, "c", oidText) require.Equal(t, []Field{{Name: "d"}}, fields) - require.Equal(t, fmt.Errorf("e"), err) + require.Equal(t, errors.New("e"), err) } func TestTableJoin_walk(t *testing.T) { diff --git a/plugins/inputs/snmp_trap/netsnmp.go b/plugins/inputs/snmp_trap/netsnmp.go index ce06987e4..beab7ac67 100644 --- a/plugins/inputs/snmp_trap/netsnmp.go +++ b/plugins/inputs/snmp_trap/netsnmp.go @@ -3,7 +3,7 @@ package snmp_trap import ( "bufio" "bytes" - "fmt" + "errors" "os/exec" "strings" "sync" @@ -75,7 +75,7 @@ func (s *netsnmpTranslator) snmptranslate(oid string) (e snmp.MibEntry, err erro i := strings.Index(e.OidText, "::") if i == -1 { - return e, fmt.Errorf("not found") + return e, errors.New("not found") } e.MibName = e.OidText[:i] e.OidText = e.OidText[i+2:] diff --git a/plugins/inputs/snmp_trap/snmp_trap.go b/plugins/inputs/snmp_trap/snmp_trap.go index 0479b3ef7..5aec21c4c 100644 --- a/plugins/inputs/snmp_trap/snmp_trap.go +++ b/plugins/inputs/snmp_trap/snmp_trap.go @@ -4,6 +4,7 @@ package snmp_trap import ( _ "embed" "encoding/hex" + "errors" "fmt" "net" "strconv" @@ -105,7 +106,7 @@ func (s *SnmpTrap) Init() error { case "netsnmp": s.transl = newNetsnmpTranslator(s.Timeout) default: - return fmt.Errorf("invalid translator value") + return errors.New("invalid translator value") } if err != nil { diff --git a/plugins/inputs/snmp_trap/snmp_trap_test.go b/plugins/inputs/snmp_trap/snmp_trap_test.go index 39bfed420..54323b3f8 100644 --- a/plugins/inputs/snmp_trap/snmp_trap_test.go +++ b/plugins/inputs/snmp_trap/snmp_trap_test.go @@ -1,7 +1,7 @@ package snmp_trap import ( - "fmt" + "errors" "net" "strconv" "strings" @@ -32,7 +32,7 @@ func (t *testTranslator) lookup(input string) (snmp.MibEntry, error) { return snmp.MibEntry{MibName: entry.e.MibName, OidText: entry.e.OidText}, nil } } - return snmp.MibEntry{}, fmt.Errorf("unexpected oid") + return snmp.MibEntry{}, errors.New("unexpected oid") } func newTestTranslator(entries []entry) *testTranslator { diff --git a/plugins/inputs/socket_listener/stream_listener.go b/plugins/inputs/socket_listener/stream_listener.go index 02ae52660..bb5ff28e9 100644 --- a/plugins/inputs/socket_listener/stream_listener.go +++ b/plugins/inputs/socket_listener/stream_listener.go @@ -16,10 +16,11 @@ import ( "syscall" "time" + "github.com/mdlayher/vsock" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" - "github.com/mdlayher/vsock" ) type hasSetReadBuffer interface { @@ -93,7 +94,7 @@ func (l *streamListener) setupVsock(u *url.URL) error { // Check address string for containing two tokens if len(addrTuple) < 2 { - return fmt.Errorf("CID and/or port number missing") + return errors.New("CID and/or port 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 @@ -103,7 +104,7 @@ func (l *streamListener) setupVsock(u *url.URL) error { } port, _ := strconv.ParseUint(addrTuple[1], 10, 32) if (port >= uint64(math.Pow(2, 32))-1) && (port <= 0) { - return fmt.Errorf("Port number %d is out of range", port) + return fmt.Errorf("port number %d is out of range", port) } l.listener, err = vsock.Listen(uint32(port), nil) diff --git a/plugins/inputs/sqlserver/sqlserver.go b/plugins/inputs/sqlserver/sqlserver.go index 967dd4a02..9276f10d8 100644 --- a/plugins/inputs/sqlserver/sqlserver.go +++ b/plugins/inputs/sqlserver/sqlserver.go @@ -519,7 +519,7 @@ func (s *SQLServer) loadToken() (*adal.Token, error) { // however it's been structured here to allow extending the cache mechanism to a different approach in future if s.adalToken == nil { - return nil, fmt.Errorf("token is nil or failed to load existing token") + return nil, errors.New("token is nil or failed to load existing token") } return s.adalToken, nil diff --git a/plugins/inputs/statsd/datadog.go b/plugins/inputs/statsd/datadog.go index 3567a9094..dc4be4f99 100644 --- a/plugins/inputs/statsd/datadog.go +++ b/plugins/inputs/statsd/datadog.go @@ -38,14 +38,14 @@ func (s *Statsd) parseEventMessage(now time.Time, message string, defaultHostnam // tag is key:value messageRaw := strings.SplitN(message, ":", 2) if len(messageRaw) < 2 || len(messageRaw[0]) < 7 || len(messageRaw[1]) < 3 { - return fmt.Errorf("invalid message format") + return errors.New("invalid message format") } header := messageRaw[0] message = messageRaw[1] rawLen := strings.SplitN(header[3:], ",", 2) if len(rawLen) != 2 { - return fmt.Errorf("invalid message format") + return errors.New("invalid message format") } titleLen, err := strconv.ParseInt(rawLen[0], 10, 64) @@ -60,7 +60,7 @@ func (s *Statsd) parseEventMessage(now time.Time, message string, defaultHostnam return fmt.Errorf("invalid message format, could not parse text.length: %q", rawLen[0]) } if titleLen+textLen+1 > int64(len(message)) { - return fmt.Errorf("invalid message format, title.length and text.length exceed total message length") + return errors.New("invalid message format, title.length and text.length exceed total message length") } rawTitle := message[:titleLen] @@ -68,7 +68,7 @@ func (s *Statsd) parseEventMessage(now time.Time, message string, defaultHostnam message = message[titleLen+1+textLen:] if len(rawTitle) == 0 || len(rawText) == 0 { - return fmt.Errorf("invalid event message format: empty 'title' or 'text' field") + return errors.New("invalid event message format: empty 'title' or 'text' field") } name := rawTitle diff --git a/plugins/inputs/statsd/statsd.go b/plugins/inputs/statsd/statsd.go index e526ff037..2184fe90d 100644 --- a/plugins/inputs/statsd/statsd.go +++ b/plugins/inputs/statsd/statsd.go @@ -491,7 +491,7 @@ func (s *Statsd) udpListen(conn *net.UDPConn) error { s.UDPBytesRecv.Incr(int64(n)) b, ok := s.bufPool.Get().(*bytes.Buffer) if !ok { - return fmt.Errorf("bufPool is not a bytes buffer") + return errors.New("bufPool is not a bytes buffer") } b.Reset() b.Write(buf[:n]) diff --git a/plugins/inputs/suricata/suricata.go b/plugins/inputs/suricata/suricata.go index 67654819d..a0c55284d 100644 --- a/plugins/inputs/suricata/suricata.go +++ b/plugins/inputs/suricata/suricata.go @@ -336,7 +336,7 @@ func (s *Suricata) parse(acc telegraf.Accumulator, sjson []byte) error { } } else { s.Log.Debugf("Invalid input without 'stats' or 'alert' object: %v", result) - return fmt.Errorf("input does not contain 'stats' or 'alert' object") + return errors.New("input does not contain 'stats' or 'alert' object") } return nil diff --git a/plugins/inputs/synproxy/synproxy_linux.go b/plugins/inputs/synproxy/synproxy_linux.go index 0cfb71761..8dca0aded 100644 --- a/plugins/inputs/synproxy/synproxy_linux.go +++ b/plugins/inputs/synproxy/synproxy_linux.go @@ -4,6 +4,7 @@ package synproxy import ( "bufio" + "errors" "fmt" "os" "strconv" @@ -62,7 +63,7 @@ func (k *Synproxy) getSynproxyStat() (map[string]interface{}, error) { } } if len(hname) == 0 { - return nil, fmt.Errorf("invalid data") + return nil, errors.New("invalid data") } // Read data rows for scanner.Scan() { diff --git a/plugins/inputs/tail/multiline.go b/plugins/inputs/tail/multiline.go index 09b076756..e27534272 100644 --- a/plugins/inputs/tail/multiline.go +++ b/plugins/inputs/tail/multiline.go @@ -3,7 +3,6 @@ package tail import ( "bytes" "errors" - "fmt" "regexp" "strings" "time" @@ -182,7 +181,7 @@ func (w *MultilineMatchWhichLine) UnmarshalText(data []byte) (err error) { return nil } *w = -1 - return fmt.Errorf("unknown multiline MatchWhichLine") + return errors.New("unknown multiline MatchWhichLine") } // MarshalText implements encoding.TextMarshaler @@ -191,5 +190,5 @@ func (w MultilineMatchWhichLine) MarshalText() ([]byte, error) { if s != "" { return []byte(s), nil } - return nil, fmt.Errorf("unknown multiline MatchWhichLine") + return nil, errors.New("unknown multiline MatchWhichLine") } diff --git a/plugins/inputs/vault/vault.go b/plugins/inputs/vault/vault.go index f9a14ed07..3ecdeb8cd 100644 --- a/plugins/inputs/vault/vault.go +++ b/plugins/inputs/vault/vault.go @@ -5,6 +5,7 @@ import ( "context" _ "embed" "encoding/json" + "errors" "fmt" "net/http" "os" @@ -44,11 +45,11 @@ func (n *Vault) Init() error { } if n.TokenFile == "" && n.Token == "" { - return fmt.Errorf("token missing") + return errors.New("token missing") } if n.TokenFile != "" && n.Token != "" { - return fmt.Errorf("both token_file and token are set") + return errors.New("both token_file and token are set") } if n.TokenFile != "" { diff --git a/plugins/inputs/vsphere/vsan.go b/plugins/inputs/vsphere/vsan.go index bcbd2aa8e..98257f50a 100644 --- a/plugins/inputs/vsphere/vsan.go +++ b/plugins/inputs/vsphere/vsan.go @@ -3,6 +3,7 @@ package vsphere import ( "context" "encoding/json" + "errors" "fmt" "strconv" "strings" @@ -182,7 +183,7 @@ func getCmmdsMap(ctx context.Context, client *vim25.Client, clusterObj *object.C } } if resp == nil { - return nil, fmt.Errorf("all hosts fail to query cmmds") + return nil, errors.New("all hosts fail to query cmmds") } var clusterCmmds Cmmds if err := json.Unmarshal([]byte(resp.Returnval), &clusterCmmds); err != nil { diff --git a/plugins/inputs/win_eventlog/util.go b/plugins/inputs/win_eventlog/util.go index 521502cf9..257a79c48 100644 --- a/plugins/inputs/win_eventlog/util.go +++ b/plugins/inputs/win_eventlog/util.go @@ -8,6 +8,7 @@ package win_eventlog import ( "bytes" "encoding/xml" + "errors" "fmt" "strings" "unicode/utf16" @@ -20,7 +21,7 @@ import ( // DecodeUTF16 to UTF8 bytes func DecodeUTF16(b []byte) ([]byte, error) { if len(b)%2 != 0 { - return nil, fmt.Errorf("must have even length byte slice") + return nil, errors.New("must have even length byte slice") } u16s := make([]uint16, 1) diff --git a/plugins/inputs/win_perf_counters/win_perf_counters.go b/plugins/inputs/win_perf_counters/win_perf_counters.go index 7a6fc06ac..86b1e9db6 100644 --- a/plugins/inputs/win_perf_counters/win_perf_counters.go +++ b/plugins/inputs/win_perf_counters/win_perf_counters.go @@ -615,7 +615,7 @@ func (m *WinPerfCounters) Init() error { } if found { - return fmt.Errorf("wildcards can't be used with LocalizeWildcardsExpansion=false") + return errors.New("wildcards can't be used with LocalizeWildcardsExpansion=false") } } return nil diff --git a/plugins/inputs/win_wmi/win_wmi.go b/plugins/inputs/win_wmi/win_wmi.go index 59f7acba8..75c8e1aef 100644 --- a/plugins/inputs/win_wmi/win_wmi.go +++ b/plugins/inputs/win_wmi/win_wmi.go @@ -11,7 +11,7 @@ import ( "strings" "sync" - ole "github.com/go-ole/go-ole" + "github.com/go-ole/go-ole" "github.com/go-ole/go-ole/oleutil" "github.com/influxdata/telegraf" @@ -120,7 +120,7 @@ func (q *Query) doQuery(acc telegraf.Accumulator) error { return err } if unknown == nil { - return fmt.Errorf("failed to create WbemScripting.SWbemLocator, maybe WMI is broken") + return errors.New("failed to create WbemScripting.SWbemLocator, maybe WMI is broken") } defer unknown.Release() diff --git a/plugins/inputs/x509_cert/x509_cert.go b/plugins/inputs/x509_cert/x509_cert.go index 7e94fcf1f..d6f96227e 100644 --- a/plugins/inputs/x509_cert/x509_cert.go +++ b/plugins/inputs/x509_cert/x509_cert.go @@ -384,7 +384,7 @@ func (c *X509Cert) getCert(u *url.URL, timeout time.Duration) ([]*x509.Certifica for { block, rest := pem.Decode(bytes.TrimSpace(content)) if block == nil { - return nil, nil, fmt.Errorf("failed to parse certificate PEM") + return nil, nil, errors.New("failed to parse certificate PEM") } if block.Type == "CERTIFICATE" { diff --git a/plugins/inputs/zipkin/codec/codec_test.go b/plugins/inputs/zipkin/codec/codec_test.go index c3d2fa655..e464b0279 100644 --- a/plugins/inputs/zipkin/codec/codec_test.go +++ b/plugins/inputs/zipkin/codec/codec_test.go @@ -1,7 +1,7 @@ package codec import ( - "fmt" + "errors" "reflect" "testing" "time" @@ -253,7 +253,7 @@ func Test_parentID(t *testing.T) { { name: "bad parent value", span: &MockSpan{ - Error: fmt.Errorf("Mommie Dearest"), + Error: errors.New("mommie dearest"), }, wantErr: true, }, @@ -468,7 +468,7 @@ func TestNewTrace(t *testing.T) { name: "span has no id", spans: []Span{ &MockSpan{ - Error: fmt.Errorf("Span has no id"), + Error: errors.New("span has no id"), }, }, wantErr: true, diff --git a/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go b/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go index fff174059..eaec42304 100644 --- a/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go +++ b/plugins/inputs/zipkin/codec/jsonV1/jsonV1.go @@ -2,6 +2,7 @@ package json_v1 import ( "encoding/json" + "errors" "fmt" "strconv" "time" @@ -65,14 +66,14 @@ func (s *span) Validate() error { func (s *span) Trace() (string, error) { if s.TraceID == "" { - return "", fmt.Errorf("Trace ID cannot be null") + return "", errors.New("trace ID cannot be null") } return TraceIDFromString(s.TraceID) } func (s *span) SpanID() (string, error) { if s.ID == "" { - return "", fmt.Errorf("Span ID cannot be null") + return "", errors.New("span ID cannot be null") } return IDFromString(s.ID) } diff --git a/plugins/inputs/zipkin/codec/thrift/gen-go/zipkincore/zipkinCore.go b/plugins/inputs/zipkin/codec/thrift/gen-go/zipkincore/zipkinCore.go index abc4ecbc4..dcef1217b 100644 --- a/plugins/inputs/zipkin/codec/thrift/gen-go/zipkincore/zipkinCore.go +++ b/plugins/inputs/zipkin/codec/thrift/gen-go/zipkincore/zipkinCore.go @@ -8,8 +8,9 @@ import ( "database/sql/driver" "errors" "fmt" - "github.com/apache/thrift/lib/go/thrift" "time" + + "github.com/apache/thrift/lib/go/thrift" ) // (needed to ensure safety because of naive import list construction.) @@ -69,7 +70,7 @@ func AnnotationTypeFromString(s string) (AnnotationType, error) { case "STRING": return AnnotationType_STRING, nil } - return AnnotationType(0), fmt.Errorf("not a valid AnnotationType string") + return AnnotationType(0), errors.New("not a valid AnnotationType string") } func AnnotationTypePtr(v AnnotationType) *AnnotationType { return &v } diff --git a/plugins/inputs/zipkin/codec/thrift/thrift.go b/plugins/inputs/zipkin/codec/thrift/thrift.go index ab8dc4366..a3b6624b4 100644 --- a/plugins/inputs/zipkin/codec/thrift/thrift.go +++ b/plugins/inputs/zipkin/codec/thrift/thrift.go @@ -3,6 +3,7 @@ package thrift import ( "context" "encoding/binary" + "errors" "fmt" "net" "strconv" @@ -144,7 +145,7 @@ type span struct { func (s *span) Trace() (string, error) { if s.Span.GetTraceIDHigh() == 0 && s.Span.GetTraceID() == 0 { - return "", fmt.Errorf("Span does not have a trace ID") + return "", errors.New("span does not have a trace ID") } if s.Span.GetTraceIDHigh() == 0 { diff --git a/plugins/inputs/zipkin/zipkin_test.go b/plugins/inputs/zipkin/zipkin_test.go index a78ae7b54..e64fd2c64 100644 --- a/plugins/inputs/zipkin/zipkin_test.go +++ b/plugins/inputs/zipkin/zipkin_test.go @@ -2,6 +2,7 @@ package zipkin import ( "bytes" + "errors" "fmt" "net/http" "os" @@ -647,7 +648,7 @@ func postThriftData(datafile, address, contentType string) error { req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/v1/spans", address), bytes.NewReader(dat)) if err != nil { - return fmt.Errorf("HTTP request creation failed") + return errors.New("HTTP request creation failed") } req.Header.Set("Content-Type", contentType) diff --git a/plugins/outputs/amon/amon.go b/plugins/outputs/amon/amon.go index 6de960695..f5465028a 100644 --- a/plugins/outputs/amon/amon.go +++ b/plugins/outputs/amon/amon.go @@ -5,6 +5,7 @@ import ( "bytes" _ "embed" "encoding/json" + "errors" "fmt" "net/http" "strings" @@ -44,7 +45,7 @@ func (*Amon) SampleConfig() string { func (a *Amon) Connect() error { if a.ServerKey == "" || a.AmonInstance == "" { - return fmt.Errorf("serverkey and amon_instance are required fields for amon output") + return errors.New("serverkey and amon_instance are required fields for amon output") } a.client = &http.Client{ Transport: &http.Transport{ @@ -134,7 +135,7 @@ func (p *Point) setValue(v interface{}) error { case float64: p[1] = d default: - return fmt.Errorf("undeterminable type") + return errors.New("undeterminable type") } return nil } diff --git a/plugins/outputs/amon/amon_test.go b/plugins/outputs/amon/amon_test.go index 408f0607b..21c7fc1ed 100644 --- a/plugins/outputs/amon/amon_test.go +++ b/plugins/outputs/amon/amon_test.go @@ -1,14 +1,13 @@ package amon import ( - "fmt" + "errors" "reflect" "testing" "time" - "github.com/influxdata/telegraf/testutil" - "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/testutil" ) func TestBuildPoint(t *testing.T) { @@ -71,7 +70,7 @@ func TestBuildPoint(t *testing.T) { float64(time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC).Unix()), 11234.5, }, - fmt.Errorf("unable to extract value from Fields, undeterminable type"), + errors.New("unable to extract value from Fields, undeterminable type"), }, } for _, tt := range tagtests { diff --git a/plugins/outputs/application_insights/application_insights.go b/plugins/outputs/application_insights/application_insights.go index 7d757579d..1ae55ec5c 100644 --- a/plugins/outputs/application_insights/application_insights.go +++ b/plugins/outputs/application_insights/application_insights.go @@ -3,6 +3,7 @@ package application_insights import ( _ "embed" + "errors" "fmt" "math" "strconv" @@ -46,7 +47,7 @@ func (*ApplicationInsights) SampleConfig() string { func (a *ApplicationInsights) Connect() error { if a.InstrumentationKey == "" { - return fmt.Errorf("instrumentation key is required") + return errors.New("instrumentation key is required") } if a.transmitter == nil { @@ -222,7 +223,7 @@ func getFloat64TelemetryPropertyValue( return metricValue, nil } - return 0.0, fmt.Errorf("no field from the candidate list was found in the metric") + return 0.0, errors.New("no field from the candidate list was found in the metric") } func getIntTelemetryPropertyValue( @@ -248,7 +249,7 @@ func getIntTelemetryPropertyValue( return metricValue, nil } - return 0, fmt.Errorf("no field from the candidate list was found in the metric") + return 0, errors.New("no field from the candidate list was found in the metric") } func contains(set []string, val string) bool { diff --git a/plugins/outputs/azure_monitor/azure_monitor.go b/plugins/outputs/azure_monitor/azure_monitor.go index e6e8fb0c0..9060f4f23 100644 --- a/plugins/outputs/azure_monitor/azure_monitor.go +++ b/plugins/outputs/azure_monitor/azure_monitor.go @@ -145,9 +145,9 @@ func (a *AzureMonitor) Connect() error { } if resourceID == "" { - return fmt.Errorf("no resource ID configured or available via VM instance metadata") + return errors.New("no resource ID configured or available via VM instance metadata") } else if region == "" { - return fmt.Errorf("no region configured or available via VM instance metadata") + return errors.New("no region configured or available via VM instance metadata") } if endpointURL == "" { diff --git a/plugins/outputs/cloud_pubsub/cloud_pubsub.go b/plugins/outputs/cloud_pubsub/cloud_pubsub.go index 764448b63..259ff37b6 100644 --- a/plugins/outputs/cloud_pubsub/cloud_pubsub.go +++ b/plugins/outputs/cloud_pubsub/cloud_pubsub.go @@ -5,6 +5,7 @@ import ( "context" _ "embed" "encoding/base64" + "errors" "fmt" "sync" "time" @@ -258,11 +259,11 @@ func (ps *PubSub) waitForResults(ctx context.Context, cancel context.CancelFunc) func (ps *PubSub) Init() error { if ps.Topic == "" { - return fmt.Errorf(`"topic" is required`) + return errors.New(`"topic" is required`) } if ps.Project == "" { - return fmt.Errorf(`"project" is required`) + return errors.New(`"project" is required`) } switch ps.ContentEncoding { diff --git a/plugins/outputs/cloudwatch_logs/cloudwatch_logs.go b/plugins/outputs/cloudwatch_logs/cloudwatch_logs.go index b69edad54..eb5772a1b 100644 --- a/plugins/outputs/cloudwatch_logs/cloudwatch_logs.go +++ b/plugins/outputs/cloudwatch_logs/cloudwatch_logs.go @@ -4,6 +4,7 @@ package cloudwatch_logs import ( "context" _ "embed" + "errors" "fmt" "sort" "strings" @@ -100,28 +101,28 @@ func (*CloudWatchLogs) SampleConfig() string { // Init initialize plugin with checking configuration parameters func (c *CloudWatchLogs) Init() error { if c.LogGroup == "" { - return fmt.Errorf("log group is not set") + return errors.New("log group is not set") } if c.LogStream == "" { - return fmt.Errorf("log stream is not set") + return errors.New("log stream is not set") } if c.LDMetricName == "" { - return fmt.Errorf("log data metrics name is not set") + return errors.New("log data metrics name is not set") } if c.LDSource == "" { - return fmt.Errorf("log data source is not set") + return errors.New("log data source is not set") } lsSplitArray := strings.Split(c.LDSource, ":") if len(lsSplitArray) != 2 { - return fmt.Errorf("log data source is not properly formatted, ':' is missed.\n" + + return errors.New("log data source is not properly formatted, ':' is missed.\n" + "Should be 'tag:' or 'field:'") } if lsSplitArray[0] != "tag" && lsSplitArray[0] != "field" { - return fmt.Errorf("log data source is not properly formatted.\n" + + return errors.New("log data source is not properly formatted.\n" + "Should be 'tag:' or 'field:'") } diff --git a/plugins/outputs/datadog/datadog.go b/plugins/outputs/datadog/datadog.go index 20009f1bf..64739d25f 100644 --- a/plugins/outputs/datadog/datadog.go +++ b/plugins/outputs/datadog/datadog.go @@ -5,6 +5,7 @@ import ( "bytes" _ "embed" "encoding/json" + "errors" "fmt" "io" "math" @@ -57,7 +58,7 @@ func (*Datadog) SampleConfig() string { func (d *Datadog) Connect() error { if d.Apikey == "" { - return fmt.Errorf("apikey is a required field for datadog output") + return errors.New("apikey is a required field for datadog output") } proxyFunc, err := d.Proxy() diff --git a/plugins/outputs/dynatrace/dynatrace.go b/plugins/outputs/dynatrace/dynatrace.go index bd31389eb..e032a9585 100644 --- a/plugins/outputs/dynatrace/dynatrace.go +++ b/plugins/outputs/dynatrace/dynatrace.go @@ -4,6 +4,7 @@ package dynatrace import ( "bytes" _ "embed" + "errors" "fmt" "io" "net/http" @@ -191,7 +192,7 @@ func (d *Dynatrace) Init() error { } if d.URL != apiconstants.GetDefaultOneAgentEndpoint() && d.APIToken.Empty() { d.Log.Errorf("Dynatrace api_token is a required field for Dynatrace output") - return fmt.Errorf("api_token is a required field for Dynatrace output") + return errors.New("api_token is a required field for Dynatrace output") } tlsCfg, err := d.ClientConfig.TLSConfig() diff --git a/plugins/outputs/elasticsearch/elasticsearch.go b/plugins/outputs/elasticsearch/elasticsearch.go index c639e46eb..1a6f530f4 100644 --- a/plugins/outputs/elasticsearch/elasticsearch.go +++ b/plugins/outputs/elasticsearch/elasticsearch.go @@ -6,6 +6,7 @@ import ( "context" "crypto/sha256" _ "embed" + "errors" "fmt" "math" "net/http" @@ -137,7 +138,7 @@ func (*Elasticsearch) SampleConfig() string { func (a *Elasticsearch) Connect() error { if a.URLs == nil || a.IndexName == "" { - return fmt.Errorf("elasticsearch urls or index_name is not defined") + return errors.New("elasticsearch urls or index_name is not defined") } // Determine if we should process NaN and inf values @@ -333,7 +334,7 @@ func (a *Elasticsearch) Write(metrics []telegraf.Metric) error { func (a *Elasticsearch) manageTemplate(ctx context.Context) error { if a.TemplateName == "" { - return fmt.Errorf("elasticsearch template_name configuration not defined") + return errors.New("elasticsearch template_name configuration not defined") } templateExists, errExists := a.Client.IndexTemplateExists(a.TemplateName).Do(ctx) @@ -353,7 +354,7 @@ func (a *Elasticsearch) manageTemplate(ctx context.Context) error { } if templatePattern == "" { - return fmt.Errorf("template cannot be created for dynamic index names without an index prefix") + return errors.New("template cannot be created for dynamic index names without an index prefix") } if (a.OverwriteTemplate) || (!templateExists) || (templatePattern != "") { diff --git a/plugins/outputs/execd/execd.go b/plugins/outputs/execd/execd.go index 016e3eb0d..f764d142e 100644 --- a/plugins/outputs/execd/execd.go +++ b/plugins/outputs/execd/execd.go @@ -4,6 +4,7 @@ package execd import ( "bufio" _ "embed" + "errors" "fmt" "io" "strings" @@ -41,7 +42,7 @@ func (e *Execd) SetSerializer(s serializers.Serializer) { func (e *Execd) Init() error { if len(e.Command) == 0 { - return fmt.Errorf("no command specified") + return errors.New("no command specified") } var err error diff --git a/plugins/outputs/influxdb/udp_test.go b/plugins/outputs/influxdb/udp_test.go index d6b82f72f..b88b2de80 100644 --- a/plugins/outputs/influxdb/udp_test.go +++ b/plugins/outputs/influxdb/udp_test.go @@ -3,6 +3,7 @@ package influxdb_test import ( "bytes" "context" + "errors" "fmt" "log" "net" @@ -121,8 +122,7 @@ func TestUDP_DialError(t *testing.T) { URL: u, Dialer: &MockDialer{ DialContextF: func(network, address string) (influxdb.Conn, error) { - return nil, fmt.Errorf( - `unsupported scheme [invalid://localhost:9999]: "invalid"`) + return nil, errors.New(`unsupported scheme [invalid://localhost:9999]: "invalid"`) }, }, } @@ -143,8 +143,7 @@ func TestUDP_WriteError(t *testing.T) { DialContextF: func(network, address string) (influxdb.Conn, error) { conn := &MockConn{ WriteF: func(b []byte) (n int, err error) { - return 0, fmt.Errorf( - "write udp 127.0.0.1:52190->127.0.0.1:9999: write: connection refused") + return 0, errors.New("write udp 127.0.0.1:52190->127.0.0.1:9999: write: connection refused") }, CloseF: func() error { closed = true diff --git a/plugins/outputs/influxdb_v2/influxdb_v2.go b/plugins/outputs/influxdb_v2/influxdb_v2.go index 660432f78..23ccdbb7b 100644 --- a/plugins/outputs/influxdb_v2/influxdb_v2.go +++ b/plugins/outputs/influxdb_v2/influxdb_v2.go @@ -118,7 +118,7 @@ func (i *InfluxDB) Write(metrics []telegraf.Metric) error { i.Log.Errorf("When writing to [%s]: %v", client.URL(), err) } - return fmt.Errorf("failed to send metrics to any configured server(s)") + return errors.New("failed to send metrics to any configured server(s)") } func (i *InfluxDB) getHTTPClient(address *url.URL, proxy *url.URL) (Client, error) { diff --git a/plugins/outputs/librato/librato_test.go b/plugins/outputs/librato/librato_test.go index 9eb7036c1..9437850d1 100644 --- a/plugins/outputs/librato/librato_test.go +++ b/plugins/outputs/librato/librato_test.go @@ -1,18 +1,19 @@ package librato import ( - "fmt" + "errors" "net/http" "net/http/httptest" "reflect" "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) var ( @@ -220,7 +221,7 @@ func TestBuildGaugeWithSource(t *testing.T) { MeasureTime: mtime.Unix(), Value: 1.0, }, - fmt.Errorf("undeterminable Source type from Field, hostname"), + errors.New("undeterminable Source type from Field, hostname"), }, { pt3, diff --git a/plugins/outputs/logzio/logzio.go b/plugins/outputs/logzio/logzio.go index 2ec9cb2ff..218502c6b 100644 --- a/plugins/outputs/logzio/logzio.go +++ b/plugins/outputs/logzio/logzio.go @@ -6,6 +6,7 @@ import ( "compress/gzip" _ "embed" "encoding/json" + "errors" "fmt" "net/http" "time" @@ -54,12 +55,12 @@ func (l *Logzio) Connect() error { l.Log.Debug("Connecting to logz.io output...") if l.Token.Empty() { - return fmt.Errorf("token is required") + return errors.New("token is required") } if equal, err := l.Token.EqualTo([]byte("your logz.io token")); err != nil { return err } else if equal { - return fmt.Errorf("please replace 'token' with your actual token") + return errors.New("please replace 'token' with your actual token") } tlsCfg, err := l.ClientConfig.TLSConfig() diff --git a/plugins/outputs/loki/loki.go b/plugins/outputs/loki/loki.go index e93b43c41..e2f226ef8 100644 --- a/plugins/outputs/loki/loki.go +++ b/plugins/outputs/loki/loki.go @@ -6,6 +6,7 @@ import ( "context" _ "embed" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -85,7 +86,7 @@ func (*Loki) SampleConfig() string { func (l *Loki) Connect() (err error) { if l.Domain == "" { - return fmt.Errorf("domain is required") + return errors.New("domain is required") } if l.Endpoint == "" { diff --git a/plugins/outputs/mongodb/mongodb.go b/plugins/outputs/mongodb/mongodb.go index 0b998bdb0..b424c0c1a 100644 --- a/plugins/outputs/mongodb/mongodb.go +++ b/plugins/outputs/mongodb/mongodb.go @@ -4,6 +4,7 @@ package mongodb import ( "context" _ "embed" + "errors" "fmt" "net/url" "strconv" @@ -79,12 +80,12 @@ func (s *MongoDB) Init() error { s.MetricGranularity = "seconds" case "seconds", "minutes", "hours": default: - return fmt.Errorf("invalid time series collection granularity. please specify \"seconds\", \"minutes\", or \"hours\"") + return errors.New("invalid time series collection granularity. please specify \"seconds\", \"minutes\", or \"hours\"") } // do some basic Dsn checks if !strings.HasPrefix(s.Dsn, "mongodb://") && !strings.HasPrefix(s.Dsn, "mongodb+srv://") { - return fmt.Errorf("invalid connection string. expected mongodb://host:port/?{options} or mongodb+srv://host:port/?{options}") + return errors.New("invalid connection string. expected mongodb://host:port/?{options} or mongodb+srv://host:port/?{options}") } if !strings.Contains(s.Dsn[strings.Index(s.Dsn, "://")+3:], "/") { //append '/' to Dsn if its missing s.Dsn = s.Dsn + "/" @@ -96,10 +97,10 @@ func (s *MongoDB) Init() error { switch s.AuthenticationType { case "SCRAM": if s.Username.Empty() { - return fmt.Errorf("SCRAM authentication must specify a username") + return errors.New("SCRAM authentication must specify a username") } if s.Password.Empty() { - return fmt.Errorf("SCRAM authentication must specify a password") + return errors.New("SCRAM authentication must specify a password") } username, err := s.Username.Get() if err != nil { diff --git a/plugins/outputs/newrelic/newrelic.go b/plugins/outputs/newrelic/newrelic.go index d6e68e305..f45198c42 100644 --- a/plugins/outputs/newrelic/newrelic.go +++ b/plugins/outputs/newrelic/newrelic.go @@ -4,6 +4,7 @@ package newrelic import ( "context" _ "embed" + "errors" "fmt" "net/http" "net/url" @@ -42,7 +43,7 @@ func (*NewRelic) SampleConfig() string { // Connect to the Output func (nr *NewRelic) Connect() error { if nr.InsightsKey == "" { - return fmt.Errorf("InsightKey is a required for newrelic") + return errors.New("InsightKey is a required for newrelic") } err := nr.initClient() if err != nil { diff --git a/plugins/outputs/opensearch/opensearch.go b/plugins/outputs/opensearch/opensearch.go index c06224729..3e59ecb05 100644 --- a/plugins/outputs/opensearch/opensearch.go +++ b/plugins/outputs/opensearch/opensearch.go @@ -7,6 +7,7 @@ import ( "crypto/sha256" _ "embed" "encoding/json" + "errors" "fmt" "math" "net/http" @@ -72,7 +73,7 @@ func (*Opensearch) SampleConfig() string { func (o *Opensearch) Init() error { if len(o.URLs) == 0 || o.IndexName == "" { - return fmt.Errorf("opensearch urls or index_name is not defined") + return errors.New("opensearch urls or index_name is not defined") } // Determine if we should process NaN and inf values @@ -109,7 +110,7 @@ func (o *Opensearch) Init() error { } if o.TemplateName == "" { - return fmt.Errorf("template_name configuration not defined") + return errors.New("template_name configuration not defined") } return nil @@ -209,7 +210,7 @@ func (o *Opensearch) Write(metrics []telegraf.Metric) error { // get indexers based on unique pipeline values indexers := getTargetIndexers(metrics, o) if len(indexers) == 0 { - return fmt.Errorf("failed to instantiate OpenSearch bulkindexer") + return errors.New("failed to instantiate OpenSearch bulkindexer") } ctx, cancel := context.WithTimeout(context.Background(), time.Duration(o.Timeout)) @@ -407,7 +408,7 @@ func (o *Opensearch) manageTemplate(ctx context.Context) error { } if templatePattern == "" { - return fmt.Errorf("template cannot be created for dynamic index names without an index prefix") + return errors.New("template cannot be created for dynamic index names without an index prefix") } if o.OverwriteTemplate || !templateExists || templatePattern != "" { diff --git a/plugins/outputs/opentsdb/opentsdb.go b/plugins/outputs/opentsdb/opentsdb.go index e4b7842e0..c1cef28ce 100644 --- a/plugins/outputs/opentsdb/opentsdb.go +++ b/plugins/outputs/opentsdb/opentsdb.go @@ -3,6 +3,7 @@ package opentsdb import ( _ "embed" + "errors" "fmt" "math" "net" @@ -98,7 +99,7 @@ func (o *OpenTSDB) Write(metrics []telegraf.Metric) error { } else if u.Scheme == "http" || u.Scheme == "https" { return o.WriteHTTP(metrics, u) } - return fmt.Errorf("unknown scheme in host parameter") + return errors.New("unknown scheme in host parameter") } func (o *OpenTSDB) WriteHTTP(metrics []telegraf.Metric, u *url.URL) error { @@ -154,7 +155,7 @@ func (o *OpenTSDB) WriteTelnet(metrics []telegraf.Metric, u *url.URL) error { tcpAddr, _ := net.ResolveTCPAddr("tcp", uri) connection, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { - return fmt.Errorf("OpenTSDB: Telnet connect fail") + return errors.New("OpenTSDB: Telnet connect fail") } defer connection.Close() diff --git a/plugins/outputs/postgresql/postgresql.go b/plugins/outputs/postgresql/postgresql.go index e6b1315a3..c4ac48aa7 100644 --- a/plugins/outputs/postgresql/postgresql.go +++ b/plugins/outputs/postgresql/postgresql.go @@ -103,7 +103,7 @@ func newPostgresql() *Postgresql { func (p *Postgresql) Init() error { if p.TagCacheSize < 0 { - return fmt.Errorf("invalid tag_cache_size") + return errors.New("invalid tag_cache_size") } // Set the time-column name @@ -148,7 +148,7 @@ func (p *Postgresql) Init() error { p.dbConfig.ConnConfig.Logger = utils.PGXLogger{Logger: p.Logger} p.dbConfig.ConnConfig.LogLevel, err = pgx.LogLevelFromString(p.LogLevel) if err != nil { - return fmt.Errorf("invalid log level") + return errors.New("invalid log level") } } @@ -157,7 +157,7 @@ func (p *Postgresql) Init() error { case PgUint8: p.dbConfig.AfterConnect = p.registerUint8 default: - return fmt.Errorf("invalid uint64_type") + return errors.New("invalid uint64_type") } return nil diff --git a/plugins/outputs/sensu/sensu.go b/plugins/outputs/sensu/sensu.go index 23ede543b..2981842c3 100644 --- a/plugins/outputs/sensu/sensu.go +++ b/plugins/outputs/sensu/sensu.go @@ -5,6 +5,7 @@ import ( "bytes" _ "embed" "encoding/json" + "errors" "fmt" "io" "math" @@ -373,7 +374,7 @@ func (s *Sensu) getCheck(metricPoints []*OutputMetric) (*OutputCheck, error) { count := len(metricPoints) if s.Check == nil || s.Check.Name == nil { - return &OutputCheck{}, fmt.Errorf("missing check name") + return &OutputCheck{}, errors.New("missing check name") } return &OutputCheck{ diff --git a/plugins/outputs/socket_writer/socket_writer.go b/plugins/outputs/socket_writer/socket_writer.go index d6b11b3df..a07c8c8b1 100644 --- a/plugins/outputs/socket_writer/socket_writer.go +++ b/plugins/outputs/socket_writer/socket_writer.go @@ -12,13 +12,14 @@ import ( "strings" "time" + "github.com/mdlayher/vsock" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" tlsint "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers" - "github.com/mdlayher/vsock" ) //go:embed sample.conf @@ -64,7 +65,7 @@ func (sw *SocketWriter) Connect() error { // Check address string for containing two if len(addrTuple) < 2 { - return fmt.Errorf("CID and/or port number missing") + return errors.New("CID and/or port number missing") } // Parse CID and port number from address string both being 32-bit @@ -75,7 +76,7 @@ func (sw *SocketWriter) Connect() error { } port, _ := strconv.ParseUint(addrTuple[1], 10, 32) if (port >= uint64(math.Pow(2, 32))-1) && (port <= 0) { - return fmt.Errorf("Port number %d is out of range", port) + return fmt.Errorf("port number %d is out of range", port) } c, err = vsock.Dial(uint32(cid), uint32(port), nil) if err != nil { diff --git a/plugins/outputs/stackdriver/stackdriver.go b/plugins/outputs/stackdriver/stackdriver.go index c67cf5bb7..e5475f00d 100644 --- a/plugins/outputs/stackdriver/stackdriver.go +++ b/plugins/outputs/stackdriver/stackdriver.go @@ -4,6 +4,7 @@ package stackdriver import ( "context" _ "embed" + "errors" "fmt" "hash/fnv" "path" @@ -114,7 +115,7 @@ func (*Stackdriver) SampleConfig() string { // Connect initiates the primary connection to the GCP project. func (s *Stackdriver) Connect() error { if s.Project == "" { - return fmt.Errorf("project is a required field for stackdriver output") + return errors.New("project is a required field for stackdriver output") } if s.Namespace == "" { @@ -569,7 +570,7 @@ func (s *Stackdriver) getStackdriverTypedValue(value interface{}) (*monitoringpb func (s *Stackdriver) buildHistogram(m telegraf.Metric) (*monitoringpb.TypedValue, error) { sumInter, ok := m.GetField("sum") if !ok { - return nil, fmt.Errorf("no sum field present") + return nil, errors.New("no sum field present") } sum, err := internal.ToFloat64(sumInter) if err != nil { @@ -579,7 +580,7 @@ func (s *Stackdriver) buildHistogram(m telegraf.Metric) (*monitoringpb.TypedValu countInter, ok := m.GetField("count") if !ok { - return nil, fmt.Errorf("no count field present") + return nil, errors.New("no count field present") } count, err := internal.ToFloat64(countInter) if err != nil { diff --git a/plugins/outputs/timestream/timestream.go b/plugins/outputs/timestream/timestream.go index 2265914b1..8b03b27ff 100644 --- a/plugins/outputs/timestream/timestream.go +++ b/plugins/outputs/timestream/timestream.go @@ -123,11 +123,11 @@ func (*Timestream) SampleConfig() string { func (t *Timestream) Connect() error { if t.DatabaseName == "" { - return fmt.Errorf("DatabaseName key is required") + return errors.New("DatabaseName key is required") } if t.MappingMode == "" { - return fmt.Errorf("MappingMode key is required") + return errors.New("MappingMode key is required") } if t.MappingMode != MappingModeSingleTable && t.MappingMode != MappingModeMultiTable { @@ -171,11 +171,11 @@ func (t *Timestream) Connect() error { if t.CreateTableIfNotExists { if t.CreateTableMagneticStoreRetentionPeriodInDays < 1 { - return fmt.Errorf("if Telegraf should create tables, CreateTableMagneticStoreRetentionPeriodInDays key should have a value greater than 0") + return errors.New("if Telegraf should create tables, CreateTableMagneticStoreRetentionPeriodInDays key should have a value greater than 0") } if t.CreateTableMemoryStoreRetentionPeriodInHours < 1 { - return fmt.Errorf("if Telegraf should create tables, CreateTableMemoryStoreRetentionPeriodInHours key should have a value greater than 0") + return errors.New("if Telegraf should create tables, CreateTableMemoryStoreRetentionPeriodInHours key should have a value greater than 0") } } diff --git a/plugins/outputs/timestream/timestream_test.go b/plugins/outputs/timestream/timestream_test.go index 5e6df4168..5f2dc755e 100644 --- a/plugins/outputs/timestream/timestream_test.go +++ b/plugins/outputs/timestream/timestream_test.go @@ -2,6 +2,7 @@ package timestream import ( "context" + "errors" "fmt" "math" "reflect" @@ -64,7 +65,7 @@ func (m *mockTimestreamClient) DescribeDatabase( *timestreamwrite.DescribeDatabaseInput, ...func(*timestreamwrite.Options), ) (*timestreamwrite.DescribeDatabaseOutput, error) { - return nil, fmt.Errorf("hello from DescribeDatabase") + return nil, errors.New("hello from DescribeDatabase") } func TestConnectValidatesConfigParameters(t *testing.T) { diff --git a/plugins/outputs/wavefront/wavefront.go b/plugins/outputs/wavefront/wavefront.go index 5c978925c..f62906bfe 100644 --- a/plugins/outputs/wavefront/wavefront.go +++ b/plugins/outputs/wavefront/wavefront.go @@ -122,7 +122,7 @@ func (w *Wavefront) Connect() error { sender, err := w.createSender(connectionURL, flushSeconds) if err != nil { - return fmt.Errorf("could not create Wavefront Sender for the provided url") + return errors.New("could not create Wavefront Sender for the provided url") } w.sender = sender diff --git a/plugins/parsers/avro/schema_registry.go b/plugins/parsers/avro/schema_registry.go index 5ca53987d..f76dec0b4 100644 --- a/plugins/parsers/avro/schema_registry.go +++ b/plugins/parsers/avro/schema_registry.go @@ -4,6 +4,7 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -99,7 +100,7 @@ func (sr *schemaRegistry) getSchemaAndCodec(id int) (*schemaAndCodec, error) { schema, ok := jsonResponse["schema"] if !ok { - return nil, fmt.Errorf("malformed response from schema registry: no 'schema' key") + return nil, errors.New("malformed response from schema registry: no 'schema' key") } schemaValue, ok := schema.(string) diff --git a/plugins/parsers/csv/parser.go b/plugins/parsers/csv/parser.go index 8b361e668..c9b86f75f 100644 --- a/plugins/parsers/csv/parser.go +++ b/plugins/parsers/csv/parser.go @@ -91,7 +91,7 @@ func (p *Parser) initializeMetadataSeparators() error { } if len(p.MetadataSeparators) == 0 { - return fmt.Errorf("csv_metadata_separators required when specifying csv_metadata_rows") + return errors.New("csv_metadata_separators required when specifying csv_metadata_rows") } p.metadataSeparatorList = metadataPattern{} @@ -140,7 +140,7 @@ func (p *Parser) Reset() { func (p *Parser) Init() error { if p.HeaderRowCount == 0 && len(p.ColumnNames) == 0 { - return fmt.Errorf("`csv_header_row_count` must be defined if `csv_column_names` is not specified") + return errors.New("`csv_header_row_count` must be defined if `csv_column_names` is not specified") } if p.Delimiter != "" { @@ -160,7 +160,7 @@ func (p *Parser) Init() error { p.gotInitialColumnNames = len(p.ColumnNames) > 0 if len(p.ColumnNames) > 0 && len(p.ColumnTypes) > 0 && len(p.ColumnNames) != len(p.ColumnTypes) { - return fmt.Errorf("csv_column_names field count doesn't match with csv_column_types") + return errors.New("csv_column_names field count doesn't match with csv_column_types") } if err := p.initializeMetadataSeparators(); err != nil { @@ -393,7 +393,7 @@ outer: if len(p.ColumnTypes) > 0 { // Throw error if current column count exceeds defined types. if i >= len(p.ColumnTypes) { - return nil, fmt.Errorf("column type: column count exceeded") + return nil, errors.New("column type: column count exceeded") } var val interface{} @@ -483,7 +483,7 @@ func parseTimestamp(timeFunc func() time.Time, recordFields map[string]interface switch timestampFormat { case "": - return time.Time{}, fmt.Errorf("timestamp format must be specified") + return time.Time{}, errors.New("timestamp format must be specified") default: metricTime, err := internal.ParseTimestamp(timestampFormat, recordFields[timestampColumn], timezone) if err != nil { diff --git a/plugins/parsers/csv/parser_test.go b/plugins/parsers/csv/parser_test.go index 1022bf232..c8e430da8 100644 --- a/plugins/parsers/csv/parser_test.go +++ b/plugins/parsers/csv/parser_test.go @@ -1,7 +1,7 @@ package csv import ( - "fmt" + "errors" "strings" "testing" "time" @@ -144,7 +144,7 @@ func TestTimestampError(t *testing.T) { 23/05/09 04:05:06 PM,70,test_name 07/11/09 04:05:06 PM,80,test_name2` _, err = p.Parse([]byte(testCSV)) - require.Equal(t, fmt.Errorf("timestamp format must be specified"), err) + require.Equal(t, errors.New("timestamp format must be specified"), err) } func TestTimestampUnixFormat(t *testing.T) { diff --git a/plugins/parsers/form_urlencoded/parser.go b/plugins/parsers/form_urlencoded/parser.go index 3aebfd992..2427917aa 100644 --- a/plugins/parsers/form_urlencoded/parser.go +++ b/plugins/parsers/form_urlencoded/parser.go @@ -2,7 +2,7 @@ package form_urlencoded import ( "bytes" - "fmt" + "errors" "net/url" "strconv" "time" @@ -12,7 +12,7 @@ import ( "github.com/influxdata/telegraf/plugins/parsers" ) -var ErrNoMetric = fmt.Errorf("no metric in line") +var ErrNoMetric = errors.New("no metric in line") // Parser decodes "application/x-www-form-urlencoded" data into metrics type Parser struct { diff --git a/plugins/parsers/graphite/parser.go b/plugins/parsers/graphite/parser.go index e2fcf423c..2a0092024 100644 --- a/plugins/parsers/graphite/parser.go +++ b/plugins/parsers/graphite/parser.go @@ -134,7 +134,7 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) { // Check if we have fractional seconds timestamp = time.Unix(int64(unixTime), int64((unixTime-math.Floor(unixTime))*float64(time.Second))) if timestamp.Before(MinDate) || timestamp.After(MaxDate) { - return nil, fmt.Errorf("timestamp out of range") + return nil, errors.New("timestamp out of range") } } } diff --git a/plugins/parsers/grok/parser.go b/plugins/parsers/grok/parser.go index d972be55a..94830a3bd 100644 --- a/plugins/parsers/grok/parser.go +++ b/plugins/parsers/grok/parser.go @@ -3,6 +3,7 @@ package grok import ( "bufio" "bytes" + "errors" "fmt" "os" "regexp" @@ -160,7 +161,7 @@ func (p *Parser) Compile() error { } if len(p.NamedPatterns) == 0 { - return fmt.Errorf("pattern required") + return errors.New("pattern required") } // Combine user-supplied CustomPatterns with DEFAULT_PATTERNS and parse diff --git a/plugins/parsers/influx/influx_upstream/parser.go b/plugins/parsers/influx/influx_upstream/parser.go index 095289f95..4aa7db623 100644 --- a/plugins/parsers/influx/influx_upstream/parser.go +++ b/plugins/parsers/influx/influx_upstream/parser.go @@ -242,9 +242,9 @@ func (sp *StreamParser) SetTimePrecision(u time.Duration) error { case time.Second: sp.precision = lineprotocol.Second case time.Minute: - return fmt.Errorf("time precision 'm' is not supported") + return errors.New("time precision 'm' is not supported") case time.Hour: - return fmt.Errorf("time precision 'h' is not supported") + return errors.New("time precision 'h' is not supported") } return nil diff --git a/plugins/parsers/json/parser.go b/plugins/parsers/json/parser.go index 9df6616e4..4f6bc687a 100644 --- a/plugins/parsers/json/parser.go +++ b/plugins/parsers/json/parser.go @@ -87,12 +87,12 @@ func (p *Parser) parseObject(data map[string]interface{}, timestamp time.Time) ( // if time key is specified, set timestamp to it if p.TimeKey != "" { if p.TimeFormat == "" { - err := fmt.Errorf("use of 'json_time_key' requires 'json_time_format'") + err := errors.New("use of 'json_time_key' requires 'json_time_format'") return nil, err } if f.Fields[p.TimeKey] == nil { - err := fmt.Errorf("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 5e3a64f57..f24e93cd7 100644 --- a/plugins/parsers/json/parser_test.go +++ b/plugins/parsers/json/parser_test.go @@ -1,7 +1,7 @@ package json import ( - "fmt" + "errors" "testing" "time" @@ -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, fmt.Errorf("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 8eaa23624..970de9db6 100644 --- a/plugins/parsers/json_v2/parser.go +++ b/plugins/parsers/json_v2/parser.go @@ -1,6 +1,7 @@ package json_v2 import ( + "errors" "fmt" "io" "strconv" @@ -169,7 +170,7 @@ func (p *Parser) parseCriticalPath(input []byte) ([]telegraf.Metric, error) { } if !result.IsArray() && !result.IsObject() { if c.TimestampFormat == "" { - err := fmt.Errorf("use of 'timestamp_path' requires 'timestamp_format'") + err := errors.New("use of 'timestamp_path' requires 'timestamp_format'") return nil, err } @@ -227,7 +228,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, fmt.Errorf("GJSON path is required") + return nil, errors.New("GJSON path is required") } result := gjson.GetBytes(input, c.Path) if err := p.checkResult(result, c.Path); err != nil { @@ -383,7 +384,7 @@ func (p *Parser) expandArray(result MetricNode, timestamp time.Time) ([]telegraf } else { if p.objectConfig.TimestampKey != "" && result.SetName == p.objectConfig.TimestampKey { if p.objectConfig.TimestampFormat == "" { - err := fmt.Errorf("use of 'timestamp_key' requires 'timestamp_format'") + err := errors.New("use of 'timestamp_key' requires 'timestamp_format'") return nil, err } var loc *time.Location @@ -474,7 +475,7 @@ func (p *Parser) processObjects(input []byte, objects []Object, timestamp time.T p.objectConfig = c if c.Path == "" { - return nil, fmt.Errorf("GJSON path is required") + return nil, errors.New("GJSON path is required") } result := gjson.GetBytes(input, c.Path) @@ -646,7 +647,7 @@ func (p *Parser) isExcluded(key string) bool { } func (p *Parser) ParseLine(_ string) (telegraf.Metric, error) { - return nil, fmt.Errorf("ParseLine is designed for parsing influx line protocol, therefore not implemented for parsing JSON") + return nil, errors.New("ParseLine is designed for parsing influx line protocol, therefore not implemented for parsing JSON") } func (p *Parser) SetDefaultTags(tags map[string]string) { diff --git a/plugins/parsers/prometheus/parser.go b/plugins/parsers/prometheus/parser.go index 389e0819b..8cecbb83a 100644 --- a/plugins/parsers/prometheus/parser.go +++ b/plugins/parsers/prometheus/parser.go @@ -7,10 +7,11 @@ import ( "io" "net/http" - "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/plugins/parsers" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/expfmt" + + "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/plugins/parsers" ) type Parser struct { @@ -72,11 +73,11 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) { } if len(metrics) < 1 { - return nil, fmt.Errorf("no metrics in line") + return nil, errors.New("no metrics in line") } if len(metrics) > 1 { - return nil, fmt.Errorf("more than one metric in line") + return nil, errors.New("more than one metric in line") } return metrics[0], nil diff --git a/plugins/parsers/prometheusremotewrite/parser.go b/plugins/parsers/prometheusremotewrite/parser.go index e096b41b6..1701e0b6d 100644 --- a/plugins/parsers/prometheusremotewrite/parser.go +++ b/plugins/parsers/prometheusremotewrite/parser.go @@ -1,6 +1,7 @@ package prometheusremotewrite import ( + "errors" "fmt" "math" "time" @@ -70,11 +71,11 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) { } if len(metrics) < 1 { - return nil, fmt.Errorf("no metrics in line") + return nil, errors.New("no metrics in line") } if len(metrics) > 1 { - return nil, fmt.Errorf("more than one metric in line") + return nil, errors.New("more than one metric in line") } return metrics[0], nil diff --git a/plugins/parsers/xpath/parser.go b/plugins/parsers/xpath/parser.go index d570f8bea..468402352 100644 --- a/plugins/parsers/xpath/parser.go +++ b/plugins/parsers/xpath/parser.go @@ -212,7 +212,7 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) { } if (len(selectedNodes) < 1 || selectedNodes[0] == nil) && !p.AllowEmptySelection { p.debugEmptyQuery("metric selection", doc, config.Selection) - return metrics, fmt.Errorf("cannot parse with empty selection node") + return metrics, errors.New("cannot parse with empty selection node") } p.Log.Debugf("Number of selected metric nodes: %d", len(selectedNodes)) diff --git a/plugins/parsers/xpath/protocolbuffer_document.go b/plugins/parsers/xpath/protocolbuffer_document.go index 9ccc2ac04..fbecd5b58 100644 --- a/plugins/parsers/xpath/protocolbuffer_document.go +++ b/plugins/parsers/xpath/protocolbuffer_document.go @@ -2,6 +2,7 @@ package xpath import ( "encoding/hex" + "errors" "fmt" "reflect" "sort" @@ -32,10 +33,10 @@ type protobufDocument struct { func (d *protobufDocument) Init() error { // Check the message definition and type if d.MessageDefinition == "" { - return fmt.Errorf("protocol-buffer message-definition not set") + return errors.New("protocol-buffer message-definition not set") } if d.MessageType == "" { - return fmt.Errorf("protocol-buffer message-type not set") + return errors.New("protocol-buffer message-type not set") } // Load the file descriptors from the given protocol-buffer definition diff --git a/plugins/processors/converter/converter.go b/plugins/processors/converter/converter.go index df99ac698..5576d9620 100644 --- a/plugins/processors/converter/converter.go +++ b/plugins/processors/converter/converter.go @@ -4,7 +4,6 @@ package converter import ( _ "embed" "errors" - "fmt" "math" "math/big" "strconv" @@ -79,7 +78,7 @@ func (p *Converter) compile() error { } if tf == nil && ff == nil { - return fmt.Errorf("no filters found") + return errors.New("no filters found") } p.tagConversions = tf diff --git a/plugins/processors/ifname/ifname.go b/plugins/processors/ifname/ifname.go index 5c4f8e0ff..52eb31dda 100644 --- a/plugins/processors/ifname/ifname.go +++ b/plugins/processors/ifname/ifname.go @@ -98,7 +98,7 @@ func (d *IfName) addTag(metric telegraf.Metric) error { num, err := strconv.ParseUint(numS, 10, 64) if err != nil { - return fmt.Errorf("couldn't parse source tag as uint") + return errors.New("couldn't parse source tag as uint") } firstTime := true @@ -212,7 +212,7 @@ func (d *IfName) getMap(agent string) (entry nameMap, age time.Duration, err err if ok { return m, age, nil } - return nil, 0, fmt.Errorf("getting remote table from cache") + return nil, 0, errors.New("getting remote table from cache") } // The cache missed and this is the first request for this @@ -316,7 +316,7 @@ func (d *IfName) buildMap(gs snmp.GosnmpWrapper, tab *si.Table) (nameMap, error) } if len(rtab.Rows) == 0 { - return nil, fmt.Errorf("empty table") + return nil, errors.New("empty table") } t := make(nameMap) @@ -325,11 +325,11 @@ func (d *IfName) buildMap(gs snmp.GosnmpWrapper, tab *si.Table) (nameMap, error) if !ok { //should always have an index tag because the table should //always have IndexAsTag true - return nil, fmt.Errorf("no index tag") + return nil, errors.New("no index tag") } i, err := strconv.ParseUint(iStr, 10, 64) if err != nil { - return nil, fmt.Errorf("index tag isn't a uint") + return nil, errors.New("index tag isn't a uint") } nameIf, ok := v.Fields["ifName"] if !ok { diff --git a/plugins/processors/starlark/starlark.go b/plugins/processors/starlark/starlark.go index a0f88e4c0..b8a197340 100644 --- a/plugins/processors/starlark/starlark.go +++ b/plugins/processors/starlark/starlark.go @@ -3,6 +3,7 @@ package starlark import ( _ "embed" + "errors" "fmt" "go.starlark.net/starlark" @@ -50,7 +51,7 @@ func (s *Starlark) Start(_ telegraf.Accumulator) error { func (s *Starlark) Add(origMetric telegraf.Metric, acc telegraf.Accumulator) error { parameters, found := s.GetParameters("apply") if !found { - return fmt.Errorf("the parameters of the apply function could not be found") + return errors.New("the parameters of the apply function could not be found") } parameters[0].(*common.Metric).Wrap(origMetric) diff --git a/testutil/file.go b/testutil/file.go index 0e22f41e4..086def3a0 100644 --- a/testutil/file.go +++ b/testutil/file.go @@ -2,6 +2,7 @@ package testutil import ( "bufio" + "errors" "fmt" "os" "strings" @@ -17,7 +18,7 @@ type LineParser interface { func ParseRawLinesFrom(lines []string, header string) ([]string, error) { if len(lines) < 2 { // We need a line for HEADER and EMPTY TRAILING LINE - return nil, fmt.Errorf("expected at least two lines to parse from") + return nil, errors.New("expected at least two lines to parse from") } start := -1 for i := range lines { @@ -33,7 +34,7 @@ func ParseRawLinesFrom(lines []string, header string) ([]string, error) { output := make([]string, 0) for _, line := range lines[start:] { if !strings.HasPrefix(strings.TrimLeft(line, "\t "), "#") { - return nil, fmt.Errorf("section does not end with trailing empty line") + return nil, errors.New("section does not end with trailing empty line") } // Stop at empty line @@ -51,7 +52,7 @@ func ParseRawLinesFrom(lines []string, header string) ([]string, error) { func ParseMetricsFrom(lines []string, header string, parser LineParser) ([]telegraf.Metric, error) { if len(lines) < 2 { // We need a line for HEADER and EMPTY TRAILING LINE - return nil, fmt.Errorf("expected at least two lines to parse from") + return nil, errors.New("expected at least two lines to parse from") } start := -1 for i := range lines { @@ -67,7 +68,7 @@ func ParseMetricsFrom(lines []string, header string, parser LineParser) ([]teleg metrics := make([]telegraf.Metric, 0) for _, line := range lines[start:] { if !strings.HasPrefix(strings.TrimLeft(line, "\t "), "#") { - return nil, fmt.Errorf("section does not end with trailing empty line") + return nil, errors.New("section does not end with trailing empty line") } // Stop at empty line diff --git a/tools/package_incus_test/container.go b/tools/package_incus_test/container.go index eedb4eda8..442737b97 100644 --- a/tools/package_incus_test/container.go +++ b/tools/package_incus_test/container.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "math" "path/filepath" @@ -25,7 +26,7 @@ type Container struct { // create container with given name and image func (c *Container) Create(image string) error { if c.Name == "" { - return fmt.Errorf("unable to create container: no name given") + return errors.New("unable to create container: no name given") } c.client = IncusClient{} @@ -292,7 +293,7 @@ func (c *Container) detectPackageManager() error { return nil } - return fmt.Errorf("unable to determine package manager") + return errors.New("unable to determine package manager") } // Configure the system with InfluxData repo @@ -339,5 +340,5 @@ func (c *Container) waitForNetwork() error { attempts++ } - return fmt.Errorf("timeout reached waiting for network on container") + return errors.New("timeout reached waiting for network on container") }