fix: Linter fixes for plugins/inputs/[h-j]* (#9986)

This commit is contained in:
Paweł Żak 2021-10-26 15:45:03 +02:00 committed by GitHub
parent ecd4d3782c
commit 77248978c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 155 additions and 111 deletions

View File

@ -12,8 +12,9 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
type statServer struct{} type statServer struct{}
@ -134,7 +135,7 @@ func TestHaproxyGeneratesMetricsUsingSocket(t *testing.T) {
} }
sockets[i] = sock sockets[i] = sock
defer sock.Close() defer sock.Close() //nolint:revive // done on purpose, closing will be executed properly
s := statServer{} s := statServer{}
go s.serverSocket(sock) go s.serverSocket(sock)

View File

@ -3,10 +3,11 @@ package hddtemp
import ( import (
"testing" "testing"
hddtemp "github.com/influxdata/telegraf/plugins/inputs/hddtemp/go-hddtemp"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/plugins/inputs/hddtemp/go-hddtemp"
"github.com/influxdata/telegraf/testutil"
) )
type mockFetcher struct { type mockFetcher struct {
@ -33,14 +34,14 @@ func newMockFetcher() *mockFetcher {
} }
func TestFetch(t *testing.T) { func TestFetch(t *testing.T) {
hddtemp := &HDDTemp{ hddTemp := &HDDTemp{
fetcher: newMockFetcher(), fetcher: newMockFetcher(),
Address: "localhost", Address: "localhost",
Devices: []string{"*"}, Devices: []string{"*"},
} }
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}
err := hddtemp.Gather(acc) err := hddTemp.Gather(acc)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, acc.NFields(), 2) assert.Equal(t, acc.NFields(), 2)

View File

@ -9,15 +9,16 @@ import (
"net/url" "net/url"
"testing" "testing"
"github.com/stretchr/testify/require"
httpconfig "github.com/influxdata/telegraf/plugins/common/http" httpconfig "github.com/influxdata/telegraf/plugins/common/http"
oauth "github.com/influxdata/telegraf/plugins/common/oauth" "github.com/influxdata/telegraf/plugins/common/oauth"
plugin "github.com/influxdata/telegraf/plugins/inputs/http" httpplugin "github.com/influxdata/telegraf/plugins/inputs/http"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestHTTPwithJSONFormat(t *testing.T) { func TestHTTPWithJSONFormat(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) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, _ = w.Write([]byte(simpleJSON)) _, _ = w.Write([]byte(simpleJSON))
@ -27,9 +28,9 @@ func TestHTTPwithJSONFormat(t *testing.T) {
})) }))
defer fakeServer.Close() defer fakeServer.Close()
url := fakeServer.URL + "/endpoint" address := fakeServer.URL + "/endpoint"
plugin := &plugin.HTTP{ plugin := &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
} }
metricName := "metricName" metricName := "metricName"
@ -50,7 +51,7 @@ func TestHTTPwithJSONFormat(t *testing.T) {
require.Equal(t, metric.Measurement, metricName) require.Equal(t, metric.Measurement, metricName)
require.Len(t, acc.Metrics[0].Fields, 1) require.Len(t, acc.Metrics[0].Fields, 1)
require.Equal(t, acc.Metrics[0].Fields["a"], 1.2) require.Equal(t, acc.Metrics[0].Fields["a"], 1.2)
require.Equal(t, acc.Metrics[0].Tags["url"], url) require.Equal(t, acc.Metrics[0].Tags["url"], address)
} }
func TestHTTPHeaders(t *testing.T) { func TestHTTPHeaders(t *testing.T) {
@ -69,9 +70,9 @@ func TestHTTPHeaders(t *testing.T) {
})) }))
defer fakeServer.Close() defer fakeServer.Close()
url := fakeServer.URL + "/endpoint" address := fakeServer.URL + "/endpoint"
plugin := &plugin.HTTP{ plugin := &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
Headers: map[string]string{header: headerValue}, Headers: map[string]string{header: headerValue},
} }
@ -92,9 +93,9 @@ func TestInvalidStatusCode(t *testing.T) {
})) }))
defer fakeServer.Close() defer fakeServer.Close()
url := fakeServer.URL + "/endpoint" address := fakeServer.URL + "/endpoint"
plugin := &plugin.HTTP{ plugin := &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
} }
metricName := "metricName" metricName := "metricName"
@ -115,9 +116,9 @@ func TestSuccessStatusCodes(t *testing.T) {
})) }))
defer fakeServer.Close() defer fakeServer.Close()
url := fakeServer.URL + "/endpoint" address := fakeServer.URL + "/endpoint"
plugin := &plugin.HTTP{ plugin := &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
SuccessStatusCodes: []int{200, 202}, SuccessStatusCodes: []int{200, 202},
} }
@ -143,7 +144,7 @@ func TestMethod(t *testing.T) {
})) }))
defer fakeServer.Close() defer fakeServer.Close()
plugin := &plugin.HTTP{ plugin := &httpplugin.HTTP{
URLs: []string{fakeServer.URL}, URLs: []string{fakeServer.URL},
Method: "POST", Method: "POST",
} }
@ -169,18 +170,18 @@ func TestBodyAndContentEncoding(t *testing.T) {
ts := httptest.NewServer(http.NotFoundHandler()) ts := httptest.NewServer(http.NotFoundHandler())
defer ts.Close() defer ts.Close()
url := fmt.Sprintf("http://%s", ts.Listener.Addr().String()) address := fmt.Sprintf("http://%s", ts.Listener.Addr().String())
tests := []struct { tests := []struct {
name string name string
plugin *plugin.HTTP plugin *httpplugin.HTTP
queryHandlerFunc func(t *testing.T, w http.ResponseWriter, r *http.Request) queryHandlerFunc func(t *testing.T, w http.ResponseWriter, r *http.Request)
}{ }{
{ {
name: "no body", name: "no body",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
Method: "POST", Method: "POST",
URLs: []string{url}, URLs: []string{address},
}, },
queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
@ -191,8 +192,8 @@ func TestBodyAndContentEncoding(t *testing.T) {
}, },
{ {
name: "post body", name: "post body",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
Method: "POST", Method: "POST",
Body: "test", Body: "test",
}, },
@ -205,8 +206,8 @@ func TestBodyAndContentEncoding(t *testing.T) {
}, },
{ {
name: "get method body is sent", name: "get method body is sent",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
Method: "GET", Method: "GET",
Body: "test", Body: "test",
}, },
@ -219,8 +220,8 @@ func TestBodyAndContentEncoding(t *testing.T) {
}, },
{ {
name: "gzip encoding", name: "gzip encoding",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
URLs: []string{url}, URLs: []string{address},
Method: "GET", Method: "GET",
Body: "test", Body: "test",
ContentEncoding: "gzip", ContentEncoding: "gzip",
@ -269,13 +270,13 @@ func TestOAuthClientCredentialsGrant(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
plugin *plugin.HTTP plugin *httpplugin.HTTP
tokenHandler TestHandlerFunc tokenHandler TestHandlerFunc
handler TestHandlerFunc handler TestHandlerFunc
}{ }{
{ {
name: "no credentials", name: "no credentials",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
URLs: []string{u.String()}, URLs: []string{u.String()},
}, },
handler: func(t *testing.T, w http.ResponseWriter, r *http.Request) { handler: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
@ -285,7 +286,7 @@ func TestOAuthClientCredentialsGrant(t *testing.T) {
}, },
{ {
name: "success", name: "success",
plugin: &plugin.HTTP{ plugin: &httpplugin.HTTP{
URLs: []string{u.String() + "/write"}, URLs: []string{u.String() + "/write"},
HTTPClientConfig: httpconfig.HTTPClientConfig{ HTTPClientConfig: httpconfig.HTTPClientConfig{
OAuth2Config: oauth.OAuth2Config{ OAuth2Config: oauth.OAuth2Config{

View File

@ -14,10 +14,11 @@ import (
"time" "time"
"github.com/golang/snappy" "github.com/golang/snappy"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -371,6 +372,7 @@ func TestWriteHTTPGzippedData(t *testing.T) {
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.EqualValues(t, 204, resp.StatusCode) require.EqualValues(t, 204, resp.StatusCode)
hostTags := []string{"server02", "server03", hostTags := []string{"server02", "server03",

View File

@ -82,7 +82,7 @@ func (i *Icinga2) SampleConfig() string {
func (i *Icinga2) GatherStatus(acc telegraf.Accumulator, checks []Object) { func (i *Icinga2) GatherStatus(acc telegraf.Accumulator, checks []Object) {
for _, check := range checks { for _, check := range checks {
url, err := url.Parse(i.Server) serverURL, err := url.Parse(i.Server)
if err != nil { if err != nil {
i.Log.Error(err.Error()) i.Log.Error(err.Error())
continue continue
@ -106,9 +106,9 @@ func (i *Icinga2) GatherStatus(acc telegraf.Accumulator, checks []Object) {
"check_command": check.Attrs.CheckCommand, "check_command": check.Attrs.CheckCommand,
"source": source, "source": source,
"state": levels[state], "state": levels[state],
"server": url.Hostname(), "server": serverURL.Hostname(),
"scheme": url.Scheme, "scheme": serverURL.Scheme,
"port": url.Port(), "port": serverURL.Port(),
} }
acc.AddFields(fmt.Sprintf("icinga2_%s", i.ObjectType), fields, tags) acc.AddFields(fmt.Sprintf("icinga2_%s", i.ObjectType), fields, tags)
@ -152,9 +152,9 @@ func (i *Icinga2) Gather(acc telegraf.Accumulator) error {
requestURL += "&attrs=host_name" requestURL += "&attrs=host_name"
} }
url := fmt.Sprintf(requestURL, i.Server, i.ObjectType) address := fmt.Sprintf(requestURL, i.Server, i.ObjectType)
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", address, nil)
if err != nil { if err != nil {
return err return err
} }

View File

@ -13,10 +13,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -416,6 +417,7 @@ func TestWriteGzippedData(t *testing.T) {
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.EqualValues(t, 204, resp.StatusCode) require.EqualValues(t, 204, resp.StatusCode)
hostTags := []string{"server02", "server03", hostTags := []string{"server02", "server03",
@ -526,6 +528,7 @@ func TestQuery(t *testing.T) {
resp, err := http.Post( resp, err := http.Post(
createURL(listener, "http", "/query", "db=&q=CREATE+DATABASE+IF+NOT+EXISTS+%22mydb%22"), "", nil) createURL(listener, "http", "/query", "db=&q=CREATE+DATABASE+IF+NOT+EXISTS+%22mydb%22"), "", nil)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.EqualValues(t, 200, resp.StatusCode) require.EqualValues(t, 200, resp.StatusCode)
} }

View File

@ -15,9 +15,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -374,6 +375,7 @@ func TestWriteGzippedData(t *testing.T) {
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.EqualValues(t, 204, resp.StatusCode) require.EqualValues(t, 204, resp.StatusCode)
hostTags := []string{"server02", "server03", hostTags := []string{"server02", "server03",

View File

@ -57,7 +57,7 @@ func parseInterrupts(r io.Reader) ([]IRQ, error) {
if scanner.Scan() { if scanner.Scan() {
cpus := strings.Fields(scanner.Text()) cpus := strings.Fields(scanner.Text())
if cpus[0] != "CPU0" { if cpus[0] != "CPU0" {
return nil, fmt.Errorf("Expected first line to start with CPU0, but was %s", scanner.Text()) return nil, fmt.Errorf("expected first line to start with CPU0, but was %s", scanner.Text())
} }
cpucount = len(cpus) cpucount = len(cpus)
} }
@ -93,7 +93,7 @@ scan:
irqs = append(irqs, *irq) irqs = append(irqs, *irq)
} }
if scanner.Err() != nil { if scanner.Err() != nil {
return nil, fmt.Errorf("Error scanning file: %s", scanner.Err()) return nil, fmt.Errorf("error scanning file: %s", scanner.Err())
} }
return irqs, nil return irqs, nil
} }
@ -110,15 +110,9 @@ func gatherTagsFields(irq IRQ) (map[string]string, map[string]interface{}) {
func (s *Interrupts) Gather(acc telegraf.Accumulator) error { func (s *Interrupts) Gather(acc telegraf.Accumulator) error {
for measurement, file := range map[string]string{"interrupts": "/proc/interrupts", "soft_interrupts": "/proc/softirqs"} { for measurement, file := range map[string]string{"interrupts": "/proc/interrupts", "soft_interrupts": "/proc/softirqs"} {
f, err := os.Open(file) irqs, err := parseFile(file)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("Could not open file: %s", file)) acc.AddError(err)
continue
}
defer f.Close()
irqs, err := parseInterrupts(f)
if err != nil {
acc.AddError(fmt.Errorf("Parsing %s: %s", file, err))
continue continue
} }
reportMetrics(measurement, irqs, acc, s.CPUAsTag) reportMetrics(measurement, irqs, acc, s.CPUAsTag)
@ -126,6 +120,20 @@ func (s *Interrupts) Gather(acc telegraf.Accumulator) error {
return nil return nil
} }
func parseFile(file string) ([]IRQ, error) {
f, err := os.Open(file)
if err != nil {
return nil, fmt.Errorf("could not open file: %s", file)
}
defer f.Close()
irqs, err := parseInterrupts(f)
if err != nil {
return nil, fmt.Errorf("parsing %s: %s", file, err)
}
return irqs, nil
}
func reportMetrics(measurement string, irqs []IRQ, acc telegraf.Accumulator, cpusAsTags bool) { func reportMetrics(measurement string, irqs []IRQ, acc telegraf.Accumulator, cpusAsTags bool) {
for _, irq := range irqs { for _, irq := range irqs {
tags, fields := gatherTagsFields(irq) tags, fields := gatherTagsFields(irq)

View File

@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"log"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -39,6 +38,8 @@ type Ipmi struct {
UseSudo bool UseSudo bool
UseCache bool UseCache bool
CachePath string CachePath string
Log telegraf.Logger `toml:"-"`
} }
var sampleConfig = ` var sampleConfig = `
@ -172,17 +173,17 @@ func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out)) return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
} }
if m.MetricVersion == 2 { if m.MetricVersion == 2 {
return parseV2(acc, hostname, out, timestamp) return m.parseV2(acc, hostname, out, timestamp)
} }
return parseV1(acc, hostname, out, timestamp) return m.parseV1(acc, hostname, out, timestamp)
} }
func parseV1(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredAt time.Time) error { func (m *Ipmi) parseV1(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredAt time.Time) error {
// each line will look something like // each line will look something like
// Planar VBAT | 3.05 Volts | ok // Planar VBAT | 3.05 Volts | ok
scanner := bufio.NewScanner(bytes.NewReader(cmdOut)) scanner := bufio.NewScanner(bytes.NewReader(cmdOut))
for scanner.Scan() { for scanner.Scan() {
ipmiFields := extractFieldsFromRegex(reV1ParseLine, scanner.Text()) ipmiFields := m.extractFieldsFromRegex(reV1ParseLine, scanner.Text())
if len(ipmiFields) != 3 { if len(ipmiFields) != 3 {
continue continue
} }
@ -234,14 +235,14 @@ func parseV1(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredA
return scanner.Err() return scanner.Err()
} }
func parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredAt time.Time) error { func (m *Ipmi) parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredAt time.Time) error {
// each line will look something like // each line will look something like
// CMOS Battery | 65h | ok | 7.1 | // CMOS Battery | 65h | ok | 7.1 |
// Temp | 0Eh | ok | 3.1 | 55 degrees C // Temp | 0Eh | ok | 3.1 | 55 degrees C
// Drive 0 | A0h | ok | 7.1 | Drive Present // Drive 0 | A0h | ok | 7.1 | Drive Present
scanner := bufio.NewScanner(bytes.NewReader(cmdOut)) scanner := bufio.NewScanner(bytes.NewReader(cmdOut))
for scanner.Scan() { for scanner.Scan() {
ipmiFields := extractFieldsFromRegex(reV2ParseLine, scanner.Text()) ipmiFields := m.extractFieldsFromRegex(reV2ParseLine, scanner.Text())
if len(ipmiFields) < 3 || len(ipmiFields) > 4 { if len(ipmiFields) < 3 || len(ipmiFields) > 4 {
continue continue
} }
@ -257,7 +258,7 @@ func parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredA
tags["entity_id"] = transform(ipmiFields["entity_id"]) tags["entity_id"] = transform(ipmiFields["entity_id"])
tags["status_code"] = trim(ipmiFields["status_code"]) tags["status_code"] = trim(ipmiFields["status_code"])
fields := make(map[string]interface{}) fields := make(map[string]interface{})
descriptionResults := extractFieldsFromRegex(reV2ParseDescription, trim(ipmiFields["description"])) descriptionResults := m.extractFieldsFromRegex(reV2ParseDescription, trim(ipmiFields["description"]))
// This is an analog value with a unit // This is an analog value with a unit
if descriptionResults["analogValue"] != "" && len(descriptionResults["analogUnit"]) >= 1 { if descriptionResults["analogValue"] != "" && len(descriptionResults["analogUnit"]) >= 1 {
var err error var err error
@ -266,7 +267,7 @@ func parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredA
continue continue
} }
// Some implementations add an extra status to their analog units // Some implementations add an extra status to their analog units
unitResults := extractFieldsFromRegex(reV2ParseUnit, descriptionResults["analogUnit"]) unitResults := m.extractFieldsFromRegex(reV2ParseUnit, descriptionResults["analogUnit"])
tags["unit"] = transform(unitResults["realAnalogUnit"]) tags["unit"] = transform(unitResults["realAnalogUnit"])
if unitResults["statusDesc"] != "" { if unitResults["statusDesc"] != "" {
tags["status_desc"] = transform(unitResults["statusDesc"]) tags["status_desc"] = transform(unitResults["statusDesc"])
@ -289,12 +290,12 @@ func parseV2(acc telegraf.Accumulator, hostname string, cmdOut []byte, measuredA
} }
// extractFieldsFromRegex consumes a regex with named capture groups and returns a kvp map of strings with the results // extractFieldsFromRegex consumes a regex with named capture groups and returns a kvp map of strings with the results
func extractFieldsFromRegex(re *regexp.Regexp, input string) map[string]string { func (m *Ipmi) extractFieldsFromRegex(re *regexp.Regexp, input string) map[string]string {
submatches := re.FindStringSubmatch(input) submatches := re.FindStringSubmatch(input)
results := make(map[string]string) results := make(map[string]string)
subexpNames := re.SubexpNames() subexpNames := re.SubexpNames()
if len(subexpNames) > len(submatches) { if len(subexpNames) > len(submatches) {
log.Printf("D! No matches found in '%s'", input) m.Log.Debugf("No matches found in '%s'", input)
return results return results
} }
for i, name := range subexpNames { for i, name := range subexpNames {

View File

@ -7,10 +7,11 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestGather(t *testing.T) { func TestGather(t *testing.T) {
@ -20,6 +21,7 @@ func TestGather(t *testing.T) {
Privilege: "USER", Privilege: "USER",
Timeout: config.Duration(time.Second * 5), Timeout: config.Duration(time.Second * 5),
HexKey: "1234567F", HexKey: "1234567F",
Log: testutil.Logger{},
} }
// overwriting exec commands with mock commands // overwriting exec commands with mock commands
@ -44,7 +46,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(20), "value": float64(20),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "ambient_temp", "name": "ambient_temp",
@ -55,7 +57,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(80), "value": float64(80),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "altitude", "name": "altitude",
@ -66,7 +68,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(210), "value": float64(210),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "avg_power", "name": "avg_power",
@ -77,7 +79,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(4.9), "value": float64(4.9),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "planar_5v", "name": "planar_5v",
@ -88,7 +90,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(3.05), "value": float64(3.05),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "planar_vbat", "name": "planar_vbat",
@ -99,7 +101,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(2610), "value": float64(2610),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "fan_1a_tach", "name": "fan_1a_tach",
@ -110,7 +112,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(1775), "value": float64(1775),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "fan_1b_tach", "name": "fan_1b_tach",
@ -127,6 +129,7 @@ func TestGather(t *testing.T) {
i = &Ipmi{ i = &Ipmi{
Path: "ipmitool", Path: "ipmitool",
Timeout: config.Duration(time.Second * 5), Timeout: config.Duration(time.Second * 5),
Log: testutil.Logger{},
} }
err = acc.GatherError(i.Gather) err = acc.GatherError(i.Gather)
@ -139,7 +142,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(20), "value": float64(20),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "ambient_temp", "name": "ambient_temp",
@ -149,7 +152,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(80), "value": float64(80),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "altitude", "name": "altitude",
@ -159,7 +162,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(210), "value": float64(210),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "avg_power", "name": "avg_power",
@ -169,7 +172,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(4.9), "value": float64(4.9),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "planar_5v", "name": "planar_5v",
@ -179,7 +182,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(3.05), "value": float64(3.05),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "planar_vbat", "name": "planar_vbat",
@ -189,7 +192,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(2610), "value": float64(2610),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "fan_1a_tach", "name": "fan_1a_tach",
@ -199,7 +202,7 @@ func TestGather(t *testing.T) {
{ {
map[string]interface{}{ map[string]interface{}{
"value": float64(1775), "value": float64(1775),
"status": int(1), "status": 1,
}, },
map[string]string{ map[string]string{
"name": "fan_1b_tach", "name": "fan_1b_tach",
@ -371,7 +374,7 @@ OS RealTime Mod | 0x00 | ok
// Previous arguments are tests stuff, that looks like : // Previous arguments are tests stuff, that looks like :
// /tmp/go-build970079519/…/_test/integration.test -test.run=TestHelperProcess -- // /tmp/go-build970079519/…/_test/integration.test -test.run=TestHelperProcess --
cmd, args := args[3], args[4:] cmd := args[3]
// Ignore the returned errors for the mocked interface as tests will fail anyway // Ignore the returned errors for the mocked interface as tests will fail anyway
if cmd == "ipmitool" { if cmd == "ipmitool" {
@ -380,8 +383,10 @@ OS RealTime Mod | 0x00 | ok
} else { } else {
//nolint:errcheck,revive //nolint:errcheck,revive
fmt.Fprint(os.Stdout, "command not found") fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1) os.Exit(1)
} }
//nolint:revive // error code is important for this "test"
os.Exit(0) os.Exit(0)
} }
@ -393,6 +398,7 @@ func TestGatherV2(t *testing.T) {
Timeout: config.Duration(time.Second * 5), Timeout: config.Duration(time.Second * 5),
MetricVersion: 2, MetricVersion: 2,
HexKey: "0000000F", HexKey: "0000000F",
Log: testutil.Logger{},
} }
// overwriting exec commands with mock commands // overwriting exec commands with mock commands
execCommand = fakeExecCommandV2 execCommand = fakeExecCommandV2
@ -434,6 +440,7 @@ func TestGatherV2(t *testing.T) {
Path: "ipmitool", Path: "ipmitool",
Timeout: config.Duration(time.Second * 5), Timeout: config.Duration(time.Second * 5),
MetricVersion: 2, MetricVersion: 2,
Log: testutil.Logger{},
} }
err = acc.GatherError(i.Gather) err = acc.GatherError(i.Gather)
@ -568,7 +575,7 @@ Power Supply 1 | 03h | ok | 10.1 | 110 Watts, Presence detected
// Previous arguments are tests stuff, that looks like : // Previous arguments are tests stuff, that looks like :
// /tmp/go-build970079519/…/_test/integration.test -test.run=TestHelperProcess -- // /tmp/go-build970079519/…/_test/integration.test -test.run=TestHelperProcess --
cmd, args := args[3], args[4:] cmd := args[3]
// Ignore the returned errors for the mocked interface as tests will fail anyway // Ignore the returned errors for the mocked interface as tests will fail anyway
if cmd == "ipmitool" { if cmd == "ipmitool" {
@ -577,8 +584,10 @@ Power Supply 1 | 03h | ok | 10.1 | 110 Watts, Presence detected
} else { } else {
//nolint:errcheck,revive //nolint:errcheck,revive
fmt.Fprint(os.Stdout, "command not found") fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // error code is important for this "test"
os.Exit(1) os.Exit(1)
} }
//nolint:revive // error code is important for this "test"
os.Exit(0) os.Exit(0)
} }
@ -613,10 +622,14 @@ Power Supply 1 | 03h | ok | 10.1 | 110 Watts, Presence detected
v2Data, v2Data,
} }
ipmi := &Ipmi{
Log: testutil.Logger{},
}
for i := range tests { for i := range tests {
t.Logf("Checking v%d data...", i+1) t.Logf("Checking v%d data...", i+1)
extractFieldsFromRegex(reV1ParseLine, tests[i]) ipmi.extractFieldsFromRegex(reV1ParseLine, tests[i])
extractFieldsFromRegex(reV2ParseLine, tests[i]) ipmi.extractFieldsFromRegex(reV2ParseLine, tests[i])
} }
} }
@ -653,11 +666,16 @@ func Test_parseV1(t *testing.T) {
wantErr: false, wantErr: false,
}, },
} }
ipmi := &Ipmi{
Log: testutil.Logger{},
}
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
if err := parseV1(&acc, tt.args.hostname, tt.args.cmdOut, tt.args.measuredAt); (err != nil) != tt.wantErr { if err := ipmi.parseV1(&acc, tt.args.hostname, tt.args.cmdOut, tt.args.measuredAt); (err != nil) != tt.wantErr {
t.Errorf("parseV1() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("parseV1() error = %v, wantErr %v", err, tt.wantErr)
} }
@ -746,10 +764,15 @@ func Test_parseV2(t *testing.T) {
wantErr: false, wantErr: false,
}, },
} }
ipmi := &Ipmi{
Log: testutil.Logger{},
}
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
if err := parseV2(&acc, tt.args.hostname, tt.args.cmdOut, tt.args.measuredAt); (err != nil) != tt.wantErr { if err := ipmi.parseV2(&acc, tt.args.hostname, tt.args.cmdOut, tt.args.measuredAt); (err != nil) != tt.wantErr {
t.Errorf("parseV2() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("parseV2() error = %v, wantErr %v", err, tt.wantErr)
} }
testutil.RequireMetricsEqual(t, tt.expected, acc.GetTelegrafMetrics(), testutil.IgnoreTime()) testutil.RequireMetricsEqual(t, tt.expected, acc.GetTelegrafMetrics(), testutil.IgnoreTime())

View File

@ -44,13 +44,13 @@ func TestJobRequest(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
hierarchyName := test.input.hierarchyName() hierarchyName := test.input.hierarchyName()
URL := test.input.URL() address := test.input.URL()
if hierarchyName != test.hierarchyName { if hierarchyName != test.hierarchyName {
t.Errorf("Expected %s, got %s\n", test.hierarchyName, hierarchyName) t.Errorf("Expected %s, got %s\n", test.hierarchyName, hierarchyName)
} }
if test.URL != "" && URL != test.URL { if test.URL != "" && address != test.URL {
t.Errorf("Expected %s, got %s\n", test.URL, URL) t.Errorf("Expected %s, got %s\n", test.URL, address)
} }
} }
} }
@ -429,7 +429,7 @@ func TestInitialize(t *testing.T) {
} }
if test.output != nil { if test.output != nil {
if test.input.client == nil { if test.input.client == nil {
t.Fatalf("%s: failed %s, jenkins instance shouldn't be nil", test.name, te.Error()) t.Fatalf("%s: failed %v, jenkins instance shouldn't be nil", test.name, te)
} }
if test.input.MaxConnections != test.output.MaxConnections { if test.input.MaxConnections != test.output.MaxConnections {
t.Fatalf("%s: different MaxConnections Expected %d, got %d\n", test.name, test.output.MaxConnections, test.input.MaxConnections) t.Fatalf("%s: different MaxConnections Expected %d, got %d\n", test.name, test.output.MaxConnections, test.input.MaxConnections)

View File

@ -95,7 +95,7 @@ type jolokiaResponse struct {
Status int `json:"status"` Status int `json:"status"`
} }
func NewClient(url string, config *ClientConfig) (*Client, error) { func NewClient(address string, config *ClientConfig) (*Client, error) {
tlsConfig, err := config.ClientConfig.TLSConfig() tlsConfig, err := config.ClientConfig.TLSConfig()
if err != nil { if err != nil {
return nil, err return nil, err
@ -112,7 +112,7 @@ func NewClient(url string, config *ClientConfig) (*Client, error) {
} }
return &Client{ return &Client{
URL: url, URL: address,
config: config, config: config,
client: client, client: client,
}, nil }, nil

View File

@ -80,7 +80,7 @@ func (g *Gatherer) generatePoints(metric Metric, responses []ReadResponse) ([]po
for _, response := range responses { for _, response := range responses {
switch response.Status { switch response.Status {
case 200: case 200:
break // Correct response status - do nothing.
case 404: case 404:
continue continue
default: default:

View File

@ -68,7 +68,7 @@ func (ja *JolokiaAgent) Gather(acc telegraf.Accumulator) error {
for _, url := range ja.URLs { for _, url := range ja.URLs {
client, err := ja.createClient(url) client, err := ja.createClient(url)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("Unable to create client for %s: %v", url, err)) acc.AddError(fmt.Errorf("unable to create client for %s: %v", url, err))
continue continue
} }
ja.clients = append(ja.clients, client) ja.clients = append(ja.clients, client)
@ -97,8 +97,8 @@ func (ja *JolokiaAgent) Gather(acc telegraf.Accumulator) error {
func (ja *JolokiaAgent) createMetrics() []Metric { func (ja *JolokiaAgent) createMetrics() []Metric {
var metrics []Metric var metrics []Metric
for _, config := range ja.Metrics { for _, metricConfig := range ja.Metrics {
metrics = append(metrics, NewMetric(config, metrics = append(metrics, NewMetric(metricConfig,
ja.DefaultFieldPrefix, ja.DefaultFieldSeparator, ja.DefaultTagPrefix)) ja.DefaultFieldPrefix, ja.DefaultFieldSeparator, ja.DefaultTagPrefix))
} }

View File

@ -93,8 +93,8 @@ func (jp *JolokiaProxy) Gather(acc telegraf.Accumulator) error {
func (jp *JolokiaProxy) createMetrics() []Metric { func (jp *JolokiaProxy) createMetrics() []Metric {
var metrics []Metric var metrics []Metric
for _, config := range jp.Metrics { for _, metricConfig := range jp.Metrics {
metrics = append(metrics, NewMetric(config, metrics = append(metrics, NewMetric(metricConfig,
jp.DefaultFieldPrefix, jp.DefaultFieldSeparator, jp.DefaultTagPrefix)) jp.DefaultFieldPrefix, jp.DefaultFieldSeparator, jp.DefaultTagPrefix))
} }

View File

@ -6,11 +6,12 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/influxdata/toml" "github.com/influxdata/toml"
"github.com/influxdata/toml/ast" "github.com/influxdata/toml/ast"
"github.com/stretchr/testify/assert"
) )
func TestJolokia2_ScalarValues(t *testing.T) { func TestJolokia2_ScalarValues(t *testing.T) {
@ -749,15 +750,15 @@ func TestJolokia2_ProxyTargets(t *testing.T) {
} }
func TestFillFields(t *testing.T) { func TestFillFields(t *testing.T) {
complex := map[string]interface{}{"Value": []interface{}{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}} complexPoint := map[string]interface{}{"Value": []interface{}{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}
scalar := []interface{}{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} scalarPoint := []interface{}{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
results := map[string]interface{}{} results := map[string]interface{}{}
newPointBuilder(Metric{Name: "test", Mbean: "complex"}, []string{"this", "that"}, "/").fillFields("", complex, results) newPointBuilder(Metric{Name: "test", Mbean: "complex"}, []string{"this", "that"}, "/").fillFields("", complexPoint, results)
assert.Equal(t, map[string]interface{}{}, results) assert.Equal(t, map[string]interface{}{}, results)
results = map[string]interface{}{} results = map[string]interface{}{}
newPointBuilder(Metric{Name: "test", Mbean: "scalar"}, []string{"this", "that"}, "/").fillFields("", scalar, results) newPointBuilder(Metric{Name: "test", Mbean: "scalar"}, []string{"this", "that"}, "/").fillFields("", scalarPoint, results)
assert.Equal(t, map[string]interface{}{}, results) assert.Equal(t, map[string]interface{}{}, results)
} }

View File

@ -8,17 +8,18 @@ import (
"sync" "sync"
"time" "time"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
internaltls "github.com/influxdata/telegraf/plugins/common/tls" internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/auth" "github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/auth"
"github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/oc" "github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/oc"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
) )
type OpenConfigTelemetry struct { type OpenConfigTelemetry struct {
@ -42,7 +43,7 @@ type OpenConfigTelemetry struct {
var ( var (
// Regex to match and extract data points from path value in received key // Regex to match and extract data points from path value in received key
keyPathRegex = regexp.MustCompile("\\/([^\\/]*)\\[([A-Za-z0-9\\-\\/]*\\=[^\\[]*)\\]") keyPathRegex = regexp.MustCompile(`/([^/]*)\[([A-Za-z0-9\-/]*=[^\[]*)]`)
sampleConfig = ` sampleConfig = `
## List of device addresses to collect telemetry from ## List of device addresses to collect telemetry from
servers = ["localhost:1883"] servers = ["localhost:1883"]