Linter fixes - unconvert, revive:empty-lines, revive:var-naming, revive:unused-parameter (#9036)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2021-03-24 16:27:46 +01:00 committed by GitHub
parent 9aaaf72a96
commit 5de640b855
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
66 changed files with 337 additions and 336 deletions

View File

@ -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.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 { select {
case <-ctx.Done(): case <-ctx.Done():
return nil return nil
case <-time.After(time.Duration(p.RestartDelay)): case <-time.After(p.RestartDelay):
// Continue the loop and restart the process // Continue the loop and restart the process
if err := p.cmdStart(); err != nil { if err := p.cmdStart(); err != nil {
return err return err

View File

@ -297,7 +297,7 @@ func convertField(v interface{}) interface{} {
case uint: case uint:
return uint64(v) return uint64(v)
case uint64: case uint64:
return uint64(v) return v
case []byte: case []byte:
return string(v) return string(v)
case int32: case int32:
@ -340,7 +340,7 @@ func convertField(v interface{}) interface{} {
} }
case *uint64: case *uint64:
if v != nil { if v != nil {
return uint64(*v) return *v
} }
case *[]byte: case *[]byte:
if v != nil { if v != nil {

View File

@ -458,11 +458,11 @@ L:
metric.requestDimensions = make([]map[string]string, 0, len(s.discoveryData)) metric.requestDimensions = make([]map[string]string, 0, len(s.discoveryData))
//Preparing tags & dims... //Preparing tags & dims...
for instanceId, elem := range s.discoveryData { for instanceID, elem := range s.discoveryData {
//Start filing tags //Start filing tags
//Remove old value if exist //Remove old value if exist
delete(metric.discoveryTags, instanceId) delete(metric.discoveryTags, instanceID)
metric.discoveryTags[instanceId] = make(map[string]string, len(metric.TagsQueryPath)+len(defaulTags)) metric.discoveryTags[instanceID] = make(map[string]string, len(metric.TagsQueryPath)+len(defaulTags))
for _, tagQueryPath := range metric.TagsQueryPath { for _, tagQueryPath := range metric.TagsQueryPath {
tagKey, tagValue, err := parseTag(tagQueryPath, elem) tagKey, tagValue, err := parseTag(tagQueryPath, elem)
@ -471,11 +471,11 @@ L:
continue continue
} }
if err == nil && tagValue == "" { //Nothing found 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 continue
} }
metric.discoveryTags[instanceId][tagKey] = tagValue metric.discoveryTags[instanceID][tagKey] = tagValue
} }
//Adding default tags if not already there //Adding default tags if not already there
@ -489,17 +489,17 @@ L:
if err == nil && tagValue == "" { //Nothing found if err == nil && tagValue == "" { //Nothing found
s.Log.Debugf("Data by query path %q: is not found, for instance %q", s.Log.Debugf("Data by query path %q: is not found, for instance %q",
defaultTagQP, instanceId) defaultTagQP, instanceID)
continue continue
} }
metric.discoveryTags[instanceId][tagKey] = tagValue metric.discoveryTags[instanceID][tagKey] = tagValue
} }
//Preparing dimensions (first adding dimensions that comes from discovery data) //Preparing dimensions (first adding dimensions that comes from discovery data)
metric.requestDimensions = append( metric.requestDimensions = append(
metric.requestDimensions, metric.requestDimensions,
map[string]string{s.dimensionKey: instanceId}) map[string]string{s.dimensionKey: instanceID})
} }
//Get final dimension (need to get full lis of //Get final dimension (need to get full lis of

View File

@ -60,7 +60,7 @@ type discoveryTool struct {
cli map[string]aliyunSdkClient //API client, which perform discovery request cli map[string]aliyunSdkClient //API client, which perform discovery request
respRootKey string //Root key in JSON response where to look for discovery data 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// ) //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 wg sync.WaitGroup //WG for primary discovery goroutine
interval time.Duration //Discovery interval interval time.Duration //Discovery interval
@ -69,9 +69,9 @@ type discoveryTool struct {
lg telegraf.Logger //Telegraf logger (should be provided) 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 //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 || if reflect.ValueOf(req).Type().Kind() != reflect.Ptr ||
reflect.ValueOf(req).IsNil() { 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()) 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{} cli = map[string]aliyunSdkClient{}
parseRootKey = regexp.MustCompile(`Describe(.*)`) parseRootKey = regexp.MustCompile(`Describe(.*)`)
responseRootKey string responseRootKey string
responseObjectIdKey string responseObjectIDKey string
err error err error
noDiscoverySupportErr = errors.Errorf("no discovery support for project %q", project) 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 { switch project {
case "acs_ecs_dashboard": case "acs_ecs_dashboard":
dscReq[region] = ecs.CreateDescribeInstancesRequest() dscReq[region] = ecs.CreateDescribeInstancesRequest()
responseObjectIdKey = "InstanceId" responseObjectIDKey = "InstanceId"
case "acs_rds_dashboard": case "acs_rds_dashboard":
dscReq[region] = rds.CreateDescribeDBInstancesRequest() dscReq[region] = rds.CreateDescribeDBInstancesRequest()
responseObjectIdKey = "DBInstanceId" responseObjectIDKey = "DBInstanceId"
case "acs_slb_dashboard": case "acs_slb_dashboard":
dscReq[region] = slb.CreateDescribeLoadBalancersRequest() dscReq[region] = slb.CreateDescribeLoadBalancersRequest()
responseObjectIdKey = "LoadBalancerId" responseObjectIDKey = "LoadBalancerId"
case "acs_memcache": case "acs_memcache":
return nil, noDiscoverySupportErr return nil, noDiscoverySupportErr
case "acs_ocs": 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") //req.InitWithApiInfo("oss", "2014-08-15", "DescribeDBInstances", "oss", "openAPI")
case "acs_vpc_eip": case "acs_vpc_eip":
dscReq[region] = vpc.CreateDescribeEipAddressesRequest() dscReq[region] = vpc.CreateDescribeEipAddressesRequest()
responseObjectIdKey = "AllocationId" responseObjectIDKey = "AllocationId"
case "acs_kvstore": case "acs_kvstore":
return nil, noDiscoverySupportErr return nil, noDiscoverySupportErr
case "acs_mns_new": 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 //Getting response root key (if not set already). This is to be able to parse discovery responses
//As they differ per object type //As they differ per object type
//Discovery requests are of the same type per every region, so pick the first one //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 //This means that the discovery request is not of proper type/kind
if err != nil { if err != nil {
return nil, errors.Errorf("Can't parse rpc request object from discovery request %v", dscReq[regions[0]]) 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, req: dscReq,
cli: cli, cli: cli,
respRootKey: responseRootKey, respRootKey: responseRootKey,
respObjectIdKey: responseObjectIdKey, respObjectIDKey: responseObjectIDKey,
rateLimit: rateLimit, rateLimit: rateLimit,
interval: discoveryInterval, interval: discoveryInterval,
reqDefaultPageSize: 20, reqDefaultPageSize: 20,
@ -380,8 +380,8 @@ func (dt *discoveryTool) getDiscoveryData(cli aliyunSdkClient, req *requests.Com
for _, raw := range discoveryData { for _, raw := range discoveryData {
if elem, ok := raw.(map[string]interface{}); ok { if elem, ok := raw.(map[string]interface{}); ok {
if objectId, ok := elem[dt.respObjectIdKey].(string); ok { if objectID, ok := elem[dt.respObjectIDKey].(string); ok {
preparedData[objectId] = elem preparedData[objectID] = elem
} }
} else { } else {
return nil, errors.Errorf("Can't parse input data element, not a map[string]interface{} type") 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) 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 { if err != nil {
return nil, err return nil, err
} }

View File

@ -15,7 +15,7 @@ import (
const defaultAddress = "tcp://127.0.0.1:3551" 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 { type ApcUpsd struct {
Servers []string Servers []string

View File

@ -171,7 +171,7 @@ func (c *CiscoTelemetryMDT) initBgpV4() {
c.nxpathMap[key]["aspath"] = "string" c.nxpathMap[key]["aspath"] = "string"
} }
func (c *CiscoTelemetryMDT) initCpu() { func (c *CiscoTelemetryMDT) initCPU() {
key := "show processes cpu" key := "show processes cpu"
c.nxpathMap[key] = make(map[string]string, 5) c.nxpathMap[key] = make(map[string]string, 5)
c.nxpathMap[key]["kernel_percent"] = "float" c.nxpathMap[key]["kernel_percent"] = "float"
@ -654,7 +654,7 @@ func (c *CiscoTelemetryMDT) initPimVrf() {
c.nxpathMap[key]["table-id"] = "string" c.nxpathMap[key]["table-id"] = "string"
} }
func (c *CiscoTelemetryMDT) initIpMroute() { func (c *CiscoTelemetryMDT) initIPMroute() {
key := "show ip mroute summary vrf all" key := "show ip mroute summary vrf all"
c.nxpathMap[key] = make(map[string]string, 40) c.nxpathMap[key] = make(map[string]string, 40)
c.nxpathMap[key]["nat-mode"] = "string" c.nxpathMap[key]["nat-mode"] = "string"
@ -842,7 +842,7 @@ func (c *CiscoTelemetryMDT) initDb() {
c.initPower() c.initPower()
c.initMemPhys() c.initMemPhys()
c.initBgpV4() c.initBgpV4()
c.initCpu() c.initCPU()
c.initResources() c.initResources()
c.initPtpCorrection() c.initPtpCorrection()
c.initTrans() c.initTrans()
@ -861,7 +861,7 @@ func (c *CiscoTelemetryMDT) initDb() {
c.initPimStats() c.initPimStats()
c.initIntfBrief() c.initIntfBrief()
c.initPimVrf() c.initPimVrf()
c.initIpMroute() c.initIPMroute()
c.initIpv6Mroute() c.initIpv6Mroute()
c.initVpc() c.initVpc()
c.initBgp() c.initBgp()

View File

@ -180,7 +180,7 @@ func (ps *PubSub) onMessage(ctx context.Context, msg message) error {
if err != nil { if err != nil {
return fmt.Errorf("unable to base64 decode message: %v", err) return fmt.Errorf("unable to base64 decode message: %v", err)
} }
data = []byte(strData) data = strData
} else { } else {
data = msg.Data() data = msg.Data()
} }

View File

@ -125,9 +125,9 @@ func (c *CouchDB) fetchAndInsertData(accumulator telegraf.Accumulator, host stri
if c.client == nil { if c.client == nil {
c.client = &http.Client{ c.client = &http.Client{
Transport: &http.Transport{ 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() defer response.Body.Close()
if response.StatusCode != 200 { 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{} stats := Stats{}
@ -287,9 +287,9 @@ func init() {
return &CouchDB{ return &CouchDB{
client: &http.Client{ client: &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
ResponseHeaderTimeout: time.Duration(3 * time.Second), ResponseHeaderTimeout: 3 * time.Second,
}, },
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
}, },
} }
}) })

View File

@ -176,15 +176,15 @@ func requestServer(url string, rconPw string) (string, error) {
} }
defer remoteConsole.Close() defer remoteConsole.Close()
reqId, err := remoteConsole.Write("stats") reqID, err := remoteConsole.Write("stats")
if err != nil { if err != nil {
return "", err return "", err
} }
resp, respReqId, err := remoteConsole.Read() resp, respReqID, err := remoteConsole.Read()
if err != nil { if err != nil {
return "", err return "", err
} else if reqId != respReqId { } else if reqID != respReqID {
return "", errors.New("response/request mismatch") return "", errors.New("response/request mismatch")
} else { } else {
return resp, nil return resp, nil

View File

@ -79,7 +79,7 @@ func TestCSVGZImport(t *testing.T) {
func TestMultipleJSONFileImports(t *testing.T) { func TestMultipleJSONFileImports(t *testing.T) {
acc := testutil.Accumulator{} acc := testutil.Accumulator{}
testJsonFile := "test.json" testJSONFile := "test.json"
// Establish process directory and finished directory. // Establish process directory and finished directory.
finishedDirectory, err := ioutil.TempDir("", "finished") finishedDirectory, err := ioutil.TempDir("", "finished")
@ -110,7 +110,7 @@ func TestMultipleJSONFileImports(t *testing.T) {
// Let's drop a 5-line LINE-DELIMITED json. // Let's drop a 5-line LINE-DELIMITED json.
// Write csv file to process into the 'process' directory. // 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) 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.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() f.Close()

View File

@ -41,8 +41,8 @@ func (d *DiskIO) diskInfo(devName string) (map[string]string, error) {
// This allows us to also "poison" it during test scenarios // This allows us to also "poison" it during test scenarios
udevDataPath = ic.udevDataPath udevDataPath = ic.udevDataPath
} else { } else {
major := unix.Major(uint64(stat.Rdev)) major := unix.Major(uint64(stat.Rdev)) //nolint:unconvert // Conversion needed for some architectures
minor := unix.Minor(uint64(stat.Rdev)) minor := unix.Minor(uint64(stat.Rdev)) //nolint:unconvert // Conversion needed for some architectures
udevDataPath = fmt.Sprintf("/run/udev/data/b%d:%d", major, minor) udevDataPath = fmt.Sprintf("/run/udev/data/b%d:%d", major, minor)
_, err := os.Stat(udevDataPath) _, err := os.Stat(udevDataPath)

View File

@ -1136,7 +1136,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) {
var ( var (
testDate = time.Date(2018, 6, 14, 5, 51, 53, 266176036, time.UTC) testDate = time.Date(2018, 6, 14, 5, 51, 53, 266176036, time.UTC)
metricCpuTotal = testutil.MustMetric( metricCPUTotal = testutil.MustMetric(
"docker_container_cpu", "docker_container_cpu",
map[string]string{ map[string]string{
"cpu": "cpu-total", "cpu": "cpu-total",
@ -1144,14 +1144,14 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) {
map[string]interface{}{}, map[string]interface{}{},
testDate) testDate)
metricCpu0 = testutil.MustMetric( metricCPU0 = testutil.MustMetric(
"docker_container_cpu", "docker_container_cpu",
map[string]string{ map[string]string{
"cpu": "cpu0", "cpu": "cpu0",
}, },
map[string]interface{}{}, map[string]interface{}{},
testDate) testDate)
metricCpu1 = testutil.MustMetric( metricCPU1 = testutil.MustMetric(
"docker_container_cpu", "docker_container_cpu",
map[string]string{ map[string]string{
"cpu": "cpu1", "cpu": "cpu1",
@ -1218,7 +1218,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) {
totalInclude: containerMetricClasses, totalInclude: containerMetricClasses,
}, },
expected: []telegraf.Metric{ expected: []telegraf.Metric{
metricCpuTotal, metricCpu0, metricCpu1, metricCPUTotal, metricCPU0, metricCPU1,
metricNetworkTotal, metricNetworkEth0, metricNetworkEth1, metricNetworkTotal, metricNetworkEth0, metricNetworkEth1,
metricBlkioTotal, metricBlkio6_0, metricBlkio6_1, metricBlkioTotal, metricBlkio6_0, metricBlkio6_1,
}, },
@ -1231,7 +1231,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) {
totalInclude: []string{}, totalInclude: []string{},
}, },
expected: []telegraf.Metric{ expected: []telegraf.Metric{
metricCpu0, metricCpu1, metricCPU0, metricCPU1,
metricNetworkEth0, metricNetworkEth1, metricNetworkEth0, metricNetworkEth1,
metricBlkio6_0, metricBlkio6_1, metricBlkio6_0, metricBlkio6_1,
}, },
@ -1243,7 +1243,7 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) {
perDeviceInclude: []string{}, perDeviceInclude: []string{},
totalInclude: containerMetricClasses, totalInclude: containerMetricClasses,
}, },
expected: []telegraf.Metric{metricCpuTotal, metricNetworkTotal, metricBlkioTotal}, expected: []telegraf.Metric{metricCPUTotal, metricNetworkTotal, metricBlkioTotal},
}, },
{ {
name: "Per device and total metrics disabled", name: "Per device and total metrics disabled",

View File

@ -213,20 +213,20 @@ func getFakeFileSystem(basePath string) fakeFileSystem {
var dmask uint32 = 0666 var dmask uint32 = 0666
// set directory bit // set directory bit
dmask |= (1 << uint(32-1)) dmask |= 1 << uint(32-1)
// create a lookup map for getting "files" from the "filesystem" // create a lookup map for getting "files" from the "filesystem"
fileList := map[string]fakeFileInfo{ fileList := map[string]fakeFileInfo{
basePath: {name: "testdata", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, basePath: {name: "testdata", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true},
basePath + "/foo": {name: "foo", filemode: uint32(fmask), modtime: mtime}, basePath + "/foo": {name: "foo", filemode: fmask, modtime: mtime},
basePath + "/bar": {name: "bar", filemode: uint32(fmask), modtime: mtime}, basePath + "/bar": {name: "bar", filemode: fmask, modtime: mtime},
basePath + "/baz": {name: "baz", filemode: uint32(fmask), modtime: olderMtime}, basePath + "/baz": {name: "baz", filemode: fmask, modtime: olderMtime},
basePath + "/qux": {name: "qux", size: int64(400), filemode: uint32(fmask), modtime: mtime}, basePath + "/qux": {name: "qux", size: int64(400), filemode: fmask, modtime: mtime},
basePath + "/subdir": {name: "subdir", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, basePath + "/subdir": {name: "subdir", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true},
basePath + "/subdir/quux": {name: "quux", filemode: uint32(fmask), modtime: mtime}, basePath + "/subdir/quux": {name: "quux", filemode: fmask, modtime: mtime},
basePath + "/subdir/quuz": {name: "quuz", filemode: uint32(fmask), modtime: mtime}, basePath + "/subdir/quuz": {name: "quuz", filemode: fmask, modtime: mtime},
basePath + "/subdir/nested2": {name: "nested2", size: int64(200), filemode: uint32(dmask), modtime: mtime, isdir: true}, basePath + "/subdir/nested2": {name: "nested2", size: int64(200), filemode: dmask, modtime: mtime, isdir: true},
basePath + "/subdir/nested2/qux": {name: "qux", filemode: uint32(fmask), modtime: mtime, size: int64(400)}, basePath + "/subdir/nested2/qux": {name: "qux", filemode: fmask, modtime: mtime, size: int64(400)},
} }
return fakeFileSystem{files: fileList} return fakeFileSystem{files: fileList}

View File

@ -82,11 +82,11 @@ func getTestFileSystem() fakeFileSystem {
var dmask uint32 = 0666 var dmask uint32 = 0666
// set directory bit // set directory bit
dmask |= (1 << uint(32-1)) dmask |= 1 << uint(32-1)
fileList := map[string]fakeFileInfo{ fileList := map[string]fakeFileInfo{
"/testdata": {name: "testdata", size: int64(4096), filemode: uint32(dmask), modtime: mtime, isdir: true}, "/testdata": {name: "testdata", size: int64(4096), filemode: dmask, modtime: mtime, isdir: true},
"/testdata/foo": {name: "foo", filemode: uint32(fmask), modtime: mtime}, "/testdata/foo": {name: "foo", filemode: fmask, modtime: mtime},
} }
return fakeFileSystem{files: fileList} return fakeFileSystem{files: fileList}

View File

@ -23,10 +23,10 @@ type Fireboard struct {
// NewFireboard return a new instance of Fireboard with a default http client // NewFireboard return a new instance of Fireboard with a default http client
func NewFireboard() *Fireboard { func NewFireboard() *Fireboard {
tr := &http.Transport{ResponseHeaderTimeout: time.Duration(3 * time.Second)} tr := &http.Transport{ResponseHeaderTimeout: 3 * time.Second}
client := &http.Client{ client := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
return &Fireboard{client: client} return &Fireboard{client: client}
} }
@ -70,7 +70,7 @@ func (r *Fireboard) Description() string {
// Init the things // Init the things
func (r *Fireboard) Init() error { func (r *Fireboard) Init() error {
if len(r.AuthToken) == 0 { 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 { if len(r.URL) == 0 {
r.URL = "https://fireboard.io/api/v1/devices.json" r.URL = "https://fireboard.io/api/v1/devices.json"

View File

@ -62,7 +62,7 @@ func parse(data []byte) (datapointArray []pluginData, err error) {
var endpointData endpointInfo var endpointData endpointInfo
if err = json.Unmarshal(data, &endpointData); err != nil { if err = json.Unmarshal(data, &endpointData); err != nil {
err = fmt.Errorf("Processing JSON structure") err = fmt.Errorf("processing JSON structure")
return return
} }
@ -83,17 +83,17 @@ func (h *Fluentd) SampleConfig() string { return sampleConfig }
func (h *Fluentd) Gather(acc telegraf.Accumulator) error { func (h *Fluentd) Gather(acc telegraf.Accumulator) error {
_, err := url.Parse(h.Endpoint) _, err := url.Parse(h.Endpoint)
if err != nil { if err != nil {
return fmt.Errorf("Invalid URL \"%s\"", h.Endpoint) return fmt.Errorf("invalid URL \"%s\"", h.Endpoint)
} }
if h.client == nil { if h.client == nil {
tr := &http.Transport{ tr := &http.Transport{
ResponseHeaderTimeout: time.Duration(3 * time.Second), ResponseHeaderTimeout: 3 * time.Second,
} }
client := &http.Client{ client := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
h.client = client h.client = client
@ -102,7 +102,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error {
resp, err := h.client.Get(h.Endpoint) resp, err := h.client.Get(h.Endpoint)
if err != nil { 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() defer resp.Body.Close()
@ -110,7 +110,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error {
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { 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 { if resp.StatusCode != http.StatusOK {
@ -120,7 +120,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error {
dataPoints, err := parse(body) dataPoints, err := parse(body)
if err != nil { if err != nil {
return fmt.Errorf("Problem with parsing") return fmt.Errorf("problem with parsing")
} }
// Go through all plugins one by one // Go through all plugins one by one

View File

@ -100,8 +100,8 @@ var (
// {"object:f48698", "dummy", "input", nil, nil, nil}, // {"object:f48698", "dummy", "input", nil, nil, nil},
// {"object:e27138", "dummy", "input", nil, nil, nil}, // {"object:e27138", "dummy", "input", nil, nil, nil},
// {"object:d74060", "monitor_agent", "input", nil, nil, nil}, // {"object:d74060", "monitor_agent", "input", nil, nil, nil},
{"object:11a5e2c", "stdout", "output", (*float64)(&zero), nil, nil}, {"object:11a5e2c", "stdout", "output", &zero, nil, nil},
{"object:11237ec", "s3", "output", (*float64)(&zero), (*float64)(&zero), (*float64)(&zero)}, {"object:11237ec", "s3", "output", &zero, &zero, &zero},
} }
fluentdTest = &Fluentd{ fluentdTest = &Fluentd{
Endpoint: "http://localhost:8081", Endpoint: "http://localhost:8081",

View File

@ -128,12 +128,12 @@ func (h *GrayLog) Gather(acc telegraf.Accumulator) error {
return err return err
} }
tr := &http.Transport{ tr := &http.Transport{
ResponseHeaderTimeout: time.Duration(3 * time.Second), ResponseHeaderTimeout: 3 * time.Second,
TLSClientConfig: tlsCfg, TLSClientConfig: tlsCfg,
} }
client := &http.Client{ client := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
h.client.SetHTTPClient(client) h.client.SetHTTPClient(client)
} }
@ -233,7 +233,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) {
// Prepare URL // Prepare URL
requestURL, err := url.Parse(serverURL) requestURL, err := url.Parse(serverURL)
if err != nil { 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 // Add X-Requested-By header
headers["X-Requested-By"] = "Telegraf" headers["X-Requested-By"] = "Telegraf"
@ -242,7 +242,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) {
m := &Messagebody{Metrics: h.Metrics} m := &Messagebody{Metrics: h.Metrics}
httpBody, err := json.Marshal(m) httpBody, err := json.Marshal(m)
if err != nil { 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" method = "POST"
content = bytes.NewBuffer(httpBody) content = bytes.NewBuffer(httpBody)
@ -271,7 +271,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) {
// Process response // Process response
if resp.StatusCode != http.StatusOK { 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(), requestURL.String(),
resp.StatusCode, resp.StatusCode,
http.StatusText(resp.StatusCode), http.StatusText(resp.StatusCode),

View File

@ -427,7 +427,7 @@ type buildResponse struct {
} }
func (b *buildResponse) GetTimestamp() time.Time { 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 ( const (
@ -501,7 +501,7 @@ func mapResultCode(s string) int {
func init() { func init() {
inputs.Add("jenkins", func() telegraf.Input { inputs.Add("jenkins", func() telegraf.Input {
return &Jenkins{ return &Jenkins{
MaxBuildAge: internal.Duration{Duration: time.Duration(time.Hour)}, MaxBuildAge: internal.Duration{Duration: time.Hour},
MaxConnections: 5, MaxConnections: 5,
MaxSubJobPerLayer: 10, MaxSubJobPerLayer: 10,
} }

View File

@ -160,7 +160,7 @@ func (j *Jolokia) doRequest(req *http.Request) ([]map[string]interface{}, error)
// Unmarshal json // Unmarshal json
var jsonOut []map[string]interface{} 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) return nil, fmt.Errorf("error decoding JSON response: %s: %s", err, body)
} }

View File

@ -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. // 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 { 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 // Iterate through all the groups and see if we have group with these tags
for _, group := range a { for _, group := range a {

View File

@ -53,7 +53,7 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error {
fields := make(map[string]interface{}) fields := make(map[string]interface{})
fields["entropy_avail"] = int64(entropyValue) fields["entropy_avail"] = entropyValue
dataFields := bytes.Fields(data) dataFields := bytes.Fields(data)
for i, field := range dataFields { for i, field := range dataFields {
@ -63,25 +63,25 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error {
if err != nil { if err != nil {
return err return err
} }
fields["interrupts"] = int64(m) fields["interrupts"] = m
case bytes.Equal(field, contextSwitches): case bytes.Equal(field, contextSwitches):
m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64)
if err != nil { if err != nil {
return err return err
} }
fields["context_switches"] = int64(m) fields["context_switches"] = m
case bytes.Equal(field, processesForked): case bytes.Equal(field, processesForked):
m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64)
if err != nil { if err != nil {
return err return err
} }
fields["processes_forked"] = int64(m) fields["processes_forked"] = m
case bytes.Equal(field, bootTime): case bytes.Equal(field, bootTime):
m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) m, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64)
if err != nil { if err != nil {
return err return err
} }
fields["boot_time"] = int64(m) fields["boot_time"] = m
case bytes.Equal(field, diskPages): case bytes.Equal(field, diskPages):
in, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64) in, err := strconv.ParseInt(string(dataFields[i+1]), 10, 64)
if err != nil { if err != nil {
@ -91,8 +91,8 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error {
if err != nil { if err != nil {
return err return err
} }
fields["disk_pages_in"] = int64(in) fields["disk_pages_in"] = in
fields["disk_pages_out"] = int64(out) fields["disk_pages_out"] = out
} }
} }

View File

@ -45,7 +45,7 @@ func (k *KernelVmstat) Gather(acc telegraf.Accumulator) error {
return err return err
} }
fields[string(field)] = int64(m) fields[string(field)] = m
} }
} }

View File

@ -21,7 +21,6 @@ type client struct {
} }
func newClient(baseURL, namespace, bearerToken string, timeout time.Duration, tlsConfig tls.ClientConfig) (*client, error) { func newClient(baseURL, namespace, bearerToken string, timeout time.Duration, tlsConfig tls.ClientConfig) (*client, error) {
c, err := kubernetes.NewForConfig(&rest.Config{ c, err := kubernetes.NewForConfig(&rest.Config{
TLSClientConfig: rest.TLSClientConfig{ TLSClientConfig: rest.TLSClientConfig{
ServerName: baseURL, ServerName: baseURL,

View File

@ -166,7 +166,7 @@ func atoi(s string) int64 {
if err != nil { if err != nil {
return 0 return 0
} }
return int64(i) return i
} }
func convertQuantity(s string, m float64) int64 { func convertQuantity(s string, m float64) int64 {

View File

@ -124,7 +124,7 @@ func (a *ChimpAPI) GetReport(campaignID string) (Report, error) {
func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) { func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) {
client := &http.Client{ client := &http.Client{
Transport: api.Transport, Transport: api.Transport,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
var b bytes.Buffer var b bytes.Buffer

View File

@ -27,7 +27,7 @@ func TestMarklogic(t *testing.T) {
ml := &Marklogic{ ml := &Marklogic{
Hosts: []string{"example1"}, Hosts: []string{"example1"},
URL: string(ts.URL), URL: ts.URL,
//Sources: []string{"http://localhost:8002/manage/v2/hosts/hostname1?view=status&format=json"}, //Sources: []string{"http://localhost:8002/manage/v2/hosts/hostname1?view=status&format=json"},
} }

View File

@ -568,8 +568,8 @@ func (m *Mesos) gatherMainMetrics(u *url.URL, role Role, acc telegraf.Accumulato
return err return err
} }
if err = json.Unmarshal([]byte(data), &jsonOut); err != nil { if err = json.Unmarshal(data, &jsonOut); err != nil {
return errors.New("Error decoding JSON response") return errors.New("error decoding JSON response")
} }
m.filterMetrics(role, &jsonOut) m.filterMetrics(role, &jsonOut)

View File

@ -61,7 +61,7 @@ func (n *Nats) Gather(acc telegraf.Accumulator) error {
} }
stats := new(gnatsd.Varz) stats := new(gnatsd.Varz)
err = json.Unmarshal([]byte(bytes), &stats) err = json.Unmarshal(bytes, &stats)
if err != nil { if err != nil {
return err return err
} }

View File

@ -363,7 +363,7 @@ func TestParseXML(t *testing.T) {
test := test test := test
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
err := n.parseXML(&acc, []byte(test.xmlResponse)) err := n.parseXML(&acc, test.xmlResponse)
if (err != nil) != test.wantErr { if (err != nil) != test.wantErr {
t.Errorf("err mismatch. got=%v, want=%t", err, test.wantErr) t.Errorf("err mismatch. got=%v, want=%t", err, test.wantErr)
} }

View File

@ -117,7 +117,7 @@ func (n *NetResponse) TCPGather() (tags map[string]string, fields map[string]int
} else { } else {
// Looking for string in answer // Looking for string in answer
RegEx := regexp.MustCompile(`.*` + n.Expect + `.*`) RegEx := regexp.MustCompile(`.*` + n.Expect + `.*`)
find := RegEx.FindString(string(data)) find := RegEx.FindString(data)
if find != "" { if find != "" {
setResult(Success, fields, tags, n.Expect) setResult(Success, fields, tags, n.Expect)
} else { } else {
@ -198,10 +198,10 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error {
} }
// Check send and expected string // Check send and expected string
if n.Protocol == "udp" && n.Send == "" { 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 == "" { 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 // Prepare host and port
host, port, err := net.SplitHostPort(n.Address) host, port, err := net.SplitHostPort(n.Address)
@ -212,7 +212,7 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error {
n.Address = "localhost:" + port n.Address = "localhost:" + port
} }
if port == "" { if port == "" {
return errors.New("Bad port") return errors.New("bad port")
} }
// Prepare data // Prepare data
tags := map[string]string{"server": host, "port": port} tags := map[string]string{"server": host, "port": port}
@ -226,7 +226,7 @@ func (n *NetResponse) Gather(acc telegraf.Accumulator) error {
returnTags, fields = n.UDPGather() returnTags, fields = n.UDPGather()
tags["protocol"] = "udp" tags["protocol"] = "udp"
} else { } else {
return errors.New("Bad protocol") return errors.New("bad protocol")
} }
// Merge the tags // Merge the tags
for k, v := range returnTags { for k, v := range returnTags {

View File

@ -38,7 +38,7 @@ func TestBadProtocol(t *testing.T) {
// Error // Error
err1 := c.Gather(&acc) err1 := c.Gather(&acc)
require.Error(t, err1) require.Error(t, err1)
assert.Equal(t, "Bad protocol", err1.Error()) assert.Equal(t, "bad protocol", err1.Error())
} }
func TestNoPort(t *testing.T) { func TestNoPort(t *testing.T) {
@ -49,7 +49,7 @@ func TestNoPort(t *testing.T) {
} }
err1 := c.Gather(&acc) err1 := c.Gather(&acc)
require.Error(t, err1) require.Error(t, err1)
assert.Equal(t, "Bad port", err1.Error()) assert.Equal(t, "bad port", err1.Error())
} }
func TestAddressOnly(t *testing.T) { func TestAddressOnly(t *testing.T) {
@ -79,10 +79,10 @@ func TestSendExpectStrings(t *testing.T) {
} }
err1 := tc.Gather(&acc) err1 := tc.Gather(&acc)
require.Error(t, err1) 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) err2 := uc.Gather(&acc)
require.Error(t, err2) 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) { func TestTCPError(t *testing.T) {

View File

@ -26,7 +26,7 @@ func TestNFSClientParsev3(t *testing.T) {
data := strings.Fields(" READLINK: 500 501 502 503 504 505 506 507") data := strings.Fields(" READLINK: 500 501 502 503 504 505 506 507")
nfsclient.parseStat("1.2.3.4:/storage/NFS", "/A", "3", data, &acc) nfsclient.parseStat("1.2.3.4:/storage/NFS", "/A", "3", data, &acc)
fields_ops := map[string]interface{}{ fieldsOps := map[string]interface{}{
"ops": int64(500), "ops": int64(500),
"trans": int64(501), "trans": int64(501),
"timeouts": int64(502), "timeouts": int64(502),
@ -36,7 +36,7 @@ func TestNFSClientParsev3(t *testing.T) {
"response_time": int64(506), "response_time": int64(506),
"total_time": int64(507), "total_time": int64(507),
} }
acc.AssertContainsFields(t, "nfs_ops", fields_ops) acc.AssertContainsFields(t, "nfs_ops", fieldsOps)
} }
func TestNFSClientParsev4(t *testing.T) { 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") data := strings.Fields(" DESTROY_SESSION: 500 501 502 503 504 505 506 507")
nfsclient.parseStat("2.2.2.2:/nfsdata/", "/B", "4", data, &acc) nfsclient.parseStat("2.2.2.2:/nfsdata/", "/B", "4", data, &acc)
fields_ops := map[string]interface{}{ fieldsOps := map[string]interface{}{
"ops": int64(500), "ops": int64(500),
"trans": int64(501), "trans": int64(501),
"timeouts": int64(502), "timeouts": int64(502),
@ -58,7 +58,7 @@ func TestNFSClientParsev4(t *testing.T) {
"response_time": int64(506), "response_time": int64(506),
"total_time": int64(507), "total_time": int64(507),
} }
acc.AssertContainsFields(t, "nfs_ops", fields_ops) acc.AssertContainsFields(t, "nfs_ops", fieldsOps)
} }
func TestNFSClientProcessStat(t *testing.T) { func TestNFSClientProcessStat(t *testing.T) {
@ -74,7 +74,7 @@ func TestNFSClientProcessStat(t *testing.T) {
nfsclient.processText(scanner, &acc) nfsclient.processText(scanner, &acc)
fields_readstat := map[string]interface{}{ fieldsReadstat := map[string]interface{}{
"ops": int64(600), "ops": int64(600),
"retrans": int64(1), "retrans": int64(1),
"bytes": int64(1207), "bytes": int64(1207),
@ -82,15 +82,15 @@ func TestNFSClientProcessStat(t *testing.T) {
"exe": int64(607), "exe": int64(607),
} }
read_tags := map[string]string{ readTags := map[string]string{
"serverexport": "1.2.3.4:/storage/NFS", "serverexport": "1.2.3.4:/storage/NFS",
"mountpoint": "/A", "mountpoint": "/A",
"operation": "READ", "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), "ops": int64(700),
"retrans": int64(1), "retrans": int64(1),
"bytes": int64(1407), "bytes": int64(1407),
@ -98,12 +98,12 @@ func TestNFSClientProcessStat(t *testing.T) {
"exe": int64(707), "exe": int64(707),
} }
write_tags := map[string]string{ writeTags := map[string]string{
"serverexport": "1.2.3.4:/storage/NFS", "serverexport": "1.2.3.4:/storage/NFS",
"mountpoint": "/A", "mountpoint": "/A",
"operation": "WRITE", "operation": "WRITE",
} }
acc.AssertContainsTaggedFields(t, "nfsstat", fields_writestat, write_tags) acc.AssertContainsTaggedFields(t, "nfsstat", fieldsWritestat, writeTags)
} }
func TestNFSClientProcessFull(t *testing.T) { func TestNFSClientProcessFull(t *testing.T) {
@ -119,7 +119,7 @@ func TestNFSClientProcessFull(t *testing.T) {
nfsclient.processText(scanner, &acc) nfsclient.processText(scanner, &acc)
fields_events := map[string]interface{}{ fieldsEvents := map[string]interface{}{
"inoderevalidates": int64(301736), "inoderevalidates": int64(301736),
"dentryrevalidates": int64(22838), "dentryrevalidates": int64(22838),
"datainvalidates": int64(410979), "datainvalidates": int64(410979),
@ -148,7 +148,7 @@ func TestNFSClientProcessFull(t *testing.T) {
"pnfsreads": int64(0), "pnfsreads": int64(0),
"pnfswrites": int64(0), "pnfswrites": int64(0),
} }
fields_bytes := map[string]interface{}{ fieldsBytes := map[string]interface{}{
"normalreadbytes": int64(204440464584), "normalreadbytes": int64(204440464584),
"normalwritebytes": int64(110857586443), "normalwritebytes": int64(110857586443),
"directreadbytes": int64(783170354688), "directreadbytes": int64(783170354688),
@ -158,7 +158,7 @@ func TestNFSClientProcessFull(t *testing.T) {
"readpages": int64(85749323), "readpages": int64(85749323),
"writepages": int64(30784819), "writepages": int64(30784819),
} }
fields_xprt_tcp := map[string]interface{}{ fieldsXprtTCP := map[string]interface{}{
"bind_count": int64(1), "bind_count": int64(1),
"connect_count": int64(1), "connect_count": int64(1),
"connect_time": int64(0), "connect_time": int64(0),
@ -170,7 +170,7 @@ func TestNFSClientProcessFull(t *testing.T) {
"backlogutil": int64(0), "backlogutil": int64(0),
} }
acc.AssertContainsFields(t, "nfs_events", fields_events) acc.AssertContainsFields(t, "nfs_events", fieldsEvents)
acc.AssertContainsFields(t, "nfs_bytes", fields_bytes) acc.AssertContainsFields(t, "nfs_bytes", fieldsBytes)
acc.AssertContainsFields(t, "nfs_xprt_tcp", fields_xprt_tcp) acc.AssertContainsFields(t, "nfs_xprt_tcp", fieldsXprtTCP)
} }

View File

@ -111,7 +111,7 @@ func (n *NSQ) getHTTPClient() (*http.Client, error) {
} }
httpClient := &http.Client{ httpClient := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
return httpClient, nil return httpClient, nil
} }
@ -123,7 +123,7 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error {
} }
r, err := n.httpClient.Get(u.String()) r, err := n.httpClient.Get(u.String())
if err != nil { 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() defer r.Body.Close()
@ -133,20 +133,20 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error {
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
return fmt.Errorf(`Error reading body: %s`, err) return fmt.Errorf(`error reading body: %s`, err)
} }
data := &NSQStatsData{} data := &NSQStatsData{}
err = json.Unmarshal(body, data) err = json.Unmarshal(body, data)
if err != nil { 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. // Data was not parsed correctly attempt to use old format.
if len(data.Version) < 1 { if len(data.Version) < 1 {
wrapper := &NSQStats{} wrapper := &NSQStats{}
err = json.Unmarshal(body, wrapper) err = json.Unmarshal(body, wrapper)
if err != nil { if err != nil {
return fmt.Errorf(`Error parsing response: %s`, err) return fmt.Errorf(`error parsing response: %s`, err)
} }
data = &wrapper.Data data = &wrapper.Data
} }
@ -176,7 +176,7 @@ func buildURL(e string) (*url.URL, error) {
u := fmt.Sprintf(requestPattern, e) u := fmt.Sprintf(requestPattern, e)
addr, err := url.Parse(u) addr, err := url.Parse(u)
if err != nil { 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 return addr, nil
} }

View File

@ -126,8 +126,8 @@ func (n *Openntpd) Gather(acc telegraf.Accumulator) error {
fields = strings.Fields(line) fields = strings.Fields(line)
// if there is an ntpctl state prefix, remove it and make it it's own tag // if there is an ntpctl state prefix, remove it and make it it's own tag
if strings.ContainsAny(string(fields[0]), "*") { if strings.ContainsAny(fields[0], "*") {
tags["state_prefix"] = string(fields[0]) tags["state_prefix"] = fields[0]
fields = fields[1:] fields = fields[1:]
} }

View File

@ -32,7 +32,7 @@ type podMetadata struct {
type podResponse struct { type podResponse struct {
Kind string `json:"kind"` Kind string `json:"kind"`
ApiVersion string `json:"apiVersion"` APIVersion string `json:"apiVersion"`
Metadata podMetadata `json:"metadata"` Metadata podMetadata `json:"metadata"`
Items []*corev1.Pod `json:"items,string,omitempty"` 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 { func (p *Prometheus) start(ctx context.Context) error {
config, err := rest.InClusterConfig() config, err := rest.InClusterConfig()
if err != nil { 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) client, err := kubernetes.NewForConfig(config)
if err != nil { if err != nil {
u, err := user.Current() u, err := user.Current()
if err != nil { 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") 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) podsURL := fmt.Sprintf("https://%s:10250/pods", p.NodeIP)
req, err := http.NewRequest("GET", podsURL, nil) req, err := http.NewRequest("GET", podsURL, nil)
if err != 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 // Update right away so code is not waiting the length of the specified scrape interval initially
err = updateCadvisorPodList(p, req) err = updateCadvisorPodList(p, req)
if err != nil { 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 scrapeInterval := cAdvisorPodListDefaultInterval
@ -171,7 +171,7 @@ func (p *Prometheus) cAdvisor(ctx context.Context) error {
case <-time.After(time.Duration(scrapeInterval) * time.Second): case <-time.After(time.Duration(scrapeInterval) * time.Second):
err := updateCadvisorPodList(p, req) err := updateCadvisorPodList(p, req)
if err != nil { 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) resp, err := httpClient.Do(req)
if err != nil { 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 err is nil, still check response code
if resp.StatusCode != 200 { 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() defer resp.Body.Close()

View File

@ -39,7 +39,7 @@ func (r *Raindrops) Gather(acc telegraf.Accumulator) error {
for _, u := range r.Urls { for _, u := range r.Urls {
addr, err := url.Parse(u) addr, err := url.Parse(u)
if err != nil { 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 continue
} }
@ -178,9 +178,9 @@ func init() {
inputs.Add("raindrops", func() telegraf.Input { inputs.Add("raindrops", func() telegraf.Input {
return &Raindrops{httpClient: &http.Client{ return &Raindrops{httpClient: &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
ResponseHeaderTimeout: time.Duration(3 * time.Second), ResponseHeaderTimeout: 3 * time.Second,
}, },
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
}} }}
}) })
} }

View File

@ -62,7 +62,7 @@ func TestRaindropsGeneratesMetrics(t *testing.T) {
n := &Raindrops{ n := &Raindrops{
Urls: []string{fmt.Sprintf("%s/_raindrops", ts.URL)}, Urls: []string{fmt.Sprintf("%s/_raindrops", ts.URL)},
httpClient: &http.Client{Transport: &http.Transport{ httpClient: &http.Client{Transport: &http.Transport{
ResponseHeaderTimeout: time.Duration(3 * time.Second), ResponseHeaderTimeout: 3 * time.Second,
}}, }},
} }

View File

@ -40,10 +40,10 @@ type RavenDB struct {
Log telegraf.Logger `toml:"-"` Log telegraf.Logger `toml:"-"`
client *http.Client client *http.Client
requestUrlServer string requestURLServer string
requestUrlDatabases string requestURLDatabases string
requestUrlIndexes string requestURLIndexes string
requestUrlCollection string requestURLCollection string
} }
var sampleConfig = ` var sampleConfig = `
@ -168,20 +168,20 @@ func (r *RavenDB) requestJSON(u string, target interface{}) error {
func (r *RavenDB) gatherServer(acc telegraf.Accumulator) { func (r *RavenDB) gatherServer(acc telegraf.Accumulator) {
serverResponse := &serverMetricsResponse{} serverResponse := &serverMetricsResponse{}
err := r.requestJSON(r.requestUrlServer, &serverResponse) err := r.requestJSON(r.requestURLServer, &serverResponse)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
return return
} }
tags := map[string]string{ tags := map[string]string{
"cluster_id": serverResponse.Cluster.Id, "cluster_id": serverResponse.Cluster.ID,
"node_tag": serverResponse.Cluster.NodeTag, "node_tag": serverResponse.Cluster.NodeTag,
"url": r.URL, "url": r.URL,
} }
if serverResponse.Config.PublicServerUrl != nil { if serverResponse.Config.PublicServerURL != nil {
tags["public_server_url"] = *serverResponse.Config.PublicServerUrl tags["public_server_url"] = *serverResponse.Config.PublicServerURL
} }
fields := map[string]interface{}{ fields := map[string]interface{}{
@ -192,13 +192,13 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) {
"cluster_index": serverResponse.Cluster.Index, "cluster_index": serverResponse.Cluster.Index,
"cluster_node_state": serverResponse.Cluster.NodeState, "cluster_node_state": serverResponse.Cluster.NodeState,
"config_server_urls": strings.Join(serverResponse.Config.ServerUrls, ";"), "config_server_urls": strings.Join(serverResponse.Config.ServerUrls, ";"),
"cpu_assigned_processor_count": serverResponse.Cpu.AssignedProcessorCount, "cpu_assigned_processor_count": serverResponse.CPU.AssignedProcessorCount,
"cpu_machine_io_wait": serverResponse.Cpu.MachineIoWait, "cpu_machine_io_wait": serverResponse.CPU.MachineIoWait,
"cpu_machine_usage": serverResponse.Cpu.MachineUsage, "cpu_machine_usage": serverResponse.CPU.MachineUsage,
"cpu_process_usage": serverResponse.Cpu.ProcessUsage, "cpu_process_usage": serverResponse.CPU.ProcessUsage,
"cpu_processor_count": serverResponse.Cpu.ProcessorCount, "cpu_processor_count": serverResponse.CPU.ProcessorCount,
"cpu_thread_pool_available_worker_threads": serverResponse.Cpu.ThreadPoolAvailableWorkerThreads, "cpu_thread_pool_available_worker_threads": serverResponse.CPU.ThreadPoolAvailableWorkerThreads,
"cpu_thread_pool_available_completion_port_threads": serverResponse.Cpu.ThreadPoolAvailableCompletionPortThreads, "cpu_thread_pool_available_completion_port_threads": serverResponse.CPU.ThreadPoolAvailableCompletionPortThreads,
"databases_loaded_count": serverResponse.Databases.LoadedCount, "databases_loaded_count": serverResponse.Databases.LoadedCount,
"databases_total_count": serverResponse.Databases.TotalCount, "databases_total_count": serverResponse.Databases.TotalCount,
"disk_remaining_storage_space_percentage": serverResponse.Disk.RemainingStorageSpacePercentage, "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_expiration_left_in_sec": serverResponse.License.ExpirationLeftInSec,
"license_max_cores": serverResponse.License.MaxCores, "license_max_cores": serverResponse.License.MaxCores,
"license_type": serverResponse.License.Type, "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_allocated_in_mb": serverResponse.Memory.AllocatedMemoryInMb,
"memory_installed_in_mb": serverResponse.Memory.InstalledMemoryInMb, "memory_installed_in_mb": serverResponse.Memory.InstalledMemoryInMb,
"memory_low_memory_severity": serverResponse.Memory.LowMemorySeverity, "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_authorized_non_cluster_admin_request_time_in_sec": serverResponse.Network.LastAuthorizedNonClusterAdminRequestTimeInSec,
"network_last_request_time_in_sec": serverResponse.Network.LastRequestTimeInSec, "network_last_request_time_in_sec": serverResponse.Network.LastRequestTimeInSec,
"network_requests_per_sec": serverResponse.Network.RequestsPerSec, "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, "network_total_requests": serverResponse.Network.TotalRequests,
"server_full_version": serverResponse.ServerFullVersion, "server_full_version": serverResponse.ServerFullVersion,
"server_process_id": serverResponse.ServerProcessId, "server_process_id": serverResponse.ServerProcessID,
"server_version": serverResponse.ServerVersion, "server_version": serverResponse.ServerVersion,
"uptime_in_sec": serverResponse.UpTimeInSec, "uptime_in_sec": serverResponse.UpTimeInSec,
} }
if serverResponse.Config.TcpServerUrls != nil { if serverResponse.Config.TCPServerURLs != nil {
fields["config_tcp_server_urls"] = strings.Join(serverResponse.Config.TcpServerUrls, ";") fields["config_tcp_server_urls"] = strings.Join(serverResponse.Config.TCPServerURLs, ";")
} }
if serverResponse.Config.PublicTcpServerUrls != nil { if serverResponse.Config.PublicTCPServerURLs != nil {
fields["config_public_tcp_server_urls"] = strings.Join(serverResponse.Config.PublicTcpServerUrls, ";") fields["config_public_tcp_server_urls"] = strings.Join(serverResponse.Config.PublicTCPServerURLs, ";")
} }
if serverResponse.Certificate.WellKnownAdminCertificates != nil { if serverResponse.Certificate.WellKnownAdminCertificates != nil {
@ -247,7 +247,7 @@ func (r *RavenDB) gatherServer(acc telegraf.Accumulator) {
func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) { func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) {
databasesResponse := &databasesMetricResponse{} databasesResponse := &databasesMetricResponse{}
err := r.requestJSON(r.requestUrlDatabases, &databasesResponse) err := r.requestJSON(r.requestURLDatabases, &databasesResponse)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
return return
@ -255,14 +255,14 @@ func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) {
for _, dbResponse := range databasesResponse.Results { for _, dbResponse := range databasesResponse.Results {
tags := map[string]string{ tags := map[string]string{
"database_id": dbResponse.DatabaseId, "database_id": dbResponse.DatabaseID,
"database_name": dbResponse.DatabaseName, "database_name": dbResponse.DatabaseName,
"node_tag": databasesResponse.NodeTag, "node_tag": databasesResponse.NodeTag,
"url": r.URL, "url": r.URL,
} }
if databasesResponse.PublicServerUrl != nil { if databasesResponse.PublicServerURL != nil {
tags["public_server_url"] = *databasesResponse.PublicServerUrl tags["public_server_url"] = *databasesResponse.PublicServerURL
} }
fields := map[string]interface{}{ fields := map[string]interface{}{
@ -306,7 +306,7 @@ func (r *RavenDB) gatherDatabases(acc telegraf.Accumulator) {
func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) { func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) {
indexesResponse := &indexesMetricResponse{} indexesResponse := &indexesMetricResponse{}
err := r.requestJSON(r.requestUrlIndexes, &indexesResponse) err := r.requestJSON(r.requestURLIndexes, &indexesResponse)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
return return
@ -321,8 +321,8 @@ func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) {
"url": r.URL, "url": r.URL,
} }
if indexesResponse.PublicServerUrl != nil { if indexesResponse.PublicServerURL != nil {
tags["public_server_url"] = *indexesResponse.PublicServerUrl tags["public_server_url"] = *indexesResponse.PublicServerURL
} }
fields := map[string]interface{}{ fields := map[string]interface{}{
@ -347,7 +347,7 @@ func (r *RavenDB) gatherIndexes(acc telegraf.Accumulator) {
func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) { func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) {
collectionsResponse := &collectionsMetricResponse{} collectionsResponse := &collectionsMetricResponse{}
err := r.requestJSON(r.requestUrlCollection, &collectionsResponse) err := r.requestJSON(r.requestURLCollection, &collectionsResponse)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
return return
@ -362,8 +362,8 @@ func (r *RavenDB) gatherCollections(acc telegraf.Accumulator) {
"url": r.URL, "url": r.URL,
} }
if collectionsResponse.PublicServerUrl != nil { if collectionsResponse.PublicServerURL != nil {
tags["public_server_url"] = *collectionsResponse.PublicServerUrl tags["public_server_url"] = *collectionsResponse.PublicServerURL
} }
fields := map[string]interface{}{ 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 { if len(dbNames) == 0 {
return "" return ""
} }
@ -396,10 +396,10 @@ func (r *RavenDB) Init() error {
r.URL = defaultURL r.URL = defaultURL
} }
r.requestUrlServer = r.URL + "/admin/monitoring/v1/server" r.requestURLServer = r.URL + "/admin/monitoring/v1/server"
r.requestUrlDatabases = r.URL + "/admin/monitoring/v1/databases" + prepareDbNamesUrlPart(r.DbStatsDbs) r.requestURLDatabases = r.URL + "/admin/monitoring/v1/databases" + prepareDBNamesURLPart(r.DbStatsDbs)
r.requestUrlIndexes = r.URL + "/admin/monitoring/v1/indexes" + prepareDbNamesUrlPart(r.IndexStatsDbs) r.requestURLIndexes = r.URL + "/admin/monitoring/v1/indexes" + prepareDBNamesURLPart(r.IndexStatsDbs)
r.requestUrlCollection = r.URL + "/admin/monitoring/v1/collections" + prepareDbNamesUrlPart(r.IndexStatsDbs) r.requestURLCollection = r.URL + "/admin/monitoring/v1/collections" + prepareDBNamesURLPart(r.IndexStatsDbs)
err := choice.CheckSlice(r.StatsInclude, []string{"server", "databases", "indexes", "collections"}) err := choice.CheckSlice(r.StatsInclude, []string{"server", "databases", "indexes", "collections"})
if err != nil { if err != nil {

View File

@ -4,10 +4,10 @@ type serverMetricsResponse struct {
ServerVersion string `json:"ServerVersion"` ServerVersion string `json:"ServerVersion"`
ServerFullVersion string `json:"ServerFullVersion"` ServerFullVersion string `json:"ServerFullVersion"`
UpTimeInSec int32 `json:"UpTimeInSec"` UpTimeInSec int32 `json:"UpTimeInSec"`
ServerProcessId int32 `json:"ServerProcessId"` ServerProcessID int32 `json:"ServerProcessId"`
Backup backupMetrics `json:"Backup"` Backup backupMetrics `json:"Backup"`
Config configurationMetrics `json:"Config"` Config configurationMetrics `json:"Config"`
Cpu cpuMetrics `json:"Cpu"` CPU cpuMetrics `json:"Cpu"`
Memory memoryMetrics `json:"Memory"` Memory memoryMetrics `json:"Memory"`
Disk diskMetrics `json:"Disk"` Disk diskMetrics `json:"Disk"`
License licenseMetrics `json:"License"` License licenseMetrics `json:"License"`
@ -24,9 +24,9 @@ type backupMetrics struct {
type configurationMetrics struct { type configurationMetrics struct {
ServerUrls []string `json:"ServerUrls"` ServerUrls []string `json:"ServerUrls"`
PublicServerUrl *string `json:"PublicServerUrl"` PublicServerURL *string `json:"PublicServerUrl"`
TcpServerUrls []string `json:"TcpServerUrls"` TCPServerURLs []string `json:"TcpServerUrls"`
PublicTcpServerUrls []string `json:"PublicTcpServerUrls"` PublicTCPServerURLs []string `json:"PublicTcpServerUrls"`
} }
type cpuMetrics struct { type cpuMetrics struct {
@ -60,12 +60,12 @@ type diskMetrics struct {
type licenseMetrics struct { type licenseMetrics struct {
Type string `json:"Type"` Type string `json:"Type"`
ExpirationLeftInSec *float64 `json:"ExpirationLeftInSec"` ExpirationLeftInSec *float64 `json:"ExpirationLeftInSec"`
UtilizedCpuCores int32 `json:"UtilizedCpuCores"` UtilizedCPUCores int32 `json:"UtilizedCpuCores"`
MaxCores int32 `json:"MaxCores"` MaxCores int32 `json:"MaxCores"`
} }
type networkMetrics struct { type networkMetrics struct {
TcpActiveConnections int64 `json:"TcpActiveConnections"` TCPActiveConnections int64 `json:"TcpActiveConnections"`
ConcurrentRequestsCount int64 `json:"ConcurrentRequestsCount"` ConcurrentRequestsCount int64 `json:"ConcurrentRequestsCount"`
TotalRequests int64 `json:"TotalRequests"` TotalRequests int64 `json:"TotalRequests"`
RequestsPerSec float64 `json:"RequestsPerSec"` RequestsPerSec float64 `json:"RequestsPerSec"`
@ -83,7 +83,7 @@ type clusterMetrics struct {
NodeState string `json:"NodeState"` NodeState string `json:"NodeState"`
CurrentTerm int64 `json:"CurrentTerm"` CurrentTerm int64 `json:"CurrentTerm"`
Index int64 `json:"Index"` Index int64 `json:"Index"`
Id string `json:"Id"` ID string `json:"Id"`
} }
type allDatabasesMetrics struct { type allDatabasesMetrics struct {
@ -93,13 +93,13 @@ type allDatabasesMetrics struct {
type databasesMetricResponse struct { type databasesMetricResponse struct {
Results []*databaseMetrics `json:"Results"` Results []*databaseMetrics `json:"Results"`
PublicServerUrl *string `json:"PublicServerUrl"` PublicServerURL *string `json:"PublicServerUrl"`
NodeTag string `json:"NodeTag"` NodeTag string `json:"NodeTag"`
} }
type databaseMetrics struct { type databaseMetrics struct {
DatabaseName string `json:"DatabaseName"` DatabaseName string `json:"DatabaseName"`
DatabaseId string `json:"DatabaseId"` DatabaseID string `json:"DatabaseId"`
UptimeInSec float64 `json:"UptimeInSec"` UptimeInSec float64 `json:"UptimeInSec"`
TimeSinceLastBackupInSec *float64 `json:"TimeSinceLastBackupInSec"` TimeSinceLastBackupInSec *float64 `json:"TimeSinceLastBackupInSec"`
@ -153,7 +153,7 @@ type databaseStorageMetrics struct {
type indexesMetricResponse struct { type indexesMetricResponse struct {
Results []*perDatabaseIndexMetrics `json:"Results"` Results []*perDatabaseIndexMetrics `json:"Results"`
PublicServerUrl *string `json:"PublicServerUrl"` PublicServerURL *string `json:"PublicServerUrl"`
NodeTag string `json:"NodeTag"` NodeTag string `json:"NodeTag"`
} }
@ -180,7 +180,7 @@ type indexMetrics struct {
type collectionsMetricResponse struct { type collectionsMetricResponse struct {
Results []*perDatabaseCollectionMetrics `json:"Results"` Results []*perDatabaseCollectionMetrics `json:"Results"`
PublicServerUrl *string `json:"PublicServerUrl"` PublicServerURL *string `json:"PublicServerUrl"`
NodeTag string `json:"NodeTag"` NodeTag string `json:"NodeTag"`
} }

View File

@ -73,7 +73,7 @@ type Chassis struct {
type Power struct { type Power struct {
PowerSupplies []struct { PowerSupplies []struct {
Name string Name string
MemberId string MemberID string
PowerInputWatts *float64 PowerInputWatts *float64
PowerCapacityWatts *float64 PowerCapacityWatts *float64
PowerOutputWatts *float64 PowerOutputWatts *float64
@ -83,7 +83,7 @@ type Power struct {
} }
Voltages []struct { Voltages []struct {
Name string Name string
MemberId string MemberID string
ReadingVolts *float64 ReadingVolts *float64
UpperThresholdCritical *float64 UpperThresholdCritical *float64
UpperThresholdFatal *float64 UpperThresholdFatal *float64
@ -96,7 +96,7 @@ type Power struct {
type Thermal struct { type Thermal struct {
Fans []struct { Fans []struct {
Name string Name string
MemberId string MemberID string
Reading *int64 Reading *int64
ReadingUnits *string ReadingUnits *string
UpperThresholdCritical *int64 UpperThresholdCritical *int64
@ -107,7 +107,7 @@ type Thermal struct {
} }
Temperatures []struct { Temperatures []struct {
Name string Name string
MemberId string MemberID string
ReadingCelsius *float64 ReadingCelsius *float64
UpperThresholdCritical *float64 UpperThresholdCritical *float64
UpperThresholdFatal *float64 UpperThresholdFatal *float64
@ -276,7 +276,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error {
for _, j := range thermal.Temperatures { for _, j := range thermal.Temperatures {
tags := map[string]string{} tags := map[string]string{}
tags["member_id"] = j.MemberId tags["member_id"] = j.MemberID
tags["address"] = address tags["address"] = address
tags["name"] = j.Name tags["name"] = j.Name
tags["source"] = system.Hostname tags["source"] = system.Hostname
@ -301,7 +301,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error {
for _, j := range thermal.Fans { for _, j := range thermal.Fans {
tags := map[string]string{} tags := map[string]string{}
fields := make(map[string]interface{}) fields := make(map[string]interface{})
tags["member_id"] = j.MemberId tags["member_id"] = j.MemberID
tags["address"] = address tags["address"] = address
tags["name"] = j.Name tags["name"] = j.Name
tags["source"] = system.Hostname tags["source"] = system.Hostname
@ -333,7 +333,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error {
for _, j := range power.PowerSupplies { for _, j := range power.PowerSupplies {
tags := map[string]string{} tags := map[string]string{}
tags["member_id"] = j.MemberId tags["member_id"] = j.MemberID
tags["address"] = address tags["address"] = address
tags["name"] = j.Name tags["name"] = j.Name
tags["source"] = system.Hostname tags["source"] = system.Hostname
@ -357,7 +357,7 @@ func (r *Redfish) Gather(acc telegraf.Accumulator) error {
for _, j := range power.Voltages { for _, j := range power.Voltages {
tags := map[string]string{} tags := map[string]string{}
tags["member_id"] = j.MemberId tags["member_id"] = j.MemberID
tags["address"] = address tags["address"] = address
tags["name"] = j.Name tags["name"] = j.Name
tags["source"] = system.Hostname tags["source"] = system.Hostname

View File

@ -21,10 +21,10 @@ type Riak struct {
// NewRiak return a new instance of Riak with a default http client // NewRiak return a new instance of Riak with a default http client
func NewRiak() *Riak { func NewRiak() *Riak {
tr := &http.Transport{ResponseHeaderTimeout: time.Duration(3 * time.Second)} tr := &http.Transport{ResponseHeaderTimeout: 3 * time.Second}
client := &http.Client{ client := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(4 * time.Second), Timeout: 4 * time.Second,
} }
return &Riak{client: client} return &Riak{client: client}
} }

View File

@ -62,11 +62,11 @@ const defaultEnvironment = "production"
// returns a new Salesforce plugin instance // returns a new Salesforce plugin instance
func NewSalesforce() *Salesforce { func NewSalesforce() *Salesforce {
tr := &http.Transport{ tr := &http.Transport{
ResponseHeaderTimeout: time.Duration(5 * time.Second), ResponseHeaderTimeout: 5 * time.Second,
} }
client := &http.Client{ client := &http.Client{
Transport: tr, Transport: tr,
Timeout: time.Duration(10 * time.Second), Timeout: 10 * time.Second,
} }
return &Salesforce{ return &Salesforce{
client: client, client: client,
@ -147,7 +147,7 @@ func (s *Salesforce) fetchLimits() (limits, error) {
} }
if resp.StatusCode != http.StatusOK { 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{} l = limits{}

View File

@ -14,7 +14,7 @@ import (
func Test_Gather(t *testing.T) { func Test_Gather(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json") w.Header().Add("Content-Type", "application/json")
_, _ = w.Write([]byte(testJson)) _, _ = w.Write([]byte(testJSON))
})) }))
defer fakeServer.Close() defer fakeServer.Close()
@ -35,7 +35,7 @@ func Test_Gather(t *testing.T) {
require.Len(t, m.Tags, 2) require.Len(t, m.Tags, 2)
} }
var testJson = `{ var testJSON = `{
"ConcurrentAsyncGetReportInstances" : { "ConcurrentAsyncGetReportInstances" : {
"Max" : 200, "Max" : 200,
"Remaining" : 200 "Remaining" : 200

View File

@ -27,14 +27,14 @@ func mockExecCommand(arg0 string, args ...string) *exec.Cmd {
func TestMockExecCommand(_ *testing.T) { func TestMockExecCommand(_ *testing.T) {
var cmd []string var cmd []string
for _, arg := range os.Args { for _, arg := range os.Args {
if string(arg) == "--" { if arg == "--" {
cmd = []string{} cmd = []string{}
continue continue
} }
if cmd == nil { if cmd == nil {
continue continue
} }
cmd = append(cmd, string(arg)) cmd = append(cmd, arg)
} }
if cmd == nil { if cmd == nil {
return return

View File

@ -268,7 +268,7 @@ func findnodename(node Node, ids []string) (string, string) {
return node.name, "0" return node.name, "0"
} else if node.name != "" && len(ids) == 0 && id != "0" { } else if node.name != "" && len(ids) == 0 && id != "0" {
// node with an instance // node with an instance
return node.name, string(id) return node.name, id
} else if node.name != "" && len(ids) > 0 { } else if node.name != "" && len(ids) > 0 {
// node with subinstances // node with subinstances
return node.name, strings.Join(ids, ".") return node.name, strings.Join(ids, ".")
@ -339,7 +339,7 @@ func (s *Snmp) Gather(acc telegraf.Accumulator) error {
} else { } else {
oid.Name = oidstring oid.Name = oidstring
oid.Oid = oidstring oid.Oid = oidstring
if string(oidstring[:1]) != "." { if oidstring[:1] != "." {
oid.rawOid = "." + oidstring oid.rawOid = "." + oidstring
} else { } else {
oid.rawOid = oidstring oid.rawOid = oidstring
@ -764,7 +764,7 @@ func (h *Host) HandleResponse(
var instance string var instance string
// Get oidname and instance from translate file // Get oidname and instance from translate file
oidName, instance = findnodename(initNode, oidName, instance = findnodename(initNode,
strings.Split(string(variable.Name[1:]), ".")) strings.Split(variable.Name[1:], "."))
// Set instance tag // Set instance tag
// From mapping table // From mapping table
mapping, inMappingNoSubTable := h.OidInstanceMapping[oidKey] mapping, inMappingNoSubTable := h.OidInstanceMapping[oidKey]
@ -798,7 +798,7 @@ func (h *Host) HandleResponse(
} }
tags["snmp_host"], _, _ = net.SplitHostPort(h.Address) tags["snmp_host"], _, _ = net.SplitHostPort(h.Address)
fields := make(map[string]interface{}) fields := make(map[string]interface{})
fields[string(fieldName)] = variable.Value fields[fieldName] = variable.Value
h.processedOids = append(h.processedOids, variable.Name) h.processedOids = append(h.processedOids, variable.Name)
acc.AddFields(fieldName, fields, tags) acc.AddFields(fieldName, fields, tags)

View File

@ -6,7 +6,7 @@ import (
) )
const ( const (
emptySqlInstance = "<empty-sql-instance>" emptySQLInstance = "<empty-sql-instance>"
emptyDatabaseName = "<empty-database-name>" emptyDatabaseName = "<empty-database-name>"
) )
@ -15,7 +15,7 @@ const (
// If the connection string could not be parsed or sqlInstance/databaseName were not present, a placeholder value is returned // 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) { func getConnectionIdentifiers(connectionString string) (sqlInstance string, databaseName string) {
if len(connectionString) == 0 { if len(connectionString) == 0 {
return emptySqlInstance, emptyDatabaseName return emptySQLInstance, emptyDatabaseName
} }
trimmedConnectionString := strings.TrimSpace(connectionString) trimmedConnectionString := strings.TrimSpace(connectionString)
@ -61,7 +61,7 @@ func parseConnectionStringKeyValue(connectionString string) (sqlInstance string,
} }
if sqlInstance == "" { if sqlInstance == "" {
sqlInstance = emptySqlInstance sqlInstance = emptySQLInstance
} }
if databaseName == "" { if databaseName == "" {
databaseName = emptyDatabaseName 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 // parseConnectionStringURL parses a URL-formatted connection string and returns the SQL instance and database name
func parseConnectionStringURL(connectionString string) (sqlInstance string, databaseName string) { func parseConnectionStringURL(connectionString string) (sqlInstance string, databaseName string) {
sqlInstance = emptySqlInstance sqlInstance = emptySQLInstance
databaseName = emptyDatabaseName databaseName = emptyDatabaseName
u, err := url.Parse(connectionString) u, err := url.Parse(connectionString)
if err != nil { if err != nil {
return emptySqlInstance, emptyDatabaseName return emptySQLInstance, emptyDatabaseName
} }
sqlInstance = u.Hostname() sqlInstance = u.Hostname()

View File

@ -297,7 +297,7 @@ func TestSqlServer_ConnectionString(t *testing.T) {
connectionString = "invalid connection string" connectionString = "invalid connection string"
sqlInstance, database = getConnectionIdentifiers(connectionString) sqlInstance, database = getConnectionIdentifiers(connectionString)
assert.Equal(t, emptySqlInstance, sqlInstance) assert.Equal(t, emptySQLInstance, sqlInstance)
assert.Equal(t, emptyDatabaseName, database) assert.Equal(t, emptyDatabaseName, database)
// Key/value format // Key/value format
@ -323,7 +323,7 @@ func TestSqlServer_ConnectionString(t *testing.T) {
connectionString = "invalid connection string" connectionString = "invalid connection string"
sqlInstance, database = getConnectionIdentifiers(connectionString) sqlInstance, database = getConnectionIdentifiers(connectionString)
assert.Equal(t, emptySqlInstance, sqlInstance) assert.Equal(t, emptySQLInstance, sqlInstance)
assert.Equal(t, emptyDatabaseName, database) assert.Equal(t, emptyDatabaseName, database)
} }

View File

@ -38,29 +38,29 @@ func (s *Statsd) parseEventMessage(now time.Time, message string, defaultHostnam
// tag is key:value // tag is key:value
messageRaw := strings.SplitN(message, ":", 2) messageRaw := strings.SplitN(message, ":", 2)
if len(messageRaw) < 2 || len(messageRaw[0]) < 7 || len(messageRaw[1]) < 3 { 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] header := messageRaw[0]
message = messageRaw[1] message = messageRaw[1]
rawLen := strings.SplitN(header[3:], ",", 2) rawLen := strings.SplitN(header[3:], ",", 2)
if len(rawLen) != 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) titleLen, err := strconv.ParseInt(rawLen[0], 10, 64)
if err != nil { 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 { 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) textLen, err := strconv.ParseInt(rawLen[1][:len(rawLen[1])-1], 10, 64)
if err != nil { 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)) { 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] rawTitle := message[:titleLen]
@ -68,14 +68,14 @@ func (s *Statsd) parseEventMessage(now time.Time, message string, defaultHostnam
message = message[titleLen+1+textLen:] message = message[titleLen+1+textLen:]
if len(rawTitle) == 0 || len(rawText) == 0 { 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 name := rawTitle
tags := make(map[string]string, strings.Count(message, ",")+2) // allocate for the approximate number of tags tags := make(map[string]string, strings.Count(message, ",")+2) // allocate for the approximate number of tags
fields := make(map[string]interface{}, 9) fields := make(map[string]interface{}, 9)
fields["alert_type"] = eventInfo // default event type fields["alert_type"] = eventInfo // default event type
fields["text"] = uncommenter.Replace(string(rawText)) fields["text"] = uncommenter.Replace(rawText)
if defaultHostname != "" { if defaultHostname != "" {
tags["source"] = defaultHostname tags["source"] = defaultHostname
} }

View File

@ -149,7 +149,7 @@ func flexFlatten(outmap map[string]interface{}, field string, v interface{}, del
case float64: case float64:
outmap[field] = v.(float64) outmap[field] = v.(float64)
default: default:
return fmt.Errorf("Unsupported type %T encountered", t) return fmt.Errorf("unsupported type %T encountered", t)
} }
return nil 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) { func (s *Suricata) parse(acc telegraf.Accumulator, sjson []byte) {
// initial parsing // initial parsing
var result map[string]interface{} var result map[string]interface{}
err := json.Unmarshal([]byte(sjson), &result) err := json.Unmarshal(sjson, &result)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
return return

View File

@ -42,9 +42,11 @@ func TestSuricataLarge(t *testing.T) {
c, err := net.Dial("unix", tmpfn) c, err := net.Dial("unix", tmpfn)
require.NoError(t, err) require.NoError(t, err)
c.Write([]byte(data)) _, err = c.Write(data)
c.Write([]byte("\n")) require.NoError(t, err)
c.Close() _, err = c.Write([]byte("\n"))
require.NoError(t, err)
require.NoError(t, c.Close())
acc.Wait(1) acc.Wait(1)
} }

View File

@ -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 maxRealtimeMetrics = 50000 // Absolute maximum metrics per realtime query
const hwMarkTTL = time.Duration(4 * time.Hour) const hwMarkTTL = 4 * time.Hour
type queryChunk []types.PerfQuerySpec type queryChunk []types.PerfQuerySpec

View File

@ -137,7 +137,7 @@ func (z *Zookeeper) gatherServer(ctx context.Context, address string, acc telegr
fields := make(map[string]interface{}) fields := make(map[string]interface{})
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
parts := zookeeperFormatRE.FindStringSubmatch(string(line)) parts := zookeeperFormatRE.FindStringSubmatch(line)
if len(parts) != 3 { if len(parts) != 3 {
return fmt.Errorf("unexpected line in mntr response: %q", line) 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" { if measurement == "server_state" {
zookeeperState = parts[2] zookeeperState = parts[2]
} else { } else {
sValue := string(parts[2]) sValue := parts[2]
iVal, err := strconv.ParseInt(sValue, 10, 64) iVal, err := strconv.ParseInt(sValue, 10, 64)
if err == nil { if err == nil {

View File

@ -133,11 +133,11 @@ func buildMetrics(m telegraf.Metric) (map[string]Point, error) {
func (p *Point) setValue(v interface{}) error { func (p *Point) setValue(v interface{}) error {
switch d := v.(type) { switch d := v.(type) {
case int: case int:
p[1] = float64(int(d)) p[1] = float64(d)
case int32: case int32:
p[1] = float64(int32(d)) p[1] = float64(d)
case int64: case int64:
p[1] = float64(int64(d)) p[1] = float64(d)
case float32: case float32:
p[1] = float64(d) p[1] = float64(d)
case float64: case float64:

View File

@ -183,7 +183,7 @@ func verifyMetricPublished(t *testing.T, m telegraf.Metric, published map[string
if err != nil { if err != nil {
t.Fatalf("Unable to decode expected base64-encoded message: %s", err) t.Fatalf("Unable to decode expected base64-encoded message: %s", err)
} }
data = []byte(v) data = v
} }
parsed, err := p.Parse(data) parsed, err := p.Parse(data)

View File

@ -20,7 +20,7 @@ import (
const ( const (
oneAgentMetricsURL = "http://127.0.0.1:14499/metrics/ingest" oneAgentMetricsURL = "http://127.0.0.1:14499/metrics/ingest"
dtIngestApiLineLimit = 1000 dtIngestAPILineLimit = 1000
) )
var ( var (
@ -235,7 +235,7 @@ func (d *Dynatrace) Write(metrics []telegraf.Metric) error {
fmt.Fprintf(&buf, "%s%s %v\n", metricID, tagb.String(), value) fmt.Fprintf(&buf, "%s%s %v\n", metricID, tagb.String(), value)
} }
if metricCounter%dtIngestApiLineLimit == 0 { if metricCounter%dtIngestAPILineLimit == 0 {
err = d.send(buf.Bytes()) err = d.send(buf.Bytes())
if err != nil { if err != nil {
return err return err

View File

@ -225,7 +225,7 @@ func verifyValue(v interface{}) bool {
func (g *Gauge) setValue(v interface{}) error { func (g *Gauge) setValue(v interface{}) error {
switch d := v.(type) { switch d := v.(type) {
case int64: case int64:
g.Value = float64(int64(d)) g.Value = float64(d)
case uint64: case uint64:
g.Value = float64(d) g.Value = float64(d)
case float64: case float64:

View File

@ -23,7 +23,7 @@ import (
) )
const ( const (
defaultUrl = "http://127.0.0.1:3031" defaultURL = "http://127.0.0.1:3031"
defaultClientTimeout = 5 * time.Second defaultClientTimeout = 5 * time.Second
defaultContentType = "application/json; charset=utf-8" defaultContentType = "application/json; charset=utf-8"
) )
@ -82,9 +82,9 @@ type SensuMetrics struct {
} }
type Sensu struct { type Sensu struct {
ApiKey *string `toml:"api_key"` APIKey *string `toml:"api_key"`
AgentApiUrl *string `toml:"agent_api_url"` AgentAPIURL *string `toml:"agent_api_url"`
BackendApiUrl *string `toml:"backend_api_url"` BackendAPIURL *string `toml:"backend_api_url"`
Entity *SensuEntity `toml:"entity"` Entity *SensuEntity `toml:"entity"`
Tags map[string]string `toml:"tags"` Tags map[string]string `toml:"tags"`
Metrics *SensuMetrics `toml:"metrics"` Metrics *SensuMetrics `toml:"metrics"`
@ -93,7 +93,7 @@ type Sensu struct {
Timeout config.Duration `toml:"timeout"` Timeout config.Duration `toml:"timeout"`
ContentEncoding string `toml:"content_encoding"` ContentEncoding string `toml:"content_encoding"`
EndpointUrl string EndpointURL string
OutEntity *OutputEntity OutEntity *OutputEntity
Log telegraf.Logger `toml:"-"` Log telegraf.Logger `toml:"-"`
@ -219,7 +219,7 @@ func (s *Sensu) createClient() (*http.Client, error) {
} }
func (s *Sensu) Connect() error { func (s *Sensu) Connect() error {
err := s.setEndpointUrl() err := s.setEndpointURL()
if err != nil { if err != nil {
return err 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 { if err != nil {
return err return err
} }
@ -313,7 +313,7 @@ func (s *Sensu) write(reqBody []byte) error {
reqBodyBuffer = rc reqBodyBuffer = rc
} }
req, err := http.NewRequest(method, s.EndpointUrl, reqBodyBuffer) req, err := http.NewRequest(method, s.EndpointURL, reqBodyBuffer)
if err != nil { if err != nil {
return err return err
} }
@ -325,8 +325,8 @@ func (s *Sensu) write(reqBody []byte) error {
req.Header.Set("Content-Encoding", "gzip") req.Header.Set("Content-Encoding", "gzip")
} }
if s.ApiKey != nil { if s.APIKey != nil {
req.Header.Set("Authorization", "Key "+*s.ApiKey) req.Header.Set("Authorization", "Key "+*s.APIKey)
} }
resp, err := s.client.Do(req) 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)) s.Log.Debugf("Failed to write, response: %v", string(bodyData))
if resp.StatusCode < 400 || resp.StatusCode > 499 { 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 // Resolves the event write endpoint
func (s *Sensu) setEndpointUrl() error { func (s *Sensu) setEndpointURL() error {
var ( var (
endpointUrl string endpointURL string
path_suffix string pathSuffix string
) )
if s.BackendApiUrl != nil { if s.BackendAPIURL != nil {
endpointUrl = *s.BackendApiUrl endpointURL = *s.BackendAPIURL
namespace := "default" namespace := "default"
if s.Entity != nil && s.Entity.Namespace != nil { if s.Entity != nil && s.Entity.Namespace != nil {
namespace = *s.Entity.Namespace namespace = *s.Entity.Namespace
} }
path_suffix = "/api/core/v2/namespaces/" + namespace + "/events" pathSuffix = "/api/core/v2/namespaces/" + namespace + "/events"
} else if s.AgentApiUrl != nil { } else if s.AgentAPIURL != nil {
endpointUrl = *s.AgentApiUrl endpointURL = *s.AgentAPIURL
path_suffix = "/events" pathSuffix = "/events"
} }
if len(endpointUrl) == 0 { if len(endpointURL) == 0 {
s.Log.Debugf("no backend or agent API URL provided, falling back to default agent API URL %s", defaultUrl) s.Log.Debugf("no backend or agent API URL provided, falling back to default agent API URL %s", defaultURL)
endpointUrl = defaultUrl endpointURL = defaultURL
path_suffix = "/events" pathSuffix = "/events"
} }
u, err := url.Parse(endpointUrl) u, err := url.Parse(endpointURL)
if err != nil { if err != nil {
return err return err
} }
u.Path = path.Join(u.Path, path_suffix) u.Path = path.Join(u.Path, pathSuffix)
s.EndpointUrl = u.String() s.EndpointURL = u.String()
return nil return nil
} }
@ -389,12 +389,12 @@ func (s *Sensu) Init() error {
if len(s.ContentEncoding) != 0 { if len(s.ContentEncoding) != 0 {
validEncoding := []string{"identity", "gzip"} validEncoding := []string{"identity", "gzip"}
if !choice.Contains(s.ContentEncoding, validEncoding) { 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 { if s.BackendAPIURL != nil && s.APIKey == nil {
return fmt.Errorf("backend_api_url [%q] specified, but no API Key provided", *s.BackendApiUrl) return fmt.Errorf("backend_api_url [%q] specified, but no API Key provided", *s.BackendAPIURL)
} }
return nil return nil
@ -404,18 +404,18 @@ func init() {
outputs.Add("sensu", func() telegraf.Output { outputs.Add("sensu", func() telegraf.Output {
// Default configuration values // Default configuration values
// make a string from the defaultUrl const // make a string from the defaultURL const
agentApiUrl := defaultUrl agentAPIURL := defaultURL
return &Sensu{ return &Sensu{
AgentApiUrl: &agentApiUrl, AgentAPIURL: &agentAPIURL,
Timeout: config.Duration(defaultClientTimeout), Timeout: config.Duration(defaultClientTimeout),
ContentEncoding: "identity", ContentEncoding: "identity",
} }
}) })
} }
func (s *Sensu) encodeToJson(metricPoints []*OutputMetric) ([]byte, error) { func (s *Sensu) encodeToJSON(metricPoints []*OutputMetric) ([]byte, error) {
timestamp := time.Now().Unix() timestamp := time.Now().Unix()
check, err := s.getCheck(metricPoints) check, err := s.getCheck(metricPoints)
@ -439,7 +439,7 @@ func (s *Sensu) encodeToJson(metricPoints []*OutputMetric) ([]byte, error) {
// Constructs the entity payload // Constructs the entity payload
// Throws when no entity name is provided and fails resolve to hostname // Throws when no entity name is provided and fails resolve to hostname
func (s *Sensu) setEntity() error { func (s *Sensu) setEntity() error {
if s.BackendApiUrl != nil { if s.BackendAPIURL != nil {
var entityName string var entityName string
if s.Entity != nil && s.Entity.Name != nil { if s.Entity != nil && s.Entity.Name != nil {
entityName = *s.Entity.Name entityName = *s.Entity.Name

View File

@ -17,58 +17,58 @@ import (
) )
func TestResolveEventEndpointUrl(t *testing.T) { func TestResolveEventEndpointUrl(t *testing.T) {
agentApiUrl := "http://127.0.0.1:3031" agentAPIURL := "http://127.0.0.1:3031"
backendApiUrl := "http://127.0.0.1:8080" backendAPIURL := "http://127.0.0.1:8080"
entityNamespace := "test-namespace" entityNamespace := "test-namespace"
emptyString := "" emptyString := ""
tests := []struct { tests := []struct {
name string name string
plugin *Sensu plugin *Sensu
expectedEndpointUrl string expectedEndpointURL string
}{ }{
{ {
name: "agent event endpoint", name: "agent event endpoint",
plugin: &Sensu{ plugin: &Sensu{
AgentApiUrl: &agentApiUrl, AgentAPIURL: &agentAPIURL,
Log: testutil.Logger{}, 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", name: "backend event endpoint with default namespace",
plugin: &Sensu{ plugin: &Sensu{
AgentApiUrl: &agentApiUrl, AgentAPIURL: &agentAPIURL,
BackendApiUrl: &backendApiUrl, BackendAPIURL: &backendAPIURL,
Log: testutil.Logger{}, 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", name: "backend event endpoint with namespace declared",
plugin: &Sensu{ plugin: &Sensu{
AgentApiUrl: &agentApiUrl, AgentAPIURL: &agentAPIURL,
BackendApiUrl: &backendApiUrl, BackendAPIURL: &backendAPIURL,
Entity: &SensuEntity{ Entity: &SensuEntity{
Namespace: &entityNamespace, Namespace: &entityNamespace,
}, },
Log: testutil.Logger{}, 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{ plugin: &Sensu{
AgentApiUrl: &emptyString, AgentAPIURL: &emptyString,
Log: testutil.Logger{}, Log: testutil.Logger{},
}, },
expectedEndpointUrl: "http://127.0.0.1:3031/events", expectedEndpointURL: "http://127.0.0.1:3031/events",
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { 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, 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()) ts := httptest.NewServer(http.NotFoundHandler())
defer ts.Close() defer ts.Close()
testUrl := fmt.Sprintf("http://%s", ts.Listener.Addr().String()) testURL := fmt.Sprintf("http://%s", ts.Listener.Addr().String())
testApiKey := "a0b1c2d3-e4f5-g6h7-i8j9-k0l1m2n3o4p5" testAPIKey := "a0b1c2d3-e4f5-g6h7-i8j9-k0l1m2n3o4p5"
testCheck := "telegraf" testCheck := "telegraf"
testEntity := "entity1" testEntity := "entity1"
testNamespace := "default" testNamespace := "default"
testHandler := "influxdb" testHandler := "influxdb"
testTagName := "myTagName" testTagName := "myTagName"
testTagValue := "myTagValue" testTagValue := "myTagValue"
expectedAuthHeader := fmt.Sprintf("Key %s", testApiKey) expectedAuthHeader := fmt.Sprintf("Key %s", testAPIKey)
expectedUrl := fmt.Sprintf("/api/core/v2/namespaces/%s/events", testNamespace) expectedURL := fmt.Sprintf("/api/core/v2/namespaces/%s/events", testNamespace)
expectedPointName := "cpu" expectedPointName := "cpu"
expectedPointValue := float64(42) expectedPointValue := float64(42)
plugin := &Sensu{ plugin := &Sensu{
AgentApiUrl: nil, AgentAPIURL: nil,
BackendApiUrl: &testUrl, BackendAPIURL: &testURL,
ApiKey: &testApiKey, APIKey: &testAPIKey,
Check: &SensuCheck{ Check: &SensuCheck{
Name: &testCheck, Name: &testCheck,
}, },
@ -115,8 +115,8 @@ func TestConnectAndWrite(t *testing.T) {
t.Run("write", func(t *testing.T) { t.Run("write", func(t *testing.T) {
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, expectedUrl, r.URL.String()) require.Equal(t, expectedURL, r.URL.String())
require.Equal(t, expectedAuthHeader, (r.Header.Get("Authorization"))) 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 // 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) body, err := ioutil.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)

View File

@ -71,11 +71,11 @@ var sampleConfig = `
// Connect initiates the primary connection to the GCP project. // Connect initiates the primary connection to the GCP project.
func (s *Stackdriver) Connect() error { func (s *Stackdriver) Connect() error {
if s.Project == "" { 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 == "" { 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 == "" { if s.ResourceType == "" {
@ -300,7 +300,7 @@ func getStackdriverTypedValue(value interface{}) (*monitoringpb.TypedValue, erro
case int64: case int64:
return &monitoringpb.TypedValue{ return &monitoringpb.TypedValue{
Value: &monitoringpb.TypedValue_Int64Value{ Value: &monitoringpb.TypedValue_Int64Value{
Int64Value: int64(v), Int64Value: v,
}, },
}, nil }, nil
case float64: case float64:
@ -312,7 +312,7 @@ func getStackdriverTypedValue(value interface{}) (*monitoringpb.TypedValue, erro
case bool: case bool:
return &monitoringpb.TypedValue{ return &monitoringpb.TypedValue{
Value: &monitoringpb.TypedValue_BoolValue{ Value: &monitoringpb.TypedValue_BoolValue{
BoolValue: bool(v), BoolValue: v,
}, },
}, nil }, nil
case string: case string:

View File

@ -635,8 +635,8 @@ func TestTransformMetricsUnsupportedFieldsAreSkipped(t *testing.T) {
func comparisonTest(t *testing.T, func comparisonTest(t *testing.T,
mappingMode string, mappingMode string,
telegrafMetrics []telegraf.Metric, telegrafMetrics []telegraf.Metric,
timestreamRecords []*timestreamwrite.WriteRecordsInput) { timestreamRecords []*timestreamwrite.WriteRecordsInput,
) {
var plugin ts.Timestream var plugin ts.Timestream
switch mappingMode { switch mappingMode {
case ts.MappingModeSingleTable: case ts.MappingModeSingleTable:
@ -668,8 +668,8 @@ func comparisonTest(t *testing.T,
func arrayContains( func arrayContains(
array []*timestreamwrite.WriteRecordsInput, array []*timestreamwrite.WriteRecordsInput,
element *timestreamwrite.WriteRecordsInput) bool { element *timestreamwrite.WriteRecordsInput,
) bool {
sortWriteInputForComparison(*element) sortWriteInputForComparison(*element)
for _, a := range array { for _, a := range array {

View File

@ -316,7 +316,7 @@ func buildValue(v interface{}, name string, w *Wavefront) (float64, error) {
for prefix, mappings := range w.StringToNumber { for prefix, mappings := range w.StringToNumber {
if strings.HasPrefix(name, prefix) { if strings.HasPrefix(name, prefix) {
for _, mapping := range mappings { for _, mapping := range mappings {
val, hasVal := mapping[string(p)] val, hasVal := mapping[p]
if hasVal { if hasVal {
return val, nil return val, nil
} }

View File

@ -2152,7 +2152,7 @@ func TestStreamMachine(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
tc = append(tc, testcase{ tc = append(tc, testcase{
name: tt.name, name: tt.name,
input: bytes.NewBuffer([]byte(tt.input)), input: bytes.NewBuffer(tt.input),
results: tt.results, results: tt.results,
err: tt.err, err: tt.err,
}) })
@ -2191,7 +2191,7 @@ func TestStreamMachinePosition(t *testing.T) {
for _, tt := range positionTests { for _, tt := range positionTests {
tc = append(tc, testcase{ tc = append(tc, testcase{
name: tt.name, name: tt.name,
input: bytes.NewBuffer([]byte(tt.input)), input: bytes.NewBuffer(tt.input),
lineno: tt.lineno, lineno: tt.lineno,
column: tt.column, column: tt.column,
}) })

View File

@ -194,7 +194,7 @@ func parsePerfData(perfdatas string, timestamp time.Time) ([]telegraf.Metric, er
fieldName := strings.Trim(perf[1], "'") fieldName := strings.Trim(perf[1], "'")
tags := map[string]string{"perfdata": fieldName} tags := map[string]string{"perfdata": fieldName}
if perf[3] != "" { if perf[3] != "" {
str := string(perf[3]) str := perf[3]
if str != "" { if str != "" {
tags["unit"] = str tags["unit"] = str
} }
@ -202,10 +202,10 @@ func parsePerfData(perfdatas string, timestamp time.Time) ([]telegraf.Metric, er
fields := make(map[string]interface{}) fields := make(map[string]interface{})
if perf[2] == "U" { 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 { if err == nil {
fields["value"] = f fields["value"] = f
} }
@ -264,14 +264,14 @@ const (
MinFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52) 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 // Handles all cases from https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT
func parseThreshold(threshold string) (min float64, max float64, err error) { func parseThreshold(threshold string) (min float64, max float64, err error) {
thresh := strings.Split(threshold, ":") thresh := strings.Split(threshold, ":")
switch len(thresh) { switch len(thresh) {
case 1: case 1:
max, err = strconv.ParseFloat(string(thresh[0]), 64) max, err = strconv.ParseFloat(thresh[0], 64)
if err != nil { if err != nil {
return 0, 0, ErrBadThresholdFormat return 0, 0, ErrBadThresholdFormat
} }
@ -281,7 +281,7 @@ func parseThreshold(threshold string) (min float64, max float64, err error) {
if thresh[0] == "~" { if thresh[0] == "~" {
min = MinFloat64 min = MinFloat64
} else { } else {
min, err = strconv.ParseFloat(string(thresh[0]), 64) min, err = strconv.ParseFloat(thresh[0], 64)
if err != nil { if err != nil {
min = 0 min = 0
} }
@ -290,7 +290,7 @@ func parseThreshold(threshold string) (min float64, max float64, err error) {
if thresh[1] == "" { if thresh[1] == "" {
max = MaxFloat64 max = MaxFloat64
} else { } else {
max, err = strconv.ParseFloat(string(thresh[1]), 64) max, err = strconv.ParseFloat(thresh[1], 64)
if err != nil { if err != nil {
return 0, 0, ErrBadThresholdFormat return 0, 0, ErrBadThresholdFormat
} }

View File

@ -28,7 +28,7 @@ func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
if len(values) < 1 { if len(values) < 1 {
return []telegraf.Metric{}, nil return []telegraf.Metric{}, nil
} }
vStr = string(values[len(values)-1]) vStr = values[len(values)-1]
} }
var value interface{} var value interface{}
@ -65,7 +65,7 @@ func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) {
} }
if len(metrics) < 1 { 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 return metrics[0], nil

View File

@ -33,7 +33,7 @@ func TestSerializeMetricFloat(t *testing.T) {
buf, err = s.Serialize(m) buf, err = s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":1529875740.819}` 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) { func TestSerializeMetricFloatHec(t *testing.T) {
@ -53,7 +53,7 @@ func TestSerializeMetricFloatHec(t *testing.T) {
buf, err = s.Serialize(m) buf, err = s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":1529875740.819,"fields":{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` 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) { func TestSerializeMetricInt(t *testing.T) {
@ -73,7 +73,7 @@ func TestSerializeMetricInt(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` 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) { func TestSerializeMetricIntHec(t *testing.T) {
@ -93,7 +93,7 @@ func TestSerializeMetricIntHec(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` 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) { func TestSerializeMetricBool(t *testing.T) {
@ -113,7 +113,7 @@ func TestSerializeMetricBool(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":1,"container-name":"telegraf-test","metric_name":"docker.oomkiller","time":0}` 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) { func TestSerializeMetricBoolHec(t *testing.T) {
@ -133,7 +133,7 @@ func TestSerializeMetricBoolHec(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"_value":0,"container-name":"telegraf-test","metric_name":"docker.oomkiller"}}` 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) { func TestSerializeMetricString(t *testing.T) {
@ -154,7 +154,7 @@ func TestSerializeMetricString(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` 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) assert.NoError(t, err)
} }
@ -186,7 +186,7 @@ func TestSerializeBatch(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":42,"metric_name":"cpu.value","time":0}{"_value":92,"metric_name":"cpu.value","time":0}` 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) { func TestSerializeMulti(t *testing.T) {
@ -208,7 +208,7 @@ func TestSerializeMulti(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"metric_name:cpu.system":8,"metric_name:cpu.user":42,"time":0}` 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) { func TestSerializeBatchHec(t *testing.T) {
@ -239,7 +239,7 @@ func TestSerializeBatchHec(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"_value":42,"metric_name":"cpu.value"}}{"time":0,"fields":{"_value":92,"metric_name":"cpu.value"}}` 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) { func TestSerializeMultiHec(t *testing.T) {
@ -261,5 +261,5 @@ func TestSerializeMultiHec(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"metric_name:cpu.system":8,"metric_name:cpu.usage":42}}` 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))
} }