diff --git a/.golangci.yml b/.golangci.yml index 0442c3ff89c76..c2f3fd293a11c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -102,6 +102,7 @@ linters-settings: - dupBranchBody - dupCase - dupSubExpr + - dynamicFmtString - emptyDecl - evalOrder - exitAfterDefer @@ -110,6 +111,7 @@ linters-settings: - regexpPattern - sloppyTypeAssert - sortSlice + - sprintfQuotedString - sqlQuery - uncheckedInlineErr - unnecessaryDefer diff --git a/plugins/inputs/dpdk/dpdk_test.go b/plugins/inputs/dpdk/dpdk_test.go index 7da3c4ce1afa0..dada767f714b2 100644 --- a/plugins/inputs/dpdk/dpdk_test.go +++ b/plugins/inputs/dpdk/dpdk_test.go @@ -238,7 +238,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { t.Run("when 2 ethdev commands are enabled, then 2*numberOfIds new commands should be appended", func(t *testing.T) { mockConn, dpdk, mockAcc := prepareEnvironment() defer mockConn.AssertExpectations(t) - response := fmt.Sprintf(`{"%s": [1, 123]}`, ethdevListCommand) + response := fmt.Sprintf(`{%q: [1, 123]}`, ethdevListCommand) simulateResponse(mockConn, response, nil) expectedCommands := []string{"/ethdev/stats,1", "/ethdev/stats,123", "/ethdev/xstats,1", "/ethdev/xstats,123"} @@ -255,7 +255,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { t.Run("when 1 rawdev command is enabled, then 2*numberOfIds new commands should be appended", func(t *testing.T) { mockConn, dpdk, mockAcc := prepareEnvironment() defer mockConn.AssertExpectations(t) - response := fmt.Sprintf(`{"%s": [1, 123]}`, rawdevListCommand) + response := fmt.Sprintf(`{%q: [1, 123]}`, rawdevListCommand) simulateResponse(mockConn, response, nil) expectedCommands := []string{"/rawdev/xstats,1", "/rawdev/xstats,123"} @@ -271,7 +271,7 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { t.Run("when 2 ethdev commands are enabled but one command is disabled, then numberOfIds new commands should be appended", func(t *testing.T) { mockConn, dpdk, mockAcc := prepareEnvironment() defer mockConn.AssertExpectations(t) - response := fmt.Sprintf(`{"%s": [1, 123]}`, ethdevListCommand) + response := fmt.Sprintf(`{%q: [1, 123]}`, ethdevListCommand) simulateResponse(mockConn, response, nil) expectedCommands := []string{"/ethdev/stats,1", "/ethdev/stats,123"} diff --git a/plugins/inputs/dpdk/dpdk_utils_test.go b/plugins/inputs/dpdk/dpdk_utils_test.go index 0cc98668ecfe7..338d7a8f9b479 100644 --- a/plugins/inputs/dpdk/dpdk_utils_test.go +++ b/plugins/inputs/dpdk/dpdk_utils_test.go @@ -95,7 +95,7 @@ func Test_jsonToArray(t *testing.T) { t.Run("when got numeric array then string array should be returned", func(t *testing.T) { firstValue := int64(0) secondValue := int64(1) - jsonString := fmt.Sprintf(`{"%s": [%d, %d]}`, key, firstValue, secondValue) + jsonString := fmt.Sprintf(`{%q: [%d, %d]}`, key, firstValue, secondValue) arr, err := jsonToArray([]byte(jsonString), key) @@ -120,7 +120,7 @@ func Test_jsonToArray(t *testing.T) { }) t.Run("when valid json with json-object is supplied as input then error should be returned", func(t *testing.T) { - jsonString := fmt.Sprintf(`{"%s": {"testKey": "testValue"}}`, key) + jsonString := fmt.Sprintf(`{%q: {"testKey": "testValue"}}`, key) _, err := jsonToArray([]byte(jsonString), key) diff --git a/plugins/inputs/elasticsearch/elasticsearch.go b/plugins/inputs/elasticsearch/elasticsearch.go index e9279d39fcc07..2d23e4470cb0b 100644 --- a/plugins/inputs/elasticsearch/elasticsearch.go +++ b/plugins/inputs/elasticsearch/elasticsearch.go @@ -4,6 +4,7 @@ package elasticsearch import ( _ "embed" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -204,14 +205,14 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error { // Gather node ID if info.nodeID, err = e.gatherNodeID(s + "/_nodes/_local/name"); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } // get cat/master information here so NodeStats can determine // whether this node is the Master if info.masterID, err = e.getCatMaster(s + "/_cat/master"); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } @@ -233,7 +234,7 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error { // Always gather node stats if err := e.gatherNodeStats(url, acc); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } @@ -243,14 +244,14 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error { url = url + "?level=" + e.ClusterHealthLevel } if err := e.gatherClusterHealth(url, acc); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } } if e.ClusterStats && (e.serverInfo[s].isMaster() || !e.ClusterStatsOnlyFromMaster || !e.Local) { if err := e.gatherClusterStats(s+"/_cluster/stats", acc); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } } @@ -258,12 +259,12 @@ func (e *Elasticsearch) Gather(acc telegraf.Accumulator) error { if len(e.IndicesInclude) > 0 && (e.serverInfo[s].isMaster() || !e.ClusterStatsOnlyFromMaster || !e.Local) { if e.IndicesLevel != "shards" { if err := e.gatherIndicesStats(s+"/"+strings.Join(e.IndicesInclude, ",")+"/_stats", acc); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } } else { if err := e.gatherIndicesStats(s+"/"+strings.Join(e.IndicesInclude, ",")+"/_stats?level=shards", acc); err != nil { - acc.AddError(fmt.Errorf(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) + acc.AddError(errors.New(mask.ReplaceAllString(err.Error(), "http(s)://XXX:XXX@"))) return } } diff --git a/plugins/inputs/intel_dlb/intel_dlb_test.go b/plugins/inputs/intel_dlb/intel_dlb_test.go index 43b87ac7af8b5..3b40ae35f7474 100644 --- a/plugins/inputs/intel_dlb/intel_dlb_test.go +++ b/plugins/inputs/intel_dlb/intel_dlb_test.go @@ -11,11 +11,12 @@ import ( "testing" "time" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/inputs/dpdk/mocks" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" ) func TestDLB_Init(t *testing.T) { @@ -310,7 +311,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) { maxInitMessageLength: 1024, EventdevCommands: []string{"/eventdev/dev_xstats"}, } - response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListCommand) + response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListCommand) simulateResponse(mockConn, response, nil) expectedCommands := []string{"/eventdev/dev_xstats,0", "/eventdev/dev_xstats,1"} @@ -330,7 +331,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) { maxInitMessageLength: 1024, EventdevCommands: []string{"/eventdev/queue_links"}, } - responseDevList := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand) + responseDevList := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand) simulateResponse(mockConn, responseDevList, nil) responseQueueLinks := `{"0": [0]}` simulateResponse(mockConn, responseQueueLinks, nil) @@ -352,7 +353,7 @@ func TestDLB_gatherCommandsWithDeviceIndex(t *testing.T) { maxInitMessageLength: 1024, EventdevCommands: []string{"/eventdev/dev_xstats", "/eventdev/wrong"}, } - response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListCommand) + response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListCommand) mockConn.On("Write", mock.Anything).Return(0, nil).Once() mockConn.On("Read", mock.Anything).Run(func(arg mock.Arguments) { elem := arg.Get(0).([]byte) @@ -443,7 +444,7 @@ func TestDLB_gatherSecondDeviceIndex(t *testing.T) { EventdevCommands: []string{"/eventdev/port_xstats"}, } eventdevListWithSecondIndex := []string{"/eventdev/port_list", "/eventdev/queue_list"} - response := fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListWithSecondIndex[0]) + response := fmt.Sprintf(`{%q: [0, 1]}`, eventdevListWithSecondIndex[0]) simulateResponse(mockConn, response, nil) expectedCommands := []string{"/eventdev/port_xstats,0,0", "/eventdev/port_xstats,0,1"} @@ -468,7 +469,7 @@ func TestDLB_processCommandResult(t *testing.T) { maxInitMessageLength: 1024, EventdevCommands: []string{"/eventdev/dev_xstats"}, } - response := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand) + response := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand) simulateResponse(mockConn, response, nil) response = `{"/eventdev/dev_xstats": {"dev_rx_ok": 0}}` @@ -506,7 +507,7 @@ func TestDLB_processCommandResult(t *testing.T) { rasReader: fileMock, maxInitMessageLength: 1024, } - responseGather := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand) + responseGather := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand) mockConn.On("Write", mock.Anything).Return(0, nil).Twice() mockConn.On("Read", mock.Anything).Run(func(arg mock.Arguments) { elem := arg.Get(0).([]byte) @@ -537,7 +538,7 @@ func TestDLB_processCommandResult(t *testing.T) { Log: testutil.Logger{}, EventdevCommands: []string{"/eventdev/dev_xstats"}, } - response := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand) + response := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand) simulateResponse(mockConn, response, nil) simulateResponse(mockConn, "/wrong/json", nil) @@ -622,7 +623,7 @@ func TestDLB_processCommandResult(t *testing.T) { } mockConn.On("Close").Return(nil) - responseGather := fmt.Sprintf(`{"%s": [0]}`, eventdevListCommand) + responseGather := fmt.Sprintf(`{%q: [0]}`, eventdevListCommand) mockConn.On("Write", mock.Anything).Return(0, nil).Once(). On("Read", mock.Anything).Run(func(arg mock.Arguments) { elem := arg.Get(0).([]byte) @@ -949,7 +950,7 @@ func simulateSocketResponseForGather(socket net.Listener, t *testing.T) { require.NoError(t, err) eventdevListWithSecondIndex := []string{"/eventdev/port_list", "/eventdev/queue_list"} - _, err = conn.Write([]byte(fmt.Sprintf(`{"%s": [0, 1]}`, eventdevListWithSecondIndex[0]))) + _, err = conn.Write([]byte(fmt.Sprintf(`{%q: [0, 1]}`, eventdevListWithSecondIndex[0]))) require.NoError(t, err) } diff --git a/plugins/inputs/intel_rdt/intel_rdt.go b/plugins/inputs/intel_rdt/intel_rdt.go index d29b4075d4443..df056f48d2af3 100644 --- a/plugins/inputs/intel_rdt/intel_rdt.go +++ b/plugins/inputs/intel_rdt/intel_rdt.go @@ -497,7 +497,7 @@ func validateInterval(interval int32) error { func splitMeasurementLine(line string) ([]string, error) { values := strings.Split(line, ",") if len(values) < 8 { - return nil, fmt.Errorf(fmt.Sprintf("not valid line format from pqos: %s", values)) + return nil, fmt.Errorf("not valid line format from pqos: %s", values) } return values, nil } diff --git a/plugins/inputs/stackdriver/stackdriver.go b/plugins/inputs/stackdriver/stackdriver.go index b5474dcf163ed..ca2b12008a80f 100644 --- a/plugins/inputs/stackdriver/stackdriver.go +++ b/plugins/inputs/stackdriver/stackdriver.go @@ -265,7 +265,7 @@ func (s *Stackdriver) newListTimeSeriesFilter(metricType string) string { "has_substring", "one_of", } - filterString := fmt.Sprintf(`metric.type = "%s"`, metricType) + filterString := fmt.Sprintf(`metric.type = %q`, metricType) if s.Filter == nil { return filterString } diff --git a/plugins/outputs/http/http_test.go b/plugins/outputs/http/http_test.go index bfb9281720f12..4418073a9978a 100644 --- a/plugins/outputs/http/http_test.go +++ b/plugins/outputs/http/http_test.go @@ -590,7 +590,7 @@ func TestOAuthAuthorizationCodeGrant(t *testing.T) { }, tokenHandler: func(t *testing.T, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - authHeader := fmt.Sprintf(`{"id_token":"%s"}`, token) + authHeader := fmt.Sprintf(`{"id_token":%q}`, token) _, err = w.Write([]byte(authHeader)) require.NoError(t, err) }, diff --git a/plugins/outputs/influxdb/http.go b/plugins/outputs/influxdb/http.go index 983a33a36e3fb..e6ab041017ce8 100644 --- a/plugins/outputs/influxdb/http.go +++ b/plugins/outputs/influxdb/http.go @@ -208,6 +208,7 @@ func (c *httpClient) Database() string { // Note that some names are not allowed by the server, notably those with // non-printable characters or slashes. func (c *httpClient) CreateDatabase(ctx context.Context, database string) error { + //nolint:gocritic // sprintfQuotedString - "%s" used by purpose, string escaping is done by special function query := fmt.Sprintf(`CREATE DATABASE "%s"`, escapeIdentifier.Replace(database)) req, err := c.makeQueryRequest(query) diff --git a/plugins/outputs/warp10/warp10.go b/plugins/outputs/warp10/warp10.go index 5796a3be4eeec..8f7024bfcf23e 100644 --- a/plugins/outputs/warp10/warp10.go +++ b/plugins/outputs/warp10/warp10.go @@ -4,6 +4,7 @@ package warp10 import ( "bytes" _ "embed" + "errors" "fmt" "io" "math" @@ -142,14 +143,14 @@ func (w *Warp10) Write(metrics []telegraf.Metric) error { if resp.StatusCode != http.StatusOK { if w.PrintErrorBody { body, _ := io.ReadAll(resp.Body) - return fmt.Errorf(w.WarpURL + ": " + w.HandleError(string(body), w.MaxStringErrorSize)) + return errors.New(w.WarpURL + ": " + w.HandleError(string(body), w.MaxStringErrorSize)) } if len(resp.Status) < w.MaxStringErrorSize { - return fmt.Errorf(w.WarpURL + ": " + resp.Status) + return errors.New(w.WarpURL + ": " + resp.Status) } - return fmt.Errorf(w.WarpURL + ": " + resp.Status[0:w.MaxStringErrorSize]) + return errors.New(w.WarpURL + ": " + resp.Status[0:w.MaxStringErrorSize]) } return nil diff --git a/tools/package_lxd_test/container.go b/tools/package_lxd_test/container.go index 0fe093a9546af..822abb04c4fba 100644 --- a/tools/package_lxd_test/container.go +++ b/tools/package_lxd_test/container.go @@ -190,7 +190,7 @@ func (c *Container) configureYum() error { err := c.client.Exec( c.Name, "bash", "-c", "--", - fmt.Sprintf("echo \"%s\" > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo), + fmt.Sprintf("echo %q > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo), ) if err != nil { return err @@ -205,7 +205,7 @@ func (c *Container) configureDnf() error { err := c.client.Exec( c.Name, "bash", "-c", "--", - fmt.Sprintf("echo \"%s\" > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo), + fmt.Sprintf("echo %q > /etc/yum.repos.d/influxdata.repo", influxDataRPMRepo), ) if err != nil { return err @@ -219,7 +219,7 @@ func (c *Container) configureDnf() error { func (c *Container) configureZypper() error { err := c.client.Exec( c.Name, - "echo", fmt.Sprintf("\"%s\"", influxDataRPMRepo), ">", "/etc/zypp/repos.d/influxdata.repo", + "echo", fmt.Sprintf("%q", influxDataRPMRepo), ">", "/etc/zypp/repos.d/influxdata.repo", ) if err != nil { return err diff --git a/tools/package_lxd_test/lxd.go b/tools/package_lxd_test/lxd.go index be4af34605105..1a8b089f03785 100644 --- a/tools/package_lxd_test/lxd.go +++ b/tools/package_lxd_test/lxd.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "errors" "fmt" "os" "strconv" @@ -140,7 +141,7 @@ func (c *LXDClient) Exec(name string, command ...string) error { rc := int(opAPI.Metadata["return"].(float64)) if rc != 0 { - return fmt.Errorf(output.String()) + return errors.New(output.String()) } fmt.Println(output.String()) diff --git a/tools/update_goversion/main.go b/tools/update_goversion/main.go index 75c088fad6316..d1aea547aa20c 100644 --- a/tools/update_goversion/main.go +++ b/tools/update_goversion/main.go @@ -190,32 +190,32 @@ func main() { { FileName: "scripts/installgo_linux.sh", Regex: `(GO_VERSION)=("\d.\d*.\d")`, - Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion), + Replace: fmt.Sprintf("$1=%q", zeroPatchVersion), }, { FileName: "scripts/installgo_mac.sh", Regex: `(GO_VERSION)=("\d.\d*.\d")`, - Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion), + Replace: fmt.Sprintf("$1=%q", zeroPatchVersion), }, { FileName: "scripts/installgo_windows.sh", Regex: `(GO_VERSION)=("\d.\d*.\d")`, - Replace: fmt.Sprintf("$1=\"%s\"", zeroPatchVersion), + Replace: fmt.Sprintf("$1=%q", zeroPatchVersion), }, { FileName: "scripts/installgo_linux.sh", Regex: `(GO_VERSION_SHA)=".*"`, - Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.linux-amd64.tar.gz", zeroPatchVersion)]), + Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.linux-amd64.tar.gz", zeroPatchVersion)]), }, { FileName: "scripts/installgo_mac.sh", Regex: `(GO_VERSION_SHA_arm64)=".*"`, - Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.darwin-arm64.tar.gz", zeroPatchVersion)]), + Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.darwin-arm64.tar.gz", zeroPatchVersion)]), }, { FileName: "scripts/installgo_mac.sh", Regex: `(GO_VERSION_SHA_amd64)=".*"`, - Replace: fmt.Sprintf("$1=\"%s\"", hashes[fmt.Sprintf("go%s.darwin-amd64.tar.gz", zeroPatchVersion)]), + Replace: fmt.Sprintf("$1=%q", hashes[fmt.Sprintf("go%s.darwin-amd64.tar.gz", zeroPatchVersion)]), }, }