diff --git a/internal/process/process.go b/internal/process/process.go index 3f88aac57b317..6da98d211a43b 100644 --- a/internal/process/process.go +++ b/internal/process/process.go @@ -126,12 +126,12 @@ func (p *Process) cmdLoop(ctx context.Context) error { } p.Log.Errorf("Process %s exited: %v", p.Cmd.Path, err) - p.Log.Infof("Restarting in %s...", time.Duration(p.RestartDelay)) + p.Log.Infof("Restarting in %s...", p.RestartDelay) select { case <-ctx.Done(): return nil - case <-time.After(time.Duration(p.RestartDelay)): + case <-time.After(p.RestartDelay): // Continue the loop and restart the process if err := p.cmdStart(); err != nil { return err diff --git a/metric/metric.go b/metric/metric.go index b1a6edcfe91c7..e3b49c3a287fe 100644 --- a/metric/metric.go +++ b/metric/metric.go @@ -297,7 +297,7 @@ func convertField(v interface{}) interface{} { case uint: return uint64(v) case uint64: - return uint64(v) + return v case []byte: return string(v) case int32: @@ -340,7 +340,7 @@ func convertField(v interface{}) interface{} { } case *uint64: if v != nil { - return uint64(*v) + return *v } case *[]byte: if v != nil { diff --git a/plugins/inputs/aliyuncms/aliyuncms.go b/plugins/inputs/aliyuncms/aliyuncms.go index e5ce3824101dc..6aebf99b836fa 100644 --- a/plugins/inputs/aliyuncms/aliyuncms.go +++ b/plugins/inputs/aliyuncms/aliyuncms.go @@ -458,11 +458,11 @@ L: metric.requestDimensions = make([]map[string]string, 0, len(s.discoveryData)) //Preparing tags & dims... - for instanceId, elem := range s.discoveryData { + for instanceID, elem := range s.discoveryData { //Start filing tags //Remove old value if exist - delete(metric.discoveryTags, instanceId) - metric.discoveryTags[instanceId] = make(map[string]string, len(metric.TagsQueryPath)+len(defaulTags)) + delete(metric.discoveryTags, instanceID) + metric.discoveryTags[instanceID] = make(map[string]string, len(metric.TagsQueryPath)+len(defaulTags)) for _, tagQueryPath := range metric.TagsQueryPath { tagKey, tagValue, err := parseTag(tagQueryPath, elem) @@ -471,11 +471,11 @@ L: continue } if err == nil && tagValue == "" { //Nothing found - s.Log.Debugf("Data by query path %q: is not found, for instance %q", tagQueryPath, instanceId) + s.Log.Debugf("Data by query path %q: is not found, for instance %q", tagQueryPath, instanceID) continue } - metric.discoveryTags[instanceId][tagKey] = tagValue + metric.discoveryTags[instanceID][tagKey] = tagValue } //Adding default tags if not already there @@ -489,17 +489,17 @@ L: if err == nil && tagValue == "" { //Nothing found s.Log.Debugf("Data by query path %q: is not found, for instance %q", - defaultTagQP, instanceId) + defaultTagQP, instanceID) continue } - metric.discoveryTags[instanceId][tagKey] = tagValue + metric.discoveryTags[instanceID][tagKey] = tagValue } //Preparing dimensions (first adding dimensions that comes from discovery data) metric.requestDimensions = append( metric.requestDimensions, - map[string]string{s.dimensionKey: instanceId}) + map[string]string{s.dimensionKey: instanceID}) } //Get final dimension (need to get full lis of diff --git a/plugins/inputs/aliyuncms/discovery.go b/plugins/inputs/aliyuncms/discovery.go index 904f9d1948d3e..7e33d7f92c64a 100644 --- a/plugins/inputs/aliyuncms/discovery.go +++ b/plugins/inputs/aliyuncms/discovery.go @@ -60,7 +60,7 @@ type discoveryTool struct { cli map[string]aliyunSdkClient //API client, which perform discovery request respRootKey string //Root key in JSON response where to look for discovery data - respObjectIdKey string //Key in element of array under root key, that stores object ID + respObjectIDKey string //Key in element of array under root key, that stores object ID //for ,majority of cases it would be InstanceId, for OSS it is BucketName. This key is also used in dimension filtering// ) wg sync.WaitGroup //WG for primary discovery goroutine interval time.Duration //Discovery interval @@ -69,9 +69,9 @@ type discoveryTool struct { lg telegraf.Logger //Telegraf logger (should be provided) } -//getRpcReqFromDiscoveryRequest - utility function to map between aliyun request primitives +//getRPCReqFromDiscoveryRequest - utility function to map between aliyun request primitives //discoveryRequest represents different type of discovery requests -func getRpcReqFromDiscoveryRequest(req discoveryRequest) (*requests.RpcRequest, error) { +func getRPCReqFromDiscoveryRequest(req discoveryRequest) (*requests.RpcRequest, error) { if reflect.ValueOf(req).Type().Kind() != reflect.Ptr || reflect.ValueOf(req).IsNil() { return nil, errors.Errorf("Not expected type of the discovery request object: %q, %q", reflect.ValueOf(req).Type(), reflect.ValueOf(req).Kind()) @@ -109,7 +109,7 @@ func NewDiscoveryTool(regions []string, project string, lg telegraf.Logger, cred cli = map[string]aliyunSdkClient{} parseRootKey = regexp.MustCompile(`Describe(.*)`) responseRootKey string - responseObjectIdKey string + responseObjectIDKey string err error noDiscoverySupportErr = errors.Errorf("no discovery support for project %q", project) ) @@ -127,13 +127,13 @@ func NewDiscoveryTool(regions []string, project string, lg telegraf.Logger, cred switch project { case "acs_ecs_dashboard": dscReq[region] = ecs.CreateDescribeInstancesRequest() - responseObjectIdKey = "InstanceId" + responseObjectIDKey = "InstanceId" case "acs_rds_dashboard": dscReq[region] = rds.CreateDescribeDBInstancesRequest() - responseObjectIdKey = "DBInstanceId" + responseObjectIDKey = "DBInstanceId" case "acs_slb_dashboard": dscReq[region] = slb.CreateDescribeLoadBalancersRequest() - responseObjectIdKey = "LoadBalancerId" + responseObjectIDKey = "LoadBalancerId" case "acs_memcache": return nil, noDiscoverySupportErr case "acs_ocs": @@ -152,7 +152,7 @@ func NewDiscoveryTool(regions []string, project string, lg telegraf.Logger, cred //req.InitWithApiInfo("oss", "2014-08-15", "DescribeDBInstances", "oss", "openAPI") case "acs_vpc_eip": dscReq[region] = vpc.CreateDescribeEipAddressesRequest() - responseObjectIdKey = "AllocationId" + responseObjectIDKey = "AllocationId" case "acs_kvstore": return nil, noDiscoverySupportErr case "acs_mns_new": @@ -253,7 +253,7 @@ func NewDiscoveryTool(regions []string, project string, lg telegraf.Logger, cred //Getting response root key (if not set already). This is to be able to parse discovery responses //As they differ per object type //Discovery requests are of the same type per every region, so pick the first one - rpcReq, err := getRpcReqFromDiscoveryRequest(dscReq[regions[0]]) + rpcReq, err := getRPCReqFromDiscoveryRequest(dscReq[regions[0]]) //This means that the discovery request is not of proper type/kind if err != nil { return nil, errors.Errorf("Can't parse rpc request object from discovery request %v", dscReq[regions[0]]) @@ -283,7 +283,7 @@ func NewDiscoveryTool(regions []string, project string, lg telegraf.Logger, cred req: dscReq, cli: cli, respRootKey: responseRootKey, - respObjectIdKey: responseObjectIdKey, + respObjectIDKey: responseObjectIDKey, rateLimit: rateLimit, interval: discoveryInterval, reqDefaultPageSize: 20, @@ -380,8 +380,8 @@ func (dt *discoveryTool) getDiscoveryData(cli aliyunSdkClient, req *requests.Com for _, raw := range discoveryData { if elem, ok := raw.(map[string]interface{}); ok { - if objectId, ok := elem[dt.respObjectIdKey].(string); ok { - preparedData[objectId] = elem + if objectID, ok := elem[dt.respObjectIDKey].(string); ok { + preparedData[objectID] = elem } } else { return nil, errors.Errorf("Can't parse input data element, not a map[string]interface{} type") @@ -407,7 +407,7 @@ func (dt *discoveryTool) getDiscoveryDataAllRegions(limiter chan bool) (map[stri return nil, errors.Errorf("Error building common discovery request: not valid region %q", region) } - rpcReq, err := getRpcReqFromDiscoveryRequest(dscReq) + rpcReq, err := getRPCReqFromDiscoveryRequest(dscReq) if err != nil { return nil, err } diff --git a/plugins/inputs/apcupsd/apcupsd.go b/plugins/inputs/apcupsd/apcupsd.go index a862bbfc881f8..4acadffe38dd2 100644 --- a/plugins/inputs/apcupsd/apcupsd.go +++ b/plugins/inputs/apcupsd/apcupsd.go @@ -15,7 +15,7 @@ import ( const defaultAddress = "tcp://127.0.0.1:3551" -var defaultTimeout = internal.Duration{Duration: time.Duration(time.Second * 5)} +var defaultTimeout = internal.Duration{Duration: time.Second * 5} type ApcUpsd struct { Servers []string diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go index 52f3e6fd59021..e585b6fe0bda7 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go @@ -171,7 +171,7 @@ func (c *CiscoTelemetryMDT) initBgpV4() { c.nxpathMap[key]["aspath"] = "string" } -func (c *CiscoTelemetryMDT) initCpu() { +func (c *CiscoTelemetryMDT) initCPU() { key := "show processes cpu" c.nxpathMap[key] = make(map[string]string, 5) c.nxpathMap[key]["kernel_percent"] = "float" @@ -654,7 +654,7 @@ func (c *CiscoTelemetryMDT) initPimVrf() { c.nxpathMap[key]["table-id"] = "string" } -func (c *CiscoTelemetryMDT) initIpMroute() { +func (c *CiscoTelemetryMDT) initIPMroute() { key := "show ip mroute summary vrf all" c.nxpathMap[key] = make(map[string]string, 40) c.nxpathMap[key]["nat-mode"] = "string" @@ -842,7 +842,7 @@ func (c *CiscoTelemetryMDT) initDb() { c.initPower() c.initMemPhys() c.initBgpV4() - c.initCpu() + c.initCPU() c.initResources() c.initPtpCorrection() c.initTrans() @@ -861,7 +861,7 @@ func (c *CiscoTelemetryMDT) initDb() { c.initPimStats() c.initIntfBrief() c.initPimVrf() - c.initIpMroute() + c.initIPMroute() c.initIpv6Mroute() c.initVpc() c.initBgp() diff --git a/plugins/inputs/cloud_pubsub/pubsub.go b/plugins/inputs/cloud_pubsub/pubsub.go index 41ecf09ec3051..230c459045727 100644 --- a/plugins/inputs/cloud_pubsub/pubsub.go +++ b/plugins/inputs/cloud_pubsub/pubsub.go @@ -180,7 +180,7 @@ func (ps *PubSub) onMessage(ctx context.Context, msg message) error { if err != nil { return fmt.Errorf("unable to base64 decode message: %v", err) } - data = []byte(strData) + data = strData } else { data = msg.Data() } diff --git a/plugins/inputs/couchdb/couchdb.go b/plugins/inputs/couchdb/couchdb.go index 1b542d042dd30..d96c73f836977 100644 --- a/plugins/inputs/couchdb/couchdb.go +++ b/plugins/inputs/couchdb/couchdb.go @@ -125,9 +125,9 @@ func (c *CouchDB) fetchAndInsertData(accumulator telegraf.Accumulator, host stri if c.client == nil { c.client = &http.Client{ Transport: &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, }, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } } @@ -147,7 +147,7 @@ func (c *CouchDB) fetchAndInsertData(accumulator telegraf.Accumulator, host stri defer response.Body.Close() if response.StatusCode != 200 { - return fmt.Errorf("Failed to get stats from couchdb: HTTP responded %d", response.StatusCode) + return fmt.Errorf("failed to get stats from couchdb: HTTP responded %d", response.StatusCode) } stats := Stats{} @@ -287,9 +287,9 @@ func init() { return &CouchDB{ client: &http.Client{ Transport: &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, }, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, }, } }) diff --git a/plugins/inputs/csgo/csgo.go b/plugins/inputs/csgo/csgo.go index 0fa18cab21d43..75cf8a9240099 100644 --- a/plugins/inputs/csgo/csgo.go +++ b/plugins/inputs/csgo/csgo.go @@ -176,15 +176,15 @@ func requestServer(url string, rconPw string) (string, error) { } defer remoteConsole.Close() - reqId, err := remoteConsole.Write("stats") + reqID, err := remoteConsole.Write("stats") if err != nil { return "", err } - resp, respReqId, err := remoteConsole.Read() + resp, respReqID, err := remoteConsole.Read() if err != nil { return "", err - } else if reqId != respReqId { + } else if reqID != respReqID { return "", errors.New("response/request mismatch") } else { return resp, nil diff --git a/plugins/inputs/directory_monitor/directory_monitor_test.go b/plugins/inputs/directory_monitor/directory_monitor_test.go index b9cfbad8df42a..e74a1b27667de 100644 --- a/plugins/inputs/directory_monitor/directory_monitor_test.go +++ b/plugins/inputs/directory_monitor/directory_monitor_test.go @@ -79,7 +79,7 @@ func TestCSVGZImport(t *testing.T) { func TestMultipleJSONFileImports(t *testing.T) { acc := testutil.Accumulator{} - testJsonFile := "test.json" + testJSONFile := "test.json" // Establish process directory and finished directory. finishedDirectory, err := ioutil.TempDir("", "finished") @@ -110,7 +110,7 @@ func TestMultipleJSONFileImports(t *testing.T) { // Let's drop a 5-line LINE-DELIMITED json. // Write csv file to process into the 'process' directory. - f, err := os.Create(filepath.Join(processDirectory, testJsonFile)) + f, err := os.Create(filepath.Join(processDirectory, testJSONFile)) require.NoError(t, err) f.WriteString("{\"Name\": \"event1\",\"Speed\": 100.1,\"Length\": 20.1}\n{\"Name\": \"event2\",\"Speed\": 500,\"Length\": 1.4}\n{\"Name\": \"event3\",\"Speed\": 200,\"Length\": 10.23}\n{\"Name\": \"event4\",\"Speed\": 80,\"Length\": 250}\n{\"Name\": \"event5\",\"Speed\": 120.77,\"Length\": 25.97}") f.Close() diff --git a/plugins/inputs/diskio/diskio_linux.go b/plugins/inputs/diskio/diskio_linux.go index bb11429f1d387..01ca7055e3db4 100644 --- a/plugins/inputs/diskio/diskio_linux.go +++ b/plugins/inputs/diskio/diskio_linux.go @@ -41,8 +41,8 @@ func (d *DiskIO) diskInfo(devName string) (map[string]string, error) { // This allows us to also "poison" it during test scenarios udevDataPath = ic.udevDataPath } else { - major := unix.Major(uint64(stat.Rdev)) - minor := unix.Minor(uint64(stat.Rdev)) + major := unix.Major(uint64(stat.Rdev)) //nolint:unconvert // Conversion needed for some architectures + minor := unix.Minor(uint64(stat.Rdev)) //nolint:unconvert // Conversion needed for some architectures udevDataPath = fmt.Sprintf("/run/udev/data/b%d:%d", major, minor) _, err := os.Stat(udevDataPath) diff --git a/plugins/inputs/docker/docker_test.go b/plugins/inputs/docker/docker_test.go index e6ecce32323f8..c9c19da3c2f6e 100644 --- a/plugins/inputs/docker/docker_test.go +++ b/plugins/inputs/docker/docker_test.go @@ -1136,7 +1136,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { var ( testDate = time.Date(2018, 6, 14, 5, 51, 53, 266176036, time.UTC) - metricCpuTotal = testutil.MustMetric( + metricCPUTotal = testutil.MustMetric( "docker_container_cpu", map[string]string{ "cpu": "cpu-total", @@ -1144,14 +1144,14 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { map[string]interface{}{}, testDate) - metricCpu0 = testutil.MustMetric( + metricCPU0 = testutil.MustMetric( "docker_container_cpu", map[string]string{ "cpu": "cpu0", }, map[string]interface{}{}, testDate) - metricCpu1 = testutil.MustMetric( + metricCPU1 = testutil.MustMetric( "docker_container_cpu", map[string]string{ "cpu": "cpu1", @@ -1218,7 +1218,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { totalInclude: containerMetricClasses, }, expected: []telegraf.Metric{ - metricCpuTotal, metricCpu0, metricCpu1, + metricCPUTotal, metricCPU0, metricCPU1, metricNetworkTotal, metricNetworkEth0, metricNetworkEth1, metricBlkioTotal, metricBlkio6_0, metricBlkio6_1, }, @@ -1231,7 +1231,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { totalInclude: []string{}, }, expected: []telegraf.Metric{ - metricCpu0, metricCpu1, + metricCPU0, metricCPU1, metricNetworkEth0, metricNetworkEth1, metricBlkio6_0, metricBlkio6_1, }, @@ -1243,7 +1243,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { perDeviceInclude: []string{}, totalInclude: containerMetricClasses, }, - expected: []telegraf.Metric{metricCpuTotal, metricNetworkTotal, metricBlkioTotal}, + expected: []telegraf.Metric{metricCPUTotal, metricNetworkTotal, metricBlkioTotal}, }, { name: "Per device and total metrics disabled", diff --git a/plugins/inputs/filecount/filecount_test.go b/plugins/inputs/filecount/filecount_test.go index 2136c348d1d6c..a4c073bf15d80 100644 --- a/plugins/inputs/filecount/filecount_test.go +++ b/plugins/inputs/filecount/filecount_test.go @@ -213,20 +213,20 @@ func getFakeFileSystem(basePath string) fakeFileSystem { var dmask uint32 = 0666 // set directory bit - dmask |= (1 << uint(32-1)) + dmask |= 1 << uint(32-1) // create a lookup map for getting "files" from the "filesystem" fileList := map[string]fakeFileInfo{ - basePath: {name: "testdata", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, - basePath + "/foo": {name: "foo", filemode: uint32(fmask), modtime: mtime}, - basePath + "/bar": {name: "bar", filemode: uint32(fmask), modtime: mtime}, - basePath + "/baz": {name: "baz", filemode: uint32(fmask), modtime: olderMtime}, - basePath + "/qux": {name: "qux", size: int64(400), filemode: uint32(fmask), modtime: mtime}, - basePath + "/subdir": {name: "subdir", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, - basePath + "/subdir/quux": {name: "quux", filemode: uint32(fmask), modtime: mtime}, - basePath + "/subdir/quuz": {name: "quuz", filemode: uint32(fmask), modtime: mtime}, - basePath + "/subdir/nested2": {name: "nested2", size: int64(200), filemode: uint32(dmask), modtime: mtime, isdir: true}, - basePath + "/subdir/nested2/qux": {name: "qux", filemode: uint32(fmask), modtime: mtime, size: int64(400)}, + basePath: {name: "testdata", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true}, + basePath + "/foo": {name: "foo", filemode: fmask, modtime: mtime}, + basePath + "/bar": {name: "bar", filemode: fmask, modtime: mtime}, + basePath + "/baz": {name: "baz", filemode: fmask, modtime: olderMtime}, + basePath + "/qux": {name: "qux", size: int64(400), filemode: fmask, modtime: mtime}, + basePath + "/subdir": {name: "subdir", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true}, + basePath + "/subdir/quux": {name: "quux", filemode: fmask, modtime: mtime}, + basePath + "/subdir/quuz": {name: "quuz", filemode: fmask, modtime: mtime}, + basePath + "/subdir/nested2": {name: "nested2", size: int64(200), filemode: dmask, modtime: mtime, isdir: true}, + basePath + "/subdir/nested2/qux": {name: "qux", filemode: fmask, modtime: mtime, size: int64(400)}, } return fakeFileSystem{files: fileList} diff --git a/plugins/inputs/filecount/filesystem_helpers_test.go b/plugins/inputs/filecount/filesystem_helpers_test.go index 2203500726ba8..b1dacc25bc731 100644 --- a/plugins/inputs/filecount/filesystem_helpers_test.go +++ b/plugins/inputs/filecount/filesystem_helpers_test.go @@ -82,11 +82,11 @@ func getTestFileSystem() fakeFileSystem { var dmask uint32 = 0666 // set directory bit - dmask |= (1 << uint(32-1)) + dmask |= 1 << uint(32-1) fileList := map[string]fakeFileInfo{ - "/testdata": {name: "testdata", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, - "/testdata/foo": {name: "foo", filemode: uint32(fmask), modtime: mtime}, + "/testdata": {name: "testdata", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true}, + "/testdata/foo": {name: "foo", filemode: fmask, modtime: mtime}, } return fakeFileSystem{files: fileList} diff --git a/plugins/inputs/fireboard/fireboard.go b/plugins/inputs/fireboard/fireboard.go index c9a79396ee313..92846a0760cfd 100644 --- a/plugins/inputs/fireboard/fireboard.go +++ b/plugins/inputs/fireboard/fireboard.go @@ -23,10 +23,10 @@ type Fireboard struct { // NewFireboard return a new instance of Fireboard with a default http client func NewFireboard() *Fireboard { - tr := &http.Transport{ResponseHeaderTimeout: time.Duration(3 * time.Second)} + tr := &http.Transport{ResponseHeaderTimeout: 3 * time.Second} client := &http.Client{ Transport: tr, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } return &Fireboard{client: client} } @@ -70,7 +70,7 @@ func (r *Fireboard) Description() string { // Init the things func (r *Fireboard) Init() error { if len(r.AuthToken) == 0 { - return fmt.Errorf("You must specify an authToken") + return fmt.Errorf("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 1d23259fa736b..42a2f1b52c0f6 100644 --- a/plugins/inputs/fluentd/fluentd.go +++ b/plugins/inputs/fluentd/fluentd.go @@ -62,7 +62,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 = fmt.Errorf("processing JSON structure") return } @@ -83,17 +83,17 @@ func (h *Fluentd) SampleConfig() string { return sampleConfig } func (h *Fluentd) Gather(acc telegraf.Accumulator) error { _, err := url.Parse(h.Endpoint) if err != nil { - return fmt.Errorf("Invalid URL \"%s\"", h.Endpoint) + return fmt.Errorf("invalid URL \"%s\"", h.Endpoint) } if h.client == nil { tr := &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, } client := &http.Client{ Transport: tr, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } h.client = client @@ -102,7 +102,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error { resp, err := h.client.Get(h.Endpoint) if err != nil { - return fmt.Errorf("Unable to perform HTTP client GET on \"%s\": %s", h.Endpoint, err) + return fmt.Errorf("unable to perform HTTP client GET on \"%s\": %v", h.Endpoint, err) } defer resp.Body.Close() @@ -110,7 +110,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error { body, err := ioutil.ReadAll(resp.Body) if err != nil { - return fmt.Errorf("Unable to read the HTTP body \"%s\": %s", string(body), err) + return fmt.Errorf("unable to read the HTTP body \"%s\": %v", string(body), err) } if resp.StatusCode != http.StatusOK { @@ -120,7 +120,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error { dataPoints, err := parse(body) if err != nil { - return fmt.Errorf("Problem with parsing") + return fmt.Errorf("problem with parsing") } // Go through all plugins one by one diff --git a/plugins/inputs/fluentd/fluentd_test.go b/plugins/inputs/fluentd/fluentd_test.go index 6279f6cf5ef7e..41166085a8876 100644 --- a/plugins/inputs/fluentd/fluentd_test.go +++ b/plugins/inputs/fluentd/fluentd_test.go @@ -100,8 +100,8 @@ var ( // {"object:f48698", "dummy", "input", nil, nil, nil}, // {"object:e27138", "dummy", "input", nil, nil, nil}, // {"object:d74060", "monitor_agent", "input", nil, nil, nil}, - {"object:11a5e2c", "stdout", "output", (*float64)(&zero), nil, nil}, - {"object:11237ec", "s3", "output", (*float64)(&zero), (*float64)(&zero), (*float64)(&zero)}, + {"object:11a5e2c", "stdout", "output", &zero, nil, nil}, + {"object:11237ec", "s3", "output", &zero, &zero, &zero}, } fluentdTest = &Fluentd{ Endpoint: "http://localhost:8081", diff --git a/plugins/inputs/graylog/graylog.go b/plugins/inputs/graylog/graylog.go index 585a05ee32bea..af19450f1f560 100644 --- a/plugins/inputs/graylog/graylog.go +++ b/plugins/inputs/graylog/graylog.go @@ -128,12 +128,12 @@ func (h *GrayLog) Gather(acc telegraf.Accumulator) error { return err } tr := &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, TLSClientConfig: tlsCfg, } client := &http.Client{ Transport: tr, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } h.client.SetHTTPClient(client) } @@ -233,7 +233,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) { // Prepare URL requestURL, err := url.Parse(serverURL) if err != nil { - return "", -1, fmt.Errorf("Invalid server URL \"%s\"", serverURL) + return "", -1, fmt.Errorf("invalid server URL \"%s\"", serverURL) } // Add X-Requested-By header headers["X-Requested-By"] = "Telegraf" @@ -242,7 +242,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) { m := &Messagebody{Metrics: h.Metrics} httpBody, err := json.Marshal(m) if err != nil { - return "", -1, fmt.Errorf("Invalid list of Metrics %s", h.Metrics) + return "", -1, fmt.Errorf("invalid list of Metrics %s", h.Metrics) } method = "POST" content = bytes.NewBuffer(httpBody) @@ -271,7 +271,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) { // Process response if resp.StatusCode != http.StatusOK { - err = fmt.Errorf("Response from url \"%s\" has status code %d (%s), expected %d (%s)", + err = fmt.Errorf("response from url \"%s\" has status code %d (%s), expected %d (%s)", requestURL.String(), resp.StatusCode, http.StatusText(resp.StatusCode), diff --git a/plugins/inputs/jenkins/jenkins.go b/plugins/inputs/jenkins/jenkins.go index 5844f0e7a8a69..859121cf606ce 100644 --- a/plugins/inputs/jenkins/jenkins.go +++ b/plugins/inputs/jenkins/jenkins.go @@ -427,7 +427,7 @@ type buildResponse struct { } func (b *buildResponse) GetTimestamp() time.Time { - return time.Unix(0, int64(b.Timestamp)*int64(time.Millisecond)) + return time.Unix(0, b.Timestamp*int64(time.Millisecond)) } const ( @@ -501,7 +501,7 @@ func mapResultCode(s string) int { func init() { inputs.Add("jenkins", func() telegraf.Input { return &Jenkins{ - MaxBuildAge: internal.Duration{Duration: time.Duration(time.Hour)}, + MaxBuildAge: internal.Duration{Duration: time.Hour}, MaxConnections: 5, MaxSubJobPerLayer: 10, } diff --git a/plugins/inputs/jolokia/jolokia.go b/plugins/inputs/jolokia/jolokia.go index ed5922ddaa063..6e7a3d5a524fc 100644 --- a/plugins/inputs/jolokia/jolokia.go +++ b/plugins/inputs/jolokia/jolokia.go @@ -160,7 +160,7 @@ func (j *Jolokia) doRequest(req *http.Request) ([]map[string]interface{}, error) // Unmarshal json var jsonOut []map[string]interface{} - if err = json.Unmarshal([]byte(body), &jsonOut); err != nil { + if err = json.Unmarshal(body, &jsonOut); err != nil { return nil, fmt.Errorf("error decoding JSON response: %s: %s", err, body) } diff --git a/plugins/inputs/jti_openconfig_telemetry/collection.go b/plugins/inputs/jti_openconfig_telemetry/collection.go index ffd9019f5f317..d1bad8b30c739 100644 --- a/plugins/inputs/jti_openconfig_telemetry/collection.go +++ b/plugins/inputs/jti_openconfig_telemetry/collection.go @@ -17,7 +17,7 @@ func (a CollectionByKeys) Less(i, j int) bool { return a[i].numKeys < a[j].numKe // Checks to see if there is already a group with these tags and returns its index. Returns -1 if unavailable. func (a CollectionByKeys) IsAvailable(tags map[string]string) *DataGroup { - sort.Sort(CollectionByKeys(a)) + sort.Sort(a) // Iterate through all the groups and see if we have group with these tags for _, group := range a { diff --git a/plugins/inputs/kernel/kernel.go b/plugins/inputs/kernel/kernel.go index 484c819cf7794..404c62d88c2b8 100644 --- a/plugins/inputs/kernel/kernel.go +++ b/plugins/inputs/kernel/kernel.go @@ -53,7 +53,7 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error { fields := make(map[string]interface{}) - fields["entropy_avail"] = int64(entropyValue) + fields["entropy_avail"] = entropyValue dataFields := bytes.Fields(data) for i, field := range dataFields { @@ -63,25 +63,25 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error { if err != nil { return err } - fields["interrupts"] = int64(m) + fields["interrupts"] = m case bytes.Equal(field, contextSwitches): m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) if err != nil { return err } - fields["context_switches"] = int64(m) + fields["context_switches"] = m case bytes.Equal(field, processesForked): m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) if err != nil { return err } - fields["processes_forked"] = int64(m) + fields["processes_forked"] = m case bytes.Equal(field, bootTime): m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) if err != nil { return err } - fields["boot_time"] = int64(m) + fields["boot_time"] = m case bytes.Equal(field, diskPages): in, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) if err != nil { @@ -91,8 +91,8 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error { if err != nil { return err } - fields["disk_pages_in"] = int64(in) - fields["disk_pages_out"] = int64(out) + fields["disk_pages_in"] = in + fields["disk_pages_out"] = out } } diff --git a/plugins/inputs/kernel_vmstat/kernel_vmstat.go b/plugins/inputs/kernel_vmstat/kernel_vmstat.go index 7b0292937b1c0..66e7c7d664748 100644 --- a/plugins/inputs/kernel_vmstat/kernel_vmstat.go +++ b/plugins/inputs/kernel_vmstat/kernel_vmstat.go @@ -45,7 +45,7 @@ func (k *KernelVmstat) Gather(acc telegraf.Accumulator) error { return err } - fields[string(field)] = int64(m) + fields[string(field)] = m } } diff --git a/plugins/inputs/kube_inventory/client.go b/plugins/inputs/kube_inventory/client.go index bc26d1a700ec3..5b53dd1fb98d1 100644 --- a/plugins/inputs/kube_inventory/client.go +++ b/plugins/inputs/kube_inventory/client.go @@ -21,7 +21,6 @@ type client struct { } func newClient(baseURL, namespace, bearerToken string, timeout time.Duration, tlsConfig tls.ClientConfig) (*client, error) { - c, err := kubernetes.NewForConfig(&rest.Config{ TLSClientConfig: rest.TLSClientConfig{ ServerName: baseURL, diff --git a/plugins/inputs/kube_inventory/kube_state.go b/plugins/inputs/kube_inventory/kube_state.go index 0a2a882974e67..6ea5de3525220 100644 --- a/plugins/inputs/kube_inventory/kube_state.go +++ b/plugins/inputs/kube_inventory/kube_state.go @@ -166,7 +166,7 @@ func atoi(s string) int64 { if err != nil { return 0 } - return int64(i) + return i } func convertQuantity(s string, m float64) int64 { diff --git a/plugins/inputs/mailchimp/chimp_api.go b/plugins/inputs/mailchimp/chimp_api.go index b36bbf322cdf7..0e62fccd6d5dd 100644 --- a/plugins/inputs/mailchimp/chimp_api.go +++ b/plugins/inputs/mailchimp/chimp_api.go @@ -124,7 +124,7 @@ func (a *ChimpAPI) GetReport(campaignID string) (Report, error) { func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) { client := &http.Client{ Transport: api.Transport, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } var b bytes.Buffer diff --git a/plugins/inputs/marklogic/marklogic_test.go b/plugins/inputs/marklogic/marklogic_test.go index e6057f6e088af..a809f850ff3b4 100644 --- a/plugins/inputs/marklogic/marklogic_test.go +++ b/plugins/inputs/marklogic/marklogic_test.go @@ -27,7 +27,7 @@ func TestMarklogic(t *testing.T) { ml := &Marklogic{ Hosts: []string{"example1"}, - URL: string(ts.URL), + URL: ts.URL, //Sources: []string{"http://localhost:8002/manage/v2/hosts/hostname1?view=status&format=json"}, } diff --git a/plugins/inputs/mesos/mesos.go b/plugins/inputs/mesos/mesos.go index 7f3d08b118176..1ebbc6bf290d1 100644 --- a/plugins/inputs/mesos/mesos.go +++ b/plugins/inputs/mesos/mesos.go @@ -568,8 +568,8 @@ func (m *Mesos) gatherMainMetrics(u *url.URL, role Role, acc telegraf.Accumulato return err } - if err = json.Unmarshal([]byte(data), &jsonOut); err != nil { - return errors.New("Error decoding JSON response") + if err = json.Unmarshal(data, &jsonOut); err != nil { + return errors.New("error decoding JSON response") } m.filterMetrics(role, &jsonOut) diff --git a/plugins/inputs/nats/nats.go b/plugins/inputs/nats/nats.go index 1afb0046dc3a5..94e1ad74e1d69 100644 --- a/plugins/inputs/nats/nats.go +++ b/plugins/inputs/nats/nats.go @@ -61,7 +61,7 @@ func (n *Nats) Gather(acc telegraf.Accumulator) error { } stats := new(gnatsd.Varz) - err = json.Unmarshal([]byte(bytes), &stats) + err = json.Unmarshal(bytes, &stats) if err != nil { return err } diff --git a/plugins/inputs/neptune_apex/neptune_apex_test.go b/plugins/inputs/neptune_apex/neptune_apex_test.go index 6cca64952637f..86e794575a669 100644 --- a/plugins/inputs/neptune_apex/neptune_apex_test.go +++ b/plugins/inputs/neptune_apex/neptune_apex_test.go @@ -363,7 +363,7 @@ func TestParseXML(t *testing.T) { test := test t.Run(test.name, func(t *testing.T) { var acc testutil.Accumulator - err := n.parseXML(&acc, []byte(test.xmlResponse)) + err := n.parseXML(&acc, test.xmlResponse) if (err != nil) != test.wantErr { t.Errorf("err mismatch. got=%v, want=%t", err, test.wantErr) } diff --git a/plugins/inputs/net_response/net_response.go b/plugins/inputs/net_response/net_response.go index 023b4405e3609..0b092c36d1d73 100644 --- a/plugins/inputs/net_response/net_response.go +++ b/plugins/inputs/net_response/net_response.go @@ -117,7 +117,7 @@ func (n *NetResponse) TCPGather() (tags map[string]string, fields map[string]int } else { // Looking for string in answer RegEx := regexp.MustCompile(`.*` + n.Expect + `.*`) - find := RegEx.FindString(string(data)) + find := RegEx.FindString(data) if find != "" { setResult(Success, fields, tags, n.Expect) } else { @@ -198,10 +198,10 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error { } // Check send and expected string if n.Protocol == "udp" && n.Send == "" { - return errors.New("Send string cannot be empty") + return errors.New("send string cannot be empty") } if n.Protocol == "udp" && n.Expect == "" { - return errors.New("Expected string cannot be empty") + return errors.New("expected string cannot be empty") } // Prepare host and port host, port, err := net.SplitHostPort(n.Address) @@ -212,7 +212,7 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error { n.Address = "localhost:" + port } if port == "" { - return errors.New("Bad port") + return errors.New("bad port") } // Prepare data tags := map[string]string{"server": host, "port": port} @@ -226,7 +226,7 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error { returnTags, fields = n.UDPGather() tags["protocol"] = "udp" } else { - return errors.New("Bad protocol") + return errors.New("bad protocol") } // Merge the tags for k, v := range returnTags { diff --git a/plugins/inputs/net_response/net_response_test.go b/plugins/inputs/net_response/net_response_test.go index a64d553164a45..3bb78b35121a3 100644 --- a/plugins/inputs/net_response/net_response_test.go +++ b/plugins/inputs/net_response/net_response_test.go @@ -38,7 +38,7 @@ func TestBadProtocol(t *testing.T) { // Error err1 := c.Gather(&acc) require.Error(t, err1) - assert.Equal(t, "Bad protocol", err1.Error()) + assert.Equal(t, "bad protocol", err1.Error()) } func TestNoPort(t *testing.T) { @@ -49,7 +49,7 @@ func TestNoPort(t *testing.T) { } err1 := c.Gather(&acc) require.Error(t, err1) - assert.Equal(t, "Bad port", err1.Error()) + assert.Equal(t, "bad port", err1.Error()) } func TestAddressOnly(t *testing.T) { @@ -79,10 +79,10 @@ func TestSendExpectStrings(t *testing.T) { } err1 := tc.Gather(&acc) require.Error(t, err1) - assert.Equal(t, "Send string cannot be empty", err1.Error()) + assert.Equal(t, "send string cannot be empty", err1.Error()) err2 := uc.Gather(&acc) require.Error(t, err2) - assert.Equal(t, "Expected string cannot be empty", err2.Error()) + assert.Equal(t, "expected string cannot be empty", err2.Error()) } func TestTCPError(t *testing.T) { diff --git a/plugins/inputs/nfsclient/nfsclient_test.go b/plugins/inputs/nfsclient/nfsclient_test.go index 4dab7b320f0c5..11a9e4dd37f08 100644 --- a/plugins/inputs/nfsclient/nfsclient_test.go +++ b/plugins/inputs/nfsclient/nfsclient_test.go @@ -26,7 +26,7 @@ func TestNFSClientParsev3(t *testing.T) { data := strings.Fields(" READLINK: 500 501 502 503 504 505 506 507") nfsclient.parseStat("1.2.3.4:/storage/NFS", "/A", "3", data, &acc) - fields_ops := map[string]interface{}{ + fieldsOps := map[string]interface{}{ "ops": int64(500), "trans": int64(501), "timeouts": int64(502), @@ -36,7 +36,7 @@ func TestNFSClientParsev3(t *testing.T) { "response_time": int64(506), "total_time": int64(507), } - acc.AssertContainsFields(t, "nfs_ops", fields_ops) + acc.AssertContainsFields(t, "nfs_ops", fieldsOps) } func TestNFSClientParsev4(t *testing.T) { @@ -48,7 +48,7 @@ func TestNFSClientParsev4(t *testing.T) { data := strings.Fields(" DESTROY_SESSION: 500 501 502 503 504 505 506 507") nfsclient.parseStat("2.2.2.2:/nfsdata/", "/B", "4", data, &acc) - fields_ops := map[string]interface{}{ + fieldsOps := map[string]interface{}{ "ops": int64(500), "trans": int64(501), "timeouts": int64(502), @@ -58,7 +58,7 @@ func TestNFSClientParsev4(t *testing.T) { "response_time": int64(506), "total_time": int64(507), } - acc.AssertContainsFields(t, "nfs_ops", fields_ops) + acc.AssertContainsFields(t, "nfs_ops", fieldsOps) } func TestNFSClientProcessStat(t *testing.T) { @@ -74,7 +74,7 @@ func TestNFSClientProcessStat(t *testing.T) { nfsclient.processText(scanner, &acc) - fields_readstat := map[string]interface{}{ + fieldsReadstat := map[string]interface{}{ "ops": int64(600), "retrans": int64(1), "bytes": int64(1207), @@ -82,15 +82,15 @@ func TestNFSClientProcessStat(t *testing.T) { "exe": int64(607), } - read_tags := map[string]string{ + readTags := map[string]string{ "serverexport": "1.2.3.4:/storage/NFS", "mountpoint": "/A", "operation": "READ", } - acc.AssertContainsTaggedFields(t, "nfsstat", fields_readstat, read_tags) + acc.AssertContainsTaggedFields(t, "nfsstat", fieldsReadstat, readTags) - fields_writestat := map[string]interface{}{ + fieldsWritestat := map[string]interface{}{ "ops": int64(700), "retrans": int64(1), "bytes": int64(1407), @@ -98,12 +98,12 @@ func TestNFSClientProcessStat(t *testing.T) { "exe": int64(707), } - write_tags := map[string]string{ + writeTags := map[string]string{ "serverexport": "1.2.3.4:/storage/NFS", "mountpoint": "/A", "operation": "WRITE", } - acc.AssertContainsTaggedFields(t, "nfsstat", fields_writestat, write_tags) + acc.AssertContainsTaggedFields(t, "nfsstat", fieldsWritestat, writeTags) } func TestNFSClientProcessFull(t *testing.T) { @@ -119,7 +119,7 @@ func TestNFSClientProcessFull(t *testing.T) { nfsclient.processText(scanner, &acc) - fields_events := map[string]interface{}{ + fieldsEvents := map[string]interface{}{ "inoderevalidates": int64(301736), "dentryrevalidates": int64(22838), "datainvalidates": int64(410979), @@ -148,7 +148,7 @@ func TestNFSClientProcessFull(t *testing.T) { "pnfsreads": int64(0), "pnfswrites": int64(0), } - fields_bytes := map[string]interface{}{ + fieldsBytes := map[string]interface{}{ "normalreadbytes": int64(204440464584), "normalwritebytes": int64(110857586443), "directreadbytes": int64(783170354688), @@ -158,7 +158,7 @@ func TestNFSClientProcessFull(t *testing.T) { "readpages": int64(85749323), "writepages": int64(30784819), } - fields_xprt_tcp := map[string]interface{}{ + fieldsXprtTCP := map[string]interface{}{ "bind_count": int64(1), "connect_count": int64(1), "connect_time": int64(0), @@ -170,7 +170,7 @@ func TestNFSClientProcessFull(t *testing.T) { "backlogutil": int64(0), } - acc.AssertContainsFields(t, "nfs_events", fields_events) - acc.AssertContainsFields(t, "nfs_bytes", fields_bytes) - acc.AssertContainsFields(t, "nfs_xprt_tcp", fields_xprt_tcp) + acc.AssertContainsFields(t, "nfs_events", fieldsEvents) + acc.AssertContainsFields(t, "nfs_bytes", fieldsBytes) + acc.AssertContainsFields(t, "nfs_xprt_tcp", fieldsXprtTCP) } diff --git a/plugins/inputs/nsq/nsq.go b/plugins/inputs/nsq/nsq.go index 166444f857050..681c2f6e7f460 100644 --- a/plugins/inputs/nsq/nsq.go +++ b/plugins/inputs/nsq/nsq.go @@ -111,7 +111,7 @@ func (n *NSQ) getHTTPClient() (*http.Client, error) { } httpClient := &http.Client{ Transport: tr, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } return httpClient, nil } @@ -123,7 +123,7 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error { } r, err := n.httpClient.Get(u.String()) if err != nil { - return fmt.Errorf("Error while polling %s: %s", u.String(), err) + return fmt.Errorf("error while polling %s: %s", u.String(), err) } defer r.Body.Close() @@ -133,20 +133,20 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error { body, err := ioutil.ReadAll(r.Body) if err != nil { - return fmt.Errorf(`Error reading body: %s`, err) + return fmt.Errorf(`error reading body: %s`, err) } data := &NSQStatsData{} err = json.Unmarshal(body, data) if err != nil { - return fmt.Errorf(`Error parsing response: %s`, err) + return fmt.Errorf(`error parsing response: %s`, err) } // Data was not parsed correctly attempt to use old format. if len(data.Version) < 1 { wrapper := &NSQStats{} err = json.Unmarshal(body, wrapper) if err != nil { - return fmt.Errorf(`Error parsing response: %s`, err) + return fmt.Errorf(`error parsing response: %s`, err) } data = &wrapper.Data } @@ -176,7 +176,7 @@ func buildURL(e string) (*url.URL, error) { u := fmt.Sprintf(requestPattern, e) addr, err := url.Parse(u) if err != nil { - return nil, fmt.Errorf("Unable to parse address '%s': %s", u, err) + return nil, fmt.Errorf("unable to parse address '%s': %s", u, err) } return addr, nil } diff --git a/plugins/inputs/openntpd/openntpd.go b/plugins/inputs/openntpd/openntpd.go index aedff242e9f07..b4a35fb55b8d7 100644 --- a/plugins/inputs/openntpd/openntpd.go +++ b/plugins/inputs/openntpd/openntpd.go @@ -126,8 +126,8 @@ func (n *Openntpd) Gather(acc telegraf.Accumulator) error { fields = strings.Fields(line) // if there is an ntpctl state prefix, remove it and make it it's own tag - if strings.ContainsAny(string(fields[0]), "*") { - tags["state_prefix"] = string(fields[0]) + if strings.ContainsAny(fields[0], "*") { + tags["state_prefix"] = fields[0] fields = fields[1:] } diff --git a/plugins/inputs/prometheus/kubernetes.go b/plugins/inputs/prometheus/kubernetes.go index d42e98dd7813b..941dada56cd5c 100644 --- a/plugins/inputs/prometheus/kubernetes.go +++ b/plugins/inputs/prometheus/kubernetes.go @@ -32,7 +32,7 @@ type podMetadata struct { type podResponse struct { Kind string `json:"kind"` - ApiVersion string `json:"apiVersion"` + APIVersion string `json:"apiVersion"` Metadata podMetadata `json:"metadata"` Items []*corev1.Pod `json:"items,string,omitempty"` } @@ -58,13 +58,13 @@ func loadClient(kubeconfigPath string) (*kubernetes.Clientset, error) { func (p *Prometheus) start(ctx context.Context) error { config, err := rest.InClusterConfig() if err != nil { - return fmt.Errorf("Failed to get InClusterConfig - %v", err) + return fmt.Errorf("failed to get InClusterConfig - %v", err) } client, err := kubernetes.NewForConfig(config) if err != nil { u, err := user.Current() if err != nil { - return fmt.Errorf("Failed to get current user - %v", err) + return fmt.Errorf("failed to get current user - %v", err) } configLocation := filepath.Join(u.HomeDir, ".kube/config") @@ -150,13 +150,13 @@ func (p *Prometheus) cAdvisor(ctx context.Context) error { podsURL := fmt.Sprintf("https://%s:10250/pods", p.NodeIP) req, err := http.NewRequest("GET", podsURL, nil) if err != nil { - return fmt.Errorf("Error when creating request to %s to get pod list: %w", podsURL, err) + return fmt.Errorf("error when creating request to %s to get pod list: %w", podsURL, err) } // Update right away so code is not waiting the length of the specified scrape interval initially err = updateCadvisorPodList(p, req) if err != nil { - return fmt.Errorf("Error initially updating pod list: %w", err) + return fmt.Errorf("error initially updating pod list: %w", err) } scrapeInterval := cAdvisorPodListDefaultInterval @@ -171,7 +171,7 @@ func (p *Prometheus) cAdvisor(ctx context.Context) error { case <-time.After(time.Duration(scrapeInterval) * time.Second): err := updateCadvisorPodList(p, req) if err != nil { - return fmt.Errorf("Error updating pod list: %w", err) + return fmt.Errorf("error updating pod list: %w", err) } } } @@ -183,12 +183,12 @@ func updateCadvisorPodList(p *Prometheus, req *http.Request) error { resp, err := httpClient.Do(req) if err != nil { - return fmt.Errorf("Error when making request for pod list: %w", err) + return fmt.Errorf("error when making request for pod list: %w", err) } // If err is nil, still check response code if resp.StatusCode != 200 { - return fmt.Errorf("Error when making request for pod list with status %s", resp.Status) + return fmt.Errorf("error when making request for pod list with status %s", resp.Status) } defer resp.Body.Close() diff --git a/plugins/inputs/raindrops/raindrops.go b/plugins/inputs/raindrops/raindrops.go index 5973390e94a82..904d5418ec8db 100644 --- a/plugins/inputs/raindrops/raindrops.go +++ b/plugins/inputs/raindrops/raindrops.go @@ -39,7 +39,7 @@ func (r *Raindrops) Gather(acc telegraf.Accumulator) error { for _, u := range r.Urls { addr, err := url.Parse(u) if err != nil { - acc.AddError(fmt.Errorf("Unable to parse address '%s': %s", u, err)) + acc.AddError(fmt.Errorf("unable to parse address '%s': %s", u, err)) continue } @@ -178,9 +178,9 @@ func init() { inputs.Add("raindrops", func() telegraf.Input { return &Raindrops{httpClient: &http.Client{ Transport: &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, }, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, }} }) } diff --git a/plugins/inputs/raindrops/raindrops_test.go b/plugins/inputs/raindrops/raindrops_test.go index 2fed0a35a9af8..f8b766101b189 100644 --- a/plugins/inputs/raindrops/raindrops_test.go +++ b/plugins/inputs/raindrops/raindrops_test.go @@ -62,7 +62,7 @@ func TestRaindropsGeneratesMetrics(t *testing.T) { n := &Raindrops{ Urls: []string{fmt.Sprintf("%s/_raindrops", ts.URL)}, httpClient: &http.Client{Transport: &http.Transport{ - ResponseHeaderTimeout: time.Duration(3 * time.Second), + ResponseHeaderTimeout: 3 * time.Second, }}, } diff --git a/plugins/inputs/ravendb/ravendb.go b/plugins/inputs/ravendb/ravendb.go index 42b50d0d3816f..f246bd8e97689 100644 --- a/plugins/inputs/ravendb/ravendb.go +++ b/plugins/inputs/ravendb/ravendb.go @@ -40,10 +40,10 @@ type RavenDB struct { Log telegraf.Logger `toml:"-"` client *http.Client - requestUrlServer string - requestUrlDatabases string - requestUrlIndexes string - requestUrlCollection string + requestURLServer string + requestURLDatabases string + requestURLIndexes string + requestURLCollection string } var sampleConfig = ` @@ -168,20 +168,20 @@ func (r *RavenDB) requestJSON(u string, target interface{}) error { func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { serverResponse := &serverMetricsResponse{} - err := r.requestJSON(r.requestUrlServer, &serverResponse) + err := r.requestJSON(r.requestURLServer, &serverResponse) if err != nil { acc.AddError(err) return } tags := map[string]string{ - "cluster_id": serverResponse.Cluster.Id, + "cluster_id": serverResponse.Cluster.ID, "node_tag": serverResponse.Cluster.NodeTag, "url": r.URL, } - if serverResponse.Config.PublicServerUrl != nil { - tags["public_server_url"] = *serverResponse.Config.PublicServerUrl + if serverResponse.Config.PublicServerURL != nil { + tags["public_server_url"] = *serverResponse.Config.PublicServerURL } fields := map[string]interface{}{ @@ -192,13 +192,13 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { "cluster_index": serverResponse.Cluster.Index, "cluster_node_state": serverResponse.Cluster.NodeState, "config_server_urls": strings.Join(serverResponse.Config.ServerUrls, ";"), - "cpu_assigned_processor_count": serverResponse.Cpu.AssignedProcessorCount, - "cpu_machine_io_wait": serverResponse.Cpu.MachineIoWait, - "cpu_machine_usage": serverResponse.Cpu.MachineUsage, - "cpu_process_usage": serverResponse.Cpu.ProcessUsage, - "cpu_processor_count": serverResponse.Cpu.ProcessorCount, - "cpu_thread_pool_available_worker_threads": serverResponse.Cpu.ThreadPoolAvailableWorkerThreads, - "cpu_thread_pool_available_completion_port_threads": serverResponse.Cpu.ThreadPoolAvailableCompletionPortThreads, + "cpu_assigned_processor_count": serverResponse.CPU.AssignedProcessorCount, + "cpu_machine_io_wait": serverResponse.CPU.MachineIoWait, + "cpu_machine_usage": serverResponse.CPU.MachineUsage, + "cpu_process_usage": serverResponse.CPU.ProcessUsage, + "cpu_processor_count": serverResponse.CPU.ProcessorCount, + "cpu_thread_pool_available_worker_threads": serverResponse.CPU.ThreadPoolAvailableWorkerThreads, + "cpu_thread_pool_available_completion_port_threads": serverResponse.CPU.ThreadPoolAvailableCompletionPortThreads, "databases_loaded_count": serverResponse.Databases.LoadedCount, "databases_total_count": serverResponse.Databases.TotalCount, "disk_remaining_storage_space_percentage": serverResponse.Disk.RemainingStorageSpacePercentage, @@ -208,7 +208,7 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { "license_expiration_left_in_sec": serverResponse.License.ExpirationLeftInSec, "license_max_cores": serverResponse.License.MaxCores, "license_type": serverResponse.License.Type, - "license_utilized_cpu_cores": serverResponse.License.UtilizedCpuCores, + "license_utilized_cpu_cores": serverResponse.License.UtilizedCPUCores, "memory_allocated_in_mb": serverResponse.Memory.AllocatedMemoryInMb, "memory_installed_in_mb": serverResponse.Memory.InstalledMemoryInMb, "memory_low_memory_severity": serverResponse.Memory.LowMemorySeverity, @@ -221,20 +221,20 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { "network_last_authorized_non_cluster_admin_request_time_in_sec": serverResponse.Network.LastAuthorizedNonClusterAdminRequestTimeInSec, "network_last_request_time_in_sec": serverResponse.Network.LastRequestTimeInSec, "network_requests_per_sec": serverResponse.Network.RequestsPerSec, - "network_tcp_active_connections": serverResponse.Network.TcpActiveConnections, + "network_tcp_active_connections": serverResponse.Network.TCPActiveConnections, "network_total_requests": serverResponse.Network.TotalRequests, "server_full_version": serverResponse.ServerFullVersion, - "server_process_id": serverResponse.ServerProcessId, + "server_process_id": serverResponse.ServerProcessID, "server_version": serverResponse.ServerVersion, "uptime_in_sec": serverResponse.UpTimeInSec, } - if serverResponse.Config.TcpServerUrls != nil { - fields["config_tcp_server_urls"] = strings.Join(serverResponse.Config.TcpServerUrls, ";") + if serverResponse.Config.TCPServerURLs != nil { + fields["config_tcp_server_urls"] = strings.Join(serverResponse.Config.TCPServerURLs, ";") } - if serverResponse.Config.PublicTcpServerUrls != nil { - fields["config_public_tcp_server_urls"] = strings.Join(serverResponse.Config.PublicTcpServerUrls, ";") + if serverResponse.Config.PublicTCPServerURLs != nil { + fields["config_public_tcp_server_urls"] = strings.Join(serverResponse.Config.PublicTCPServerURLs, ";") } if serverResponse.Certificate.WellKnownAdminCertificates != nil { @@ -247,7 +247,7 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) { databasesResponse := &databasesMetricResponse{} - err := r.requestJSON(r.requestUrlDatabases, &databasesResponse) + err := r.requestJSON(r.requestURLDatabases, &databasesResponse) if err != nil { acc.AddError(err) return @@ -255,14 +255,14 @@ func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) { for _, dbResponse := range databasesResponse.Results { tags := map[string]string{ - "database_id": dbResponse.DatabaseId, + "database_id": dbResponse.DatabaseID, "database_name": dbResponse.DatabaseName, "node_tag": databasesResponse.NodeTag, "url": r.URL, } - if databasesResponse.PublicServerUrl != nil { - tags["public_server_url"] = *databasesResponse.PublicServerUrl + if databasesResponse.PublicServerURL != nil { + tags["public_server_url"] = *databasesResponse.PublicServerURL } fields := map[string]interface{}{ @@ -306,7 +306,7 @@ func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) { func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) { indexesResponse := &indexesMetricResponse{} - err := r.requestJSON(r.requestUrlIndexes, &indexesResponse) + err := r.requestJSON(r.requestURLIndexes, &indexesResponse) if err != nil { acc.AddError(err) return @@ -321,8 +321,8 @@ func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) { "url": r.URL, } - if indexesResponse.PublicServerUrl != nil { - tags["public_server_url"] = *indexesResponse.PublicServerUrl + if indexesResponse.PublicServerURL != nil { + tags["public_server_url"] = *indexesResponse.PublicServerURL } fields := map[string]interface{}{ @@ -347,7 +347,7 @@ func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) { func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) { collectionsResponse := &collectionsMetricResponse{} - err := r.requestJSON(r.requestUrlCollection, &collectionsResponse) + err := r.requestJSON(r.requestURLCollection, &collectionsResponse) if err != nil { acc.AddError(err) return @@ -362,8 +362,8 @@ func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) { "url": r.URL, } - if collectionsResponse.PublicServerUrl != nil { - tags["public_server_url"] = *collectionsResponse.PublicServerUrl + if collectionsResponse.PublicServerURL != nil { + tags["public_server_url"] = *collectionsResponse.PublicServerURL } fields := map[string]interface{}{ @@ -379,7 +379,7 @@ func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) { } } -func prepareDbNamesUrlPart(dbNames []string) string { +func prepareDBNamesURLPart(dbNames []string) string { if len(dbNames) == 0 { return "" } @@ -396,10 +396,10 @@ func (r *RavenDB) Init() error { r.URL = defaultURL } - r.requestUrlServer = r.URL + "/admin/monitoring/v1/server" - r.requestUrlDatabases = r.URL + "/admin/monitoring/v1/databases" + prepareDbNamesUrlPart(r.DbStatsDbs) - r.requestUrlIndexes = r.URL + "/admin/monitoring/v1/indexes" + prepareDbNamesUrlPart(r.IndexStatsDbs) - r.requestUrlCollection = r.URL + "/admin/monitoring/v1/collections" + prepareDbNamesUrlPart(r.IndexStatsDbs) + r.requestURLServer = r.URL + "/admin/monitoring/v1/server" + r.requestURLDatabases = r.URL + "/admin/monitoring/v1/databases" + prepareDBNamesURLPart(r.DbStatsDbs) + r.requestURLIndexes = r.URL + "/admin/monitoring/v1/indexes" + prepareDBNamesURLPart(r.IndexStatsDbs) + r.requestURLCollection = r.URL + "/admin/monitoring/v1/collections" + prepareDBNamesURLPart(r.IndexStatsDbs) err := choice.CheckSlice(r.StatsInclude, []string{"server", "databases", "indexes", "collections"}) if err != nil { diff --git a/plugins/inputs/ravendb/ravendb_dto.go b/plugins/inputs/ravendb/ravendb_dto.go index af4012f8ceecd..87ae34dccc541 100644 --- a/plugins/inputs/ravendb/ravendb_dto.go +++ b/plugins/inputs/ravendb/ravendb_dto.go @@ -4,10 +4,10 @@ type serverMetricsResponse struct { ServerVersion string `json:"ServerVersion"` ServerFullVersion string `json:"ServerFullVersion"` UpTimeInSec int32 `json:"UpTimeInSec"` - ServerProcessId int32 `json:"ServerProcessId"` + ServerProcessID int32 `json:"ServerProcessId"` Backup backupMetrics `json:"Backup"` Config configurationMetrics `json:"Config"` - Cpu cpuMetrics `json:"Cpu"` + CPU cpuMetrics `json:"Cpu"` Memory memoryMetrics `json:"Memory"` Disk diskMetrics `json:"Disk"` License licenseMetrics `json:"License"` @@ -24,9 +24,9 @@ type backupMetrics struct { type configurationMetrics struct { ServerUrls []string `json:"ServerUrls"` - PublicServerUrl *string `json:"PublicServerUrl"` - TcpServerUrls []string `json:"TcpServerUrls"` - PublicTcpServerUrls []string `json:"PublicTcpServerUrls"` + PublicServerURL *string `json:"PublicServerUrl"` + TCPServerURLs []string `json:"TcpServerUrls"` + PublicTCPServerURLs []string `json:"PublicTcpServerUrls"` } type cpuMetrics struct { @@ -60,12 +60,12 @@ type diskMetrics struct { type licenseMetrics struct { Type string `json:"Type"` ExpirationLeftInSec *float64 `json:"ExpirationLeftInSec"` - UtilizedCpuCores int32 `json:"UtilizedCpuCores"` + UtilizedCPUCores int32 `json:"UtilizedCpuCores"` MaxCores int32 `json:"MaxCores"` } type networkMetrics struct { - TcpActiveConnections int64 `json:"TcpActiveConnections"` + TCPActiveConnections int64 `json:"TcpActiveConnections"` ConcurrentRequestsCount int64 `json:"ConcurrentRequestsCount"` TotalRequests int64 `json:"TotalRequests"` RequestsPerSec float64 `json:"RequestsPerSec"` @@ -83,7 +83,7 @@ type clusterMetrics struct { NodeState string `json:"NodeState"` CurrentTerm int64 `json:"CurrentTerm"` Index int64 `json:"Index"` - Id string `json:"Id"` + ID string `json:"Id"` } type allDatabasesMetrics struct { @@ -93,13 +93,13 @@ type allDatabasesMetrics struct { type databasesMetricResponse struct { Results []*databaseMetrics `json:"Results"` - PublicServerUrl *string `json:"PublicServerUrl"` + PublicServerURL *string `json:"PublicServerUrl"` NodeTag string `json:"NodeTag"` } type databaseMetrics struct { DatabaseName string `json:"DatabaseName"` - DatabaseId string `json:"DatabaseId"` + DatabaseID string `json:"DatabaseId"` UptimeInSec float64 `json:"UptimeInSec"` TimeSinceLastBackupInSec *float64 `json:"TimeSinceLastBackupInSec"` @@ -153,7 +153,7 @@ type databaseStorageMetrics struct { type indexesMetricResponse struct { Results []*perDatabaseIndexMetrics `json:"Results"` - PublicServerUrl *string `json:"PublicServerUrl"` + PublicServerURL *string `json:"PublicServerUrl"` NodeTag string `json:"NodeTag"` } @@ -180,7 +180,7 @@ type indexMetrics struct { type collectionsMetricResponse struct { Results []*perDatabaseCollectionMetrics `json:"Results"` - PublicServerUrl *string `json:"PublicServerUrl"` + PublicServerURL *string `json:"PublicServerUrl"` NodeTag string `json:"NodeTag"` } diff --git a/plugins/inputs/redfish/redfish.go b/plugins/inputs/redfish/redfish.go index efd9f9f3367ae..4d9e70a57a9bd 100644 --- a/plugins/inputs/redfish/redfish.go +++ b/plugins/inputs/redfish/redfish.go @@ -73,7 +73,7 @@ type Chassis struct { type Power struct { PowerSupplies []struct { Name string - MemberId string + MemberID string PowerInputWatts *float64 PowerCapacityWatts *float64 PowerOutputWatts *float64 @@ -83,7 +83,7 @@ type Power struct { } Voltages []struct { Name string - MemberId string + MemberID string ReadingVolts *float64 UpperThresholdCritical *float64 UpperThresholdFatal *float64 @@ -96,7 +96,7 @@ type Power struct { type Thermal struct { Fans []struct { Name string - MemberId string + MemberID string Reading *int64 ReadingUnits *string UpperThresholdCritical *int64 @@ -107,7 +107,7 @@ type Thermal struct { } Temperatures []struct { Name string - MemberId string + MemberID string ReadingCelsius *float64 UpperThresholdCritical *float64 UpperThresholdFatal *float64 @@ -276,7 +276,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error { for _, j := range thermal.Temperatures { tags := map[string]string{} - tags["member_id"] = j.MemberId + tags["member_id"] = j.MemberID tags["address"] = address tags["name"] = j.Name tags["source"] = system.Hostname @@ -301,7 +301,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error { for _, j := range thermal.Fans { tags := map[string]string{} fields := make(map[string]interface{}) - tags["member_id"] = j.MemberId + tags["member_id"] = j.MemberID tags["address"] = address tags["name"] = j.Name tags["source"] = system.Hostname @@ -333,7 +333,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error { for _, j := range power.PowerSupplies { tags := map[string]string{} - tags["member_id"] = j.MemberId + tags["member_id"] = j.MemberID tags["address"] = address tags["name"] = j.Name tags["source"] = system.Hostname @@ -357,7 +357,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error { for _, j := range power.Voltages { tags := map[string]string{} - tags["member_id"] = j.MemberId + tags["member_id"] = j.MemberID tags["address"] = address tags["name"] = j.Name tags["source"] = system.Hostname diff --git a/plugins/inputs/riak/riak.go b/plugins/inputs/riak/riak.go index c0f3990fa8b48..6a1a98e4586a1 100644 --- a/plugins/inputs/riak/riak.go +++ b/plugins/inputs/riak/riak.go @@ -21,10 +21,10 @@ type Riak struct { // NewRiak return a new instance of Riak with a default http client func NewRiak() *Riak { - tr := &http.Transport{ResponseHeaderTimeout: time.Duration(3 * time.Second)} + tr := &http.Transport{ResponseHeaderTimeout: 3 * time.Second} client := &http.Client{ Transport: tr, - Timeout: time.Duration(4 * time.Second), + Timeout: 4 * time.Second, } return &Riak{client: client} } diff --git a/plugins/inputs/salesforce/salesforce.go b/plugins/inputs/salesforce/salesforce.go index b66266d3f17d2..f1ecff8d61a83 100644 --- a/plugins/inputs/salesforce/salesforce.go +++ b/plugins/inputs/salesforce/salesforce.go @@ -62,11 +62,11 @@ const defaultEnvironment = "production" // returns a new Salesforce plugin instance func NewSalesforce() *Salesforce { tr := &http.Transport{ - ResponseHeaderTimeout: time.Duration(5 * time.Second), + ResponseHeaderTimeout: 5 * time.Second, } client := &http.Client{ Transport: tr, - Timeout: time.Duration(10 * time.Second), + Timeout: 10 * time.Second, } return &Salesforce{ client: client, @@ -147,7 +147,7 @@ func (s *Salesforce) fetchLimits() (limits, error) { } if resp.StatusCode != http.StatusOK { - return l, fmt.Errorf("Salesforce responded with unexpected status code %d", resp.StatusCode) + return l, fmt.Errorf("salesforce responded with unexpected status code %d", resp.StatusCode) } l = limits{} diff --git a/plugins/inputs/salesforce/salesforce_test.go b/plugins/inputs/salesforce/salesforce_test.go index 288cc0f40af79..3d26d87dda964 100644 --- a/plugins/inputs/salesforce/salesforce_test.go +++ b/plugins/inputs/salesforce/salesforce_test.go @@ -14,7 +14,7 @@ import ( func Test_Gather(t *testing.T) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/json") - _, _ = w.Write([]byte(testJson)) + _, _ = w.Write([]byte(testJSON)) })) defer fakeServer.Close() @@ -35,7 +35,7 @@ func Test_Gather(t *testing.T) { require.Len(t, m.Tags, 2) } -var testJson = `{ +var testJSON = `{ "ConcurrentAsyncGetReportInstances" : { "Max" : 200, "Remaining" : 200 diff --git a/plugins/inputs/snmp/snmp_mocks_test.go b/plugins/inputs/snmp/snmp_mocks_test.go index a3b8fb8e69a6d..80d6e2cbf74ce 100644 --- a/plugins/inputs/snmp/snmp_mocks_test.go +++ b/plugins/inputs/snmp/snmp_mocks_test.go @@ -27,14 +27,14 @@ func mockExecCommand(arg0 string, args ...string) *exec.Cmd { func TestMockExecCommand(_ *testing.T) { var cmd []string for _, arg := range os.Args { - if string(arg) == "--" { + if arg == "--" { cmd = []string{} continue } if cmd == nil { continue } - cmd = append(cmd, string(arg)) + cmd = append(cmd, arg) } if cmd == nil { return diff --git a/plugins/inputs/snmp_legacy/snmp_legacy.go b/plugins/inputs/snmp_legacy/snmp_legacy.go index 5f6ecd3e0bd4f..f3f938657d09a 100644 --- a/plugins/inputs/snmp_legacy/snmp_legacy.go +++ b/plugins/inputs/snmp_legacy/snmp_legacy.go @@ -268,7 +268,7 @@ func findnodename(node Node, ids []string) (string, string) { return node.name, "0" } else if node.name != "" && len(ids) == 0 && id != "0" { // node with an instance - return node.name, string(id) + return node.name, id } else if node.name != "" && len(ids) > 0 { // node with subinstances return node.name, strings.Join(ids, ".") @@ -339,7 +339,7 @@ func (s *Snmp) Gather(acc telegraf.Accumulator) error { } else { oid.Name = oidstring oid.Oid = oidstring - if string(oidstring[:1]) != "." { + if oidstring[:1] != "." { oid.rawOid = "." + oidstring } else { oid.rawOid = oidstring @@ -764,7 +764,7 @@ func (h *Host) HandleResponse( var instance string // Get oidname and instance from translate file oidName, instance = findnodename(initNode, - strings.Split(string(variable.Name[1:]), ".")) + strings.Split(variable.Name[1:], ".")) // Set instance tag // From mapping table mapping, inMappingNoSubTable := h.OidInstanceMapping[oidKey] @@ -798,7 +798,7 @@ func (h *Host) HandleResponse( } tags["snmp_host"], _, _ = net.SplitHostPort(h.Address) fields := make(map[string]interface{}) - fields[string(fieldName)] = variable.Value + fields[fieldName] = variable.Value h.processedOids = append(h.processedOids, variable.Name) acc.AddFields(fieldName, fields, tags) diff --git a/plugins/inputs/sqlserver/connectionstring.go b/plugins/inputs/sqlserver/connectionstring.go index 54b5cd8ae6460..b5f530b9f9510 100644 --- a/plugins/inputs/sqlserver/connectionstring.go +++ b/plugins/inputs/sqlserver/connectionstring.go @@ -6,7 +6,7 @@ import ( ) const ( - emptySqlInstance = "" + emptySQLInstance = "" emptyDatabaseName = "" ) @@ -15,7 +15,7 @@ const ( // If the connection string could not be parsed or sqlInstance/databaseName were not present, a placeholder value is returned func getConnectionIdentifiers(connectionString string) (sqlInstance string, databaseName string) { if len(connectionString) == 0 { - return emptySqlInstance, emptyDatabaseName + return emptySQLInstance, emptyDatabaseName } trimmedConnectionString := strings.TrimSpace(connectionString) @@ -61,7 +61,7 @@ func parseConnectionStringKeyValue(connectionString string) (sqlInstance string, } if sqlInstance == "" { - sqlInstance = emptySqlInstance + sqlInstance = emptySQLInstance } if databaseName == "" { databaseName = emptyDatabaseName @@ -72,12 +72,12 @@ func parseConnectionStringKeyValue(connectionString string) (sqlInstance string, // parseConnectionStringURL parses a URL-formatted connection string and returns the SQL instance and database name func parseConnectionStringURL(connectionString string) (sqlInstance string, databaseName string) { - sqlInstance = emptySqlInstance + sqlInstance = emptySQLInstance databaseName = emptyDatabaseName u, err := url.Parse(connectionString) if err != nil { - return emptySqlInstance, emptyDatabaseName + return emptySQLInstance, emptyDatabaseName } sqlInstance = u.Hostname() diff --git a/plugins/inputs/sqlserver/sqlserver_test.go b/plugins/inputs/sqlserver/sqlserver_test.go index f462ebbf876bc..0e23c8635fcaa 100644 --- a/plugins/inputs/sqlserver/sqlserver_test.go +++ b/plugins/inputs/sqlserver/sqlserver_test.go @@ -297,7 +297,7 @@ func TestSqlServer_ConnectionString(t *testing.T) { connectionString = "invalid connection string" sqlInstance, database = getConnectionIdentifiers(connectionString) - assert.Equal(t, emptySqlInstance, sqlInstance) + assert.Equal(t, emptySQLInstance, sqlInstance) assert.Equal(t, emptyDatabaseName, database) // Key/value format @@ -323,7 +323,7 @@ func TestSqlServer_ConnectionString(t *testing.T) { connectionString = "invalid connection string" sqlInstance, database = getConnectionIdentifiers(connectionString) - assert.Equal(t, emptySqlInstance, sqlInstance) + assert.Equal(t, emptySQLInstance, sqlInstance) assert.Equal(t, emptyDatabaseName, database) } diff --git a/plugins/inputs/statsd/datadog.go b/plugins/inputs/statsd/datadog.go index 377db66e6d3ad..77a01f5586a7b 100644 --- a/plugins/inputs/statsd/datadog.go +++ b/plugins/inputs/statsd/datadog.go @@ -38,29 +38,29 @@ 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 fmt.Errorf("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 fmt.Errorf("invalid message format") } titleLen, err := strconv.ParseInt(rawLen[0], 10, 64) if err != nil { - return fmt.Errorf("Invalid message format, could not parse title.length: '%s'", rawLen[0]) + return fmt.Errorf("invalid message format, could not parse title.length: '%s'", rawLen[0]) } if len(rawLen[1]) < 1 { - return fmt.Errorf("Invalid message format, could not parse text.length: '%s'", rawLen[0]) + return fmt.Errorf("invalid message format, could not parse text.length: '%s'", rawLen[0]) } textLen, err := strconv.ParseInt(rawLen[1][:len(rawLen[1])-1], 10, 64) if err != nil { - return fmt.Errorf("Invalid message format, could not parse text.length: '%s'", rawLen[0]) + return fmt.Errorf("invalid message format, could not parse text.length: '%s'", 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 fmt.Errorf("invalid message format, title.length and text.length exceed total message length") } rawTitle := message[:titleLen] @@ -68,14 +68,14 @@ 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 fmt.Errorf("invalid event message format: empty 'title' or 'text' field") } name := rawTitle tags := make(map[string]string, strings.Count(message, ",")+2) // allocate for the approximate number of tags fields := make(map[string]interface{}, 9) fields["alert_type"] = eventInfo // default event type - fields["text"] = uncommenter.Replace(string(rawText)) + fields["text"] = uncommenter.Replace(rawText) if defaultHostname != "" { tags["source"] = defaultHostname } diff --git a/plugins/inputs/suricata/suricata.go b/plugins/inputs/suricata/suricata.go index 8cf374df65d3f..98ca348dce711 100644 --- a/plugins/inputs/suricata/suricata.go +++ b/plugins/inputs/suricata/suricata.go @@ -149,7 +149,7 @@ func flexFlatten(outmap map[string]interface{}, field string, v interface{}, del case float64: outmap[field] = v.(float64) default: - return fmt.Errorf("Unsupported type %T encountered", t) + return fmt.Errorf("unsupported type %T encountered", t) } return nil } @@ -157,7 +157,7 @@ func flexFlatten(outmap map[string]interface{}, field string, v interface{}, del func (s *Suricata) parse(acc telegraf.Accumulator, sjson []byte) { // initial parsing var result map[string]interface{} - err := json.Unmarshal([]byte(sjson), &result) + err := json.Unmarshal(sjson, &result) if err != nil { acc.AddError(err) return diff --git a/plugins/inputs/suricata/suricata_test.go b/plugins/inputs/suricata/suricata_test.go index 7259e658da5a9..0570c8135a418 100644 --- a/plugins/inputs/suricata/suricata_test.go +++ b/plugins/inputs/suricata/suricata_test.go @@ -42,9 +42,11 @@ func TestSuricataLarge(t *testing.T) { c, err := net.Dial("unix", tmpfn) require.NoError(t, err) - c.Write([]byte(data)) - c.Write([]byte("\n")) - c.Close() + _, err = c.Write(data) + require.NoError(t, err) + _, err = c.Write([]byte("\n")) + require.NoError(t, err) + require.NoError(t, c.Close()) acc.Wait(1) } diff --git a/plugins/inputs/vsphere/endpoint.go b/plugins/inputs/vsphere/endpoint.go index f8916242286e1..fa669a2a024ed 100644 --- a/plugins/inputs/vsphere/endpoint.go +++ b/plugins/inputs/vsphere/endpoint.go @@ -37,7 +37,7 @@ const maxMetadataSamples = 100 // Number of resources to sample for metric metad const maxRealtimeMetrics = 50000 // Absolute maximum metrics per realtime query -const hwMarkTTL = time.Duration(4 * time.Hour) +const hwMarkTTL = 4 * time.Hour type queryChunk []types.PerfQuerySpec diff --git a/plugins/inputs/zookeeper/zookeeper.go b/plugins/inputs/zookeeper/zookeeper.go index 6b6d21fc0d4f0..29d88dbfdce05 100644 --- a/plugins/inputs/zookeeper/zookeeper.go +++ b/plugins/inputs/zookeeper/zookeeper.go @@ -137,7 +137,7 @@ func (z *Zookeeper) gatherServer(ctx context.Context, address string, acc telegr fields := make(map[string]interface{}) for scanner.Scan() { line := scanner.Text() - parts := zookeeperFormatRE.FindStringSubmatch(string(line)) + parts := zookeeperFormatRE.FindStringSubmatch(line) if len(parts) != 3 { return fmt.Errorf("unexpected line in mntr response: %q", line) @@ -147,7 +147,7 @@ func (z *Zookeeper) gatherServer(ctx context.Context, address string, acc telegr if measurement == "server_state" { zookeeperState = parts[2] } else { - sValue := string(parts[2]) + sValue := parts[2] iVal, err := strconv.ParseInt(sValue, 10, 64) if err == nil { diff --git a/plugins/outputs/amon/amon.go b/plugins/outputs/amon/amon.go index 864bd60c853f1..0ee62f1e94fc2 100644 --- a/plugins/outputs/amon/amon.go +++ b/plugins/outputs/amon/amon.go @@ -133,11 +133,11 @@ func buildMetrics(m telegraf.Metric) (map[string]Point, error) { func (p *Point) setValue(v interface{}) error { switch d := v.(type) { case int: - p[1] = float64(int(d)) + p[1] = float64(d) case int32: - p[1] = float64(int32(d)) + p[1] = float64(d) case int64: - p[1] = float64(int64(d)) + p[1] = float64(d) case float32: p[1] = float64(d) case float64: diff --git a/plugins/outputs/cloud_pubsub/pubsub_test.go b/plugins/outputs/cloud_pubsub/pubsub_test.go index b3948573b7163..967a33d742c3c 100644 --- a/plugins/outputs/cloud_pubsub/pubsub_test.go +++ b/plugins/outputs/cloud_pubsub/pubsub_test.go @@ -183,7 +183,7 @@ func verifyMetricPublished(t *testing.T, m telegraf.Metric, published map[string if err != nil { t.Fatalf("Unable to decode expected base64-encoded message: %s", err) } - data = []byte(v) + data = v } parsed, err := p.Parse(data) diff --git a/plugins/outputs/dynatrace/dynatrace.go b/plugins/outputs/dynatrace/dynatrace.go index 8931986dd2fba..2c57d6fc584a0 100644 --- a/plugins/outputs/dynatrace/dynatrace.go +++ b/plugins/outputs/dynatrace/dynatrace.go @@ -20,7 +20,7 @@ import ( const ( oneAgentMetricsURL = "http://127.0.0.1:14499/metrics/ingest" - dtIngestApiLineLimit = 1000 + dtIngestAPILineLimit = 1000 ) var ( @@ -235,7 +235,7 @@ func (d *Dynatrace) Write(metrics []telegraf.Metric) error { fmt.Fprintf(&buf, "%s%s %v\n", metricID, tagb.String(), value) } - if metricCounter%dtIngestApiLineLimit == 0 { + if metricCounter%dtIngestAPILineLimit == 0 { err = d.send(buf.Bytes()) if err != nil { return err diff --git a/plugins/outputs/librato/librato.go b/plugins/outputs/librato/librato.go index c91955ced2e0d..1d9f6725206a8 100644 --- a/plugins/outputs/librato/librato.go +++ b/plugins/outputs/librato/librato.go @@ -225,7 +225,7 @@ func verifyValue(v interface{}) bool { func (g *Gauge) setValue(v interface{}) error { switch d := v.(type) { case int64: - g.Value = float64(int64(d)) + g.Value = float64(d) case uint64: g.Value = float64(d) case float64: diff --git a/plugins/outputs/sensu/sensu.go b/plugins/outputs/sensu/sensu.go index a3857b2cfceb9..568f8f7a144e4 100644 --- a/plugins/outputs/sensu/sensu.go +++ b/plugins/outputs/sensu/sensu.go @@ -23,7 +23,7 @@ import ( ) const ( - defaultUrl = "http://127.0.0.1:3031" + defaultURL = "http://127.0.0.1:3031" defaultClientTimeout = 5 * time.Second defaultContentType = "application/json; charset=utf-8" ) @@ -82,9 +82,9 @@ type SensuMetrics struct { } type Sensu struct { - ApiKey *string `toml:"api_key"` - AgentApiUrl *string `toml:"agent_api_url"` - BackendApiUrl *string `toml:"backend_api_url"` + APIKey *string `toml:"api_key"` + AgentAPIURL *string `toml:"agent_api_url"` + BackendAPIURL *string `toml:"backend_api_url"` Entity *SensuEntity `toml:"entity"` Tags map[string]string `toml:"tags"` Metrics *SensuMetrics `toml:"metrics"` @@ -93,7 +93,7 @@ type Sensu struct { Timeout config.Duration `toml:"timeout"` ContentEncoding string `toml:"content_encoding"` - EndpointUrl string + EndpointURL string OutEntity *OutputEntity Log telegraf.Logger `toml:"-"` @@ -219,7 +219,7 @@ func (s *Sensu) createClient() (*http.Client, error) { } func (s *Sensu) Connect() error { - err := s.setEndpointUrl() + err := s.setEndpointURL() if err != nil { return err } @@ -292,7 +292,7 @@ func (s *Sensu) Write(metrics []telegraf.Metric) error { } } - reqBody, err := s.encodeToJson(points) + reqBody, err := s.encodeToJSON(points) if err != nil { return err } @@ -313,7 +313,7 @@ func (s *Sensu) write(reqBody []byte) error { reqBodyBuffer = rc } - req, err := http.NewRequest(method, s.EndpointUrl, reqBodyBuffer) + req, err := http.NewRequest(method, s.EndpointURL, reqBodyBuffer) if err != nil { return err } @@ -325,8 +325,8 @@ func (s *Sensu) write(reqBody []byte) error { req.Header.Set("Content-Encoding", "gzip") } - if s.ApiKey != nil { - req.Header.Set("Authorization", "Key "+*s.ApiKey) + if s.APIKey != nil { + req.Header.Set("Authorization", "Key "+*s.APIKey) } resp, err := s.client.Do(req) @@ -342,7 +342,7 @@ func (s *Sensu) write(reqBody []byte) error { } s.Log.Debugf("Failed to write, response: %v", string(bodyData)) if resp.StatusCode < 400 || resp.StatusCode > 499 { - return fmt.Errorf("when writing to [%s] received status code: %d", s.EndpointUrl, resp.StatusCode) + return fmt.Errorf("when writing to [%s] received status code: %d", s.EndpointURL, resp.StatusCode) } } @@ -350,37 +350,37 @@ func (s *Sensu) write(reqBody []byte) error { } // Resolves the event write endpoint -func (s *Sensu) setEndpointUrl() error { +func (s *Sensu) setEndpointURL() error { var ( - endpointUrl string - path_suffix string + endpointURL string + pathSuffix string ) - if s.BackendApiUrl != nil { - endpointUrl = *s.BackendApiUrl + if s.BackendAPIURL != nil { + endpointURL = *s.BackendAPIURL namespace := "default" if s.Entity != nil && s.Entity.Namespace != nil { namespace = *s.Entity.Namespace } - path_suffix = "/api/core/v2/namespaces/" + namespace + "/events" - } else if s.AgentApiUrl != nil { - endpointUrl = *s.AgentApiUrl - path_suffix = "/events" + pathSuffix = "/api/core/v2/namespaces/" + namespace + "/events" + } else if s.AgentAPIURL != nil { + endpointURL = *s.AgentAPIURL + pathSuffix = "/events" } - if len(endpointUrl) == 0 { - s.Log.Debugf("no backend or agent API URL provided, falling back to default agent API URL %s", defaultUrl) - endpointUrl = defaultUrl - path_suffix = "/events" + if len(endpointURL) == 0 { + s.Log.Debugf("no backend or agent API URL provided, falling back to default agent API URL %s", defaultURL) + endpointURL = defaultURL + pathSuffix = "/events" } - u, err := url.Parse(endpointUrl) + u, err := url.Parse(endpointURL) if err != nil { return err } - u.Path = path.Join(u.Path, path_suffix) - s.EndpointUrl = u.String() + u.Path = path.Join(u.Path, pathSuffix) + s.EndpointURL = u.String() return nil } @@ -389,12 +389,12 @@ func (s *Sensu) Init() error { if len(s.ContentEncoding) != 0 { validEncoding := []string{"identity", "gzip"} if !choice.Contains(s.ContentEncoding, validEncoding) { - return fmt.Errorf("Unsupported content_encoding [%q] specified", s.ContentEncoding) + return fmt.Errorf("unsupported content_encoding [%q] specified", s.ContentEncoding) } } - if s.BackendApiUrl != nil && s.ApiKey == nil { - return fmt.Errorf("backend_api_url [%q] specified, but no API Key provided", *s.BackendApiUrl) + if s.BackendAPIURL != nil && s.APIKey == nil { + return fmt.Errorf("backend_api_url [%q] specified, but no API Key provided", *s.BackendAPIURL) } return nil @@ -404,18 +404,18 @@ func init() { outputs.Add("sensu", func() telegraf.Output { // Default configuration values - // make a string from the defaultUrl const - agentApiUrl := defaultUrl + // make a string from the defaultURL const + agentAPIURL := defaultURL return &Sensu{ - AgentApiUrl: &agentApiUrl, + AgentAPIURL: &agentAPIURL, Timeout: config.Duration(defaultClientTimeout), ContentEncoding: "identity", } }) } -func (s *Sensu) encodeToJson(metricPoints []*OutputMetric) ([]byte, error) { +func (s *Sensu) encodeToJSON(metricPoints []*OutputMetric) ([]byte, error) { timestamp := time.Now().Unix() check, err := s.getCheck(metricPoints) @@ -439,7 +439,7 @@ func (s *Sensu) encodeToJson(metricPoints []*OutputMetric) ([]byte, error) { // Constructs the entity payload // Throws when no entity name is provided and fails resolve to hostname func (s *Sensu) setEntity() error { - if s.BackendApiUrl != nil { + if s.BackendAPIURL != nil { var entityName string if s.Entity != nil && s.Entity.Name != nil { entityName = *s.Entity.Name diff --git a/plugins/outputs/sensu/sensu_test.go b/plugins/outputs/sensu/sensu_test.go index 4184a9976fa89..249775727a481 100644 --- a/plugins/outputs/sensu/sensu_test.go +++ b/plugins/outputs/sensu/sensu_test.go @@ -17,58 +17,58 @@ import ( ) func TestResolveEventEndpointUrl(t *testing.T) { - agentApiUrl := "http://127.0.0.1:3031" - backendApiUrl := "http://127.0.0.1:8080" + agentAPIURL := "http://127.0.0.1:3031" + backendAPIURL := "http://127.0.0.1:8080" entityNamespace := "test-namespace" emptyString := "" tests := []struct { name string plugin *Sensu - expectedEndpointUrl string + expectedEndpointURL string }{ { name: "agent event endpoint", plugin: &Sensu{ - AgentApiUrl: &agentApiUrl, + AgentAPIURL: &agentAPIURL, Log: testutil.Logger{}, }, - expectedEndpointUrl: "http://127.0.0.1:3031/events", + expectedEndpointURL: "http://127.0.0.1:3031/events", }, { name: "backend event endpoint with default namespace", plugin: &Sensu{ - AgentApiUrl: &agentApiUrl, - BackendApiUrl: &backendApiUrl, + AgentAPIURL: &agentAPIURL, + BackendAPIURL: &backendAPIURL, Log: testutil.Logger{}, }, - expectedEndpointUrl: "http://127.0.0.1:8080/api/core/v2/namespaces/default/events", + expectedEndpointURL: "http://127.0.0.1:8080/api/core/v2/namespaces/default/events", }, { name: "backend event endpoint with namespace declared", plugin: &Sensu{ - AgentApiUrl: &agentApiUrl, - BackendApiUrl: &backendApiUrl, + AgentAPIURL: &agentAPIURL, + BackendAPIURL: &backendAPIURL, Entity: &SensuEntity{ Namespace: &entityNamespace, }, Log: testutil.Logger{}, }, - expectedEndpointUrl: "http://127.0.0.1:8080/api/core/v2/namespaces/test-namespace/events", + expectedEndpointURL: "http://127.0.0.1:8080/api/core/v2/namespaces/test-namespace/events", }, { - name: "agent event endpoint due to empty AgentApiUrl", + name: "agent event endpoint due to empty AgentAPIURL", plugin: &Sensu{ - AgentApiUrl: &emptyString, + AgentAPIURL: &emptyString, Log: testutil.Logger{}, }, - expectedEndpointUrl: "http://127.0.0.1:3031/events", + expectedEndpointURL: "http://127.0.0.1:3031/events", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := tt.plugin.setEndpointUrl() + err := tt.plugin.setEndpointURL() require.Equal(t, err, error(nil)) - require.Equal(t, tt.expectedEndpointUrl, tt.plugin.EndpointUrl) + require.Equal(t, tt.expectedEndpointURL, tt.plugin.EndpointURL) }) } } @@ -77,23 +77,23 @@ func TestConnectAndWrite(t *testing.T) { ts := httptest.NewServer(http.NotFoundHandler()) defer ts.Close() - testUrl := fmt.Sprintf("http://%s", ts.Listener.Addr().String()) - testApiKey := "a0b1c2d3-e4f5-g6h7-i8j9-k0l1m2n3o4p5" + testURL := fmt.Sprintf("http://%s", ts.Listener.Addr().String()) + testAPIKey := "a0b1c2d3-e4f5-g6h7-i8j9-k0l1m2n3o4p5" testCheck := "telegraf" testEntity := "entity1" testNamespace := "default" testHandler := "influxdb" testTagName := "myTagName" testTagValue := "myTagValue" - expectedAuthHeader := fmt.Sprintf("Key %s", testApiKey) - expectedUrl := fmt.Sprintf("/api/core/v2/namespaces/%s/events", testNamespace) + expectedAuthHeader := fmt.Sprintf("Key %s", testAPIKey) + expectedURL := fmt.Sprintf("/api/core/v2/namespaces/%s/events", testNamespace) expectedPointName := "cpu" expectedPointValue := float64(42) plugin := &Sensu{ - AgentApiUrl: nil, - BackendApiUrl: &testUrl, - ApiKey: &testApiKey, + AgentAPIURL: nil, + BackendAPIURL: &testURL, + APIKey: &testAPIKey, Check: &SensuCheck{ Name: &testCheck, }, @@ -115,8 +115,8 @@ func TestConnectAndWrite(t *testing.T) { t.Run("write", func(t *testing.T) { ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, expectedUrl, r.URL.String()) - require.Equal(t, expectedAuthHeader, (r.Header.Get("Authorization"))) + require.Equal(t, expectedURL, r.URL.String()) + require.Equal(t, expectedAuthHeader, r.Header.Get("Authorization")) // let's make sure what we received is a valid Sensu event that contains all of the expected data body, err := ioutil.ReadAll(r.Body) require.NoError(t, err) diff --git a/plugins/outputs/stackdriver/stackdriver.go b/plugins/outputs/stackdriver/stackdriver.go index 3bd38614b985e..4d561a27b5007 100644 --- a/plugins/outputs/stackdriver/stackdriver.go +++ b/plugins/outputs/stackdriver/stackdriver.go @@ -71,11 +71,11 @@ var sampleConfig = ` // 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 fmt.Errorf("project is a required field for stackdriver output") } if s.Namespace == "" { - return fmt.Errorf("Namespace is a required field for stackdriver output") + return fmt.Errorf("namespace is a required field for stackdriver output") } if s.ResourceType == "" { @@ -300,7 +300,7 @@ func getStackdriverTypedValue(value interface{}) (*monitoringpb.TypedValue, erro case int64: return &monitoringpb.TypedValue{ Value: &monitoringpb.TypedValue_Int64Value{ - Int64Value: int64(v), + Int64Value: v, }, }, nil case float64: @@ -312,7 +312,7 @@ func getStackdriverTypedValue(value interface{}) (*monitoringpb.TypedValue, erro case bool: return &monitoringpb.TypedValue{ Value: &monitoringpb.TypedValue_BoolValue{ - BoolValue: bool(v), + BoolValue: v, }, }, nil case string: diff --git a/plugins/outputs/timestream/timestream_test.go b/plugins/outputs/timestream/timestream_test.go index 58984c50b8ad2..67cdb4495c1d8 100644 --- a/plugins/outputs/timestream/timestream_test.go +++ b/plugins/outputs/timestream/timestream_test.go @@ -635,8 +635,8 @@ func TestTransformMetricsUnsupportedFieldsAreSkipped(t *testing.T) { func comparisonTest(t *testing.T, mappingMode string, telegrafMetrics []telegraf.Metric, - timestreamRecords []*timestreamwrite.WriteRecordsInput) { - + timestreamRecords []*timestreamwrite.WriteRecordsInput, +) { var plugin ts.Timestream switch mappingMode { case ts.MappingModeSingleTable: @@ -668,8 +668,8 @@ func comparisonTest(t *testing.T, func arrayContains( array []*timestreamwrite.WriteRecordsInput, - element *timestreamwrite.WriteRecordsInput) bool { - + element *timestreamwrite.WriteRecordsInput, +) bool { sortWriteInputForComparison(*element) for _, a := range array { diff --git a/plugins/outputs/wavefront/wavefront.go b/plugins/outputs/wavefront/wavefront.go index f793d62b89a80..3ad4e803b9f6a 100644 --- a/plugins/outputs/wavefront/wavefront.go +++ b/plugins/outputs/wavefront/wavefront.go @@ -316,7 +316,7 @@ func buildValue(v interface{}, name string, w *Wavefront) (float64, error) { for prefix, mappings := range w.StringToNumber { if strings.HasPrefix(name, prefix) { for _, mapping := range mappings { - val, hasVal := mapping[string(p)] + val, hasVal := mapping[p] if hasVal { return val, nil } diff --git a/plugins/parsers/influx/machine_test.go b/plugins/parsers/influx/machine_test.go index 735b5b9114ddd..e8e0357fdb33f 100644 --- a/plugins/parsers/influx/machine_test.go +++ b/plugins/parsers/influx/machine_test.go @@ -2152,7 +2152,7 @@ func TestStreamMachine(t *testing.T) { for _, tt := range tests { tc = append(tc, testcase{ name: tt.name, - input: bytes.NewBuffer([]byte(tt.input)), + input: bytes.NewBuffer(tt.input), results: tt.results, err: tt.err, }) @@ -2191,7 +2191,7 @@ func TestStreamMachinePosition(t *testing.T) { for _, tt := range positionTests { tc = append(tc, testcase{ name: tt.name, - input: bytes.NewBuffer([]byte(tt.input)), + input: bytes.NewBuffer(tt.input), lineno: tt.lineno, column: tt.column, }) diff --git a/plugins/parsers/nagios/parser.go b/plugins/parsers/nagios/parser.go index e4058852bf2e2..b347195ab3c37 100644 --- a/plugins/parsers/nagios/parser.go +++ b/plugins/parsers/nagios/parser.go @@ -194,7 +194,7 @@ func parsePerfData(perfdatas string, timestamp time.Time) ([]telegraf.Metric, er fieldName := strings.Trim(perf[1], "'") tags := map[string]string{"perfdata": fieldName} if perf[3] != "" { - str := string(perf[3]) + str := perf[3] if str != "" { tags["unit"] = str } @@ -202,10 +202,10 @@ func parsePerfData(perfdatas string, timestamp time.Time) ([]telegraf.Metric, er fields := make(map[string]interface{}) if perf[2] == "U" { - return nil, errors.New("Value undetermined") + return nil, errors.New("value undetermined") } - f, err := strconv.ParseFloat(string(perf[2]), 64) + f, err := strconv.ParseFloat(perf[2], 64) if err == nil { fields["value"] = f } @@ -264,14 +264,14 @@ const ( MinFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52) ) -var ErrBadThresholdFormat = errors.New("Bad threshold format") +var ErrBadThresholdFormat = errors.New("bad threshold format") // Handles all cases from https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT func parseThreshold(threshold string) (min float64, max float64, err error) { thresh := strings.Split(threshold, ":") switch len(thresh) { case 1: - max, err = strconv.ParseFloat(string(thresh[0]), 64) + max, err = strconv.ParseFloat(thresh[0], 64) if err != nil { return 0, 0, ErrBadThresholdFormat } @@ -281,7 +281,7 @@ func parseThreshold(threshold string) (min float64, max float64, err error) { if thresh[0] == "~" { min = MinFloat64 } else { - min, err = strconv.ParseFloat(string(thresh[0]), 64) + min, err = strconv.ParseFloat(thresh[0], 64) if err != nil { min = 0 } @@ -290,7 +290,7 @@ func parseThreshold(threshold string) (min float64, max float64, err error) { if thresh[1] == "" { max = MaxFloat64 } else { - max, err = strconv.ParseFloat(string(thresh[1]), 64) + max, err = strconv.ParseFloat(thresh[1], 64) if err != nil { return 0, 0, ErrBadThresholdFormat } diff --git a/plugins/parsers/value/parser.go b/plugins/parsers/value/parser.go index 95c87a2eae982..d4a9046e020a9 100644 --- a/plugins/parsers/value/parser.go +++ b/plugins/parsers/value/parser.go @@ -28,7 +28,7 @@ func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) { if len(values) < 1 { return []telegraf.Metric{}, nil } - vStr = string(values[len(values)-1]) + vStr = values[len(values)-1] } var value interface{} @@ -65,7 +65,7 @@ func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) { } if len(metrics) < 1 { - return nil, fmt.Errorf("Can not parse the line: %s, for data format: value", line) + return nil, fmt.Errorf("can not parse the line: %s, for data format: value", line) } return metrics[0], nil diff --git a/plugins/serializers/splunkmetric/splunkmetric_test.go b/plugins/serializers/splunkmetric/splunkmetric_test.go index c00bcc7798aac..f00d5d8da2176 100644 --- a/plugins/serializers/splunkmetric/splunkmetric_test.go +++ b/plugins/serializers/splunkmetric/splunkmetric_test.go @@ -33,7 +33,7 @@ func TestSerializeMetricFloat(t *testing.T) { buf, err = s.Serialize(m) assert.NoError(t, err) expS := `{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":1529875740.819}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricFloatHec(t *testing.T) { @@ -53,7 +53,7 @@ func TestSerializeMetricFloatHec(t *testing.T) { buf, err = s.Serialize(m) assert.NoError(t, err) expS := `{"time":1529875740.819,"fields":{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricInt(t *testing.T) { @@ -73,7 +73,7 @@ func TestSerializeMetricInt(t *testing.T) { assert.NoError(t, err) expS := `{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricIntHec(t *testing.T) { @@ -93,7 +93,7 @@ func TestSerializeMetricIntHec(t *testing.T) { assert.NoError(t, err) expS := `{"time":0,"fields":{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricBool(t *testing.T) { @@ -113,7 +113,7 @@ func TestSerializeMetricBool(t *testing.T) { assert.NoError(t, err) expS := `{"_value":1,"container-name":"telegraf-test","metric_name":"docker.oomkiller","time":0}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricBoolHec(t *testing.T) { @@ -133,7 +133,7 @@ func TestSerializeMetricBoolHec(t *testing.T) { assert.NoError(t, err) expS := `{"time":0,"fields":{"_value":0,"container-name":"telegraf-test","metric_name":"docker.oomkiller"}}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMetricString(t *testing.T) { @@ -154,7 +154,7 @@ func TestSerializeMetricString(t *testing.T) { assert.NoError(t, err) expS := `{"_value":5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) assert.NoError(t, err) } @@ -186,7 +186,7 @@ func TestSerializeBatch(t *testing.T) { assert.NoError(t, err) expS := `{"_value":42,"metric_name":"cpu.value","time":0}{"_value":92,"metric_name":"cpu.value","time":0}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMulti(t *testing.T) { @@ -208,7 +208,7 @@ func TestSerializeMulti(t *testing.T) { assert.NoError(t, err) expS := `{"metric_name:cpu.system":8,"metric_name:cpu.user":42,"time":0}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeBatchHec(t *testing.T) { @@ -239,7 +239,7 @@ func TestSerializeBatchHec(t *testing.T) { assert.NoError(t, err) expS := `{"time":0,"fields":{"_value":42,"metric_name":"cpu.value"}}{"time":0,"fields":{"_value":92,"metric_name":"cpu.value"}}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) } func TestSerializeMultiHec(t *testing.T) { @@ -261,5 +261,5 @@ func TestSerializeMultiHec(t *testing.T) { assert.NoError(t, err) expS := `{"time":0,"fields":{"metric_name:cpu.system":8,"metric_name:cpu.usage":42}}` - assert.Equal(t, string(expS), string(buf)) + assert.Equal(t, expS, string(buf)) }