fix: Linter fixes for plugins/common/[a-z]* (#10189)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2021-11-30 22:46:46 +01:00 committed by GitHub
parent 27dea9bd8f
commit 3627961add
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 80 additions and 61 deletions

View File

@ -27,8 +27,7 @@ func (x *XDGSCRAMClient) Begin(userName, password, authzID string) (err error) {
}
func (x *XDGSCRAMClient) Step(challenge string) (response string, err error) {
response, err = x.ClientConversation.Step(challenge)
return
return x.ClientConversation.Step(challenge)
}
func (x *XDGSCRAMClient) Done() bool {

View File

@ -14,7 +14,7 @@ var once sync.Once
type LogHook struct {
}
// Install a logging hook into the logrus standard logger, diverting all logs
// InstallHook installs a logging hook into the logrus standard logger, diverting all logs
// through the Telegraf logger at debug level. This is useful for libraries
// that directly log to the logrus system without providing an override method.
func InstallHook() {

View File

@ -14,11 +14,11 @@ type proxyFunc func(req *http.Request) (*url.URL, error)
func (p *HTTPProxy) Proxy() (proxyFunc, error) {
if len(p.HTTPProxyURL) > 0 {
url, err := url.Parse(p.HTTPProxyURL)
address, err := url.Parse(p.HTTPProxyURL)
if err != nil {
return nil, fmt.Errorf("error parsing proxy url %q: %w", p.HTTPProxyURL, err)
}
return http.ProxyURL(url), nil
return http.ProxyURL(address), nil
}
return http.ProxyFromEnvironment, nil
}

View File

@ -5,16 +5,19 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
tgConfig "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/processors"
"github.com/stretchr/testify/require"
)
func TestLoadConfig(t *testing.T) {
os.Setenv("SECRET_TOKEN", "xxxxxxxxxx")
os.Setenv("SECRET_VALUE", `test"\test`)
err := os.Setenv("SECRET_TOKEN", "xxxxxxxxxx")
require.NoError(t, err)
err = os.Setenv("SECRET_VALUE", `test"\test`)
require.NoError(t, err)
inputs.Add("test", func() telegraf.Input {
return &serviceInput{}

View File

@ -84,13 +84,13 @@ func (s *Shim) Run(pollInterval time.Duration) error {
if err != nil {
return fmt.Errorf("RunProcessor error: %w", err)
}
} else if s.Output != nil {
} else if s.Output != nil { //nolint:revive // Not simplifying here to stay in the structure for better understanding the code
err := s.RunOutput()
if err != nil {
return fmt.Errorf("RunOutput error: %w", err)
}
} else {
return fmt.Errorf("Nothing to run")
return fmt.Errorf("nothing to run")
}
return nil
@ -102,7 +102,7 @@ func hasQuit(ctx context.Context) bool {
func (s *Shim) writeProcessedMetrics() error {
serializer := influx.NewSerializer()
for {
for { //nolint:gosimple // for-select used on purpose
select {
case m, open := <-s.metricCh:
if !open {
@ -113,7 +113,10 @@ func (s *Shim) writeProcessedMetrics() error {
return fmt.Errorf("failed to serialize metric: %s", err)
}
// Write this to stdout
fmt.Fprint(s.stdout, string(b))
_, err = fmt.Fprint(s.stdout, string(b))
if err != nil {
return fmt.Errorf("failed to write metric: %s", err)
}
}
}
}

View File

@ -8,8 +8,9 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
)
func TestShimSetsUpLogger(t *testing.T) {
@ -18,7 +19,8 @@ func TestShimSetsUpLogger(t *testing.T) {
runErroringInputPlugin(t, 40*time.Second, stdinReader, nil, stderrWriter)
stdinWriter.Write([]byte("\n"))
_, err := stdinWriter.Write([]byte("\n"))
require.NoError(t, err)
// <-metricProcessed
@ -27,7 +29,8 @@ func TestShimSetsUpLogger(t *testing.T) {
require.NoError(t, err)
require.Contains(t, out, "Error in plugin: intentional")
stdinWriter.Close()
err = stdinWriter.Close()
require.NoError(t, err)
}
func runErroringInputPlugin(t *testing.T, interval time.Duration, stdin io.Reader, stdout, stderr io.Writer) (metricProcessed chan bool, exited chan bool) {
@ -46,7 +49,8 @@ func runErroringInputPlugin(t *testing.T, interval time.Duration, stdin io.Reade
shim.stderr = stderr
log.SetOutput(stderr)
}
shim.AddInput(inp)
err := shim.AddInput(inp)
require.NoError(t, err)
go func() {
err := shim.Run(interval)
require.NoError(t, err)

View File

@ -34,7 +34,8 @@ func TestInputShimStdinSignalingWorks(t *testing.T) {
metricProcessed, exited := runInputPlugin(t, 40*time.Second, stdinReader, stdoutWriter, nil)
stdinWriter.Write([]byte("\n"))
_, err := stdinWriter.Write([]byte("\n"))
require.NoError(t, err)
<-metricProcessed
@ -43,7 +44,8 @@ func TestInputShimStdinSignalingWorks(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "measurement,tag=tag field=1i 1234000005678\n", out)
stdinWriter.Close()
err = stdinWriter.Close()
require.NoError(t, err)
go func() {
_, _ = io.ReadAll(r)
}()
@ -68,7 +70,8 @@ func runInputPlugin(t *testing.T, interval time.Duration, stdin io.Reader, stdou
if stderr != nil {
shim.stderr = stderr
}
shim.AddInput(inp)
err := shim.AddInput(inp)
require.NoError(t, err)
go func() {
err := shim.Run(interval)
require.NoError(t, err)

View File

@ -66,7 +66,7 @@ func (l *Logger) Info(args ...interface{}) {
// setLoggerOnPlugin injects the logger into the plugin,
// if it defines Log telegraf.Logger. This is sort of like SetLogger but using
// reflection instead of forcing the plugin author to define the function for it
func setLoggerOnPlugin(i interface{}, log telegraf.Logger) {
func setLoggerOnPlugin(i interface{}, logger telegraf.Logger) {
valI := reflect.ValueOf(i)
if valI.Type().Kind() != reflect.Ptr {
@ -78,10 +78,9 @@ func setLoggerOnPlugin(i interface{}, log telegraf.Logger) {
return
}
switch field.Type().String() {
case "telegraf.Logger":
if field.Type().String() == "telegraf.Logger" {
if field.CanSet() {
field.Set(reflect.ValueOf(log))
field.Set(reflect.ValueOf(logger))
}
}
}

View File

@ -8,11 +8,12 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/plugins/serializers"
"github.com/stretchr/testify/require"
)
func TestProcessorShim(t *testing.T) {
@ -95,8 +96,8 @@ type testProcessor struct {
}
func (p *testProcessor) Apply(in ...telegraf.Metric) []telegraf.Metric {
for _, metric := range in {
metric.AddTag(p.tagName, p.tagValue)
for _, m := range in {
m.AddTag(p.tagName, p.tagValue)
}
return in
}

View File

@ -5,8 +5,9 @@ import (
"sort"
"time"
"github.com/influxdata/telegraf/metric"
"go.starlark.net/starlark"
"github.com/influxdata/telegraf/metric"
)
func newMetric(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
@ -210,11 +211,11 @@ func dictUpdate(b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tupl
return nil, fmt.Errorf("dictionary update sequence element #%d is not iterable (%s)", i, pair.Type())
}
defer iter2.Done()
len := starlark.Len(pair)
if len < 0 {
length := starlark.Len(pair)
if length < 0 {
return nil, fmt.Errorf("dictionary update sequence element #%d has unknown length (%s)", i, pair.Type())
} else if len != 2 {
return nil, fmt.Errorf("dictionary update sequence element #%d has length %d, want 2", i, len)
} else if length != 2 {
return nil, fmt.Errorf("dictionary update sequence element #%d has length %d, want 2", i, length)
}
var k, v starlark.Value
iter2.Next(&k)

View File

@ -6,8 +6,9 @@ import (
"reflect"
"strings"
"github.com/influxdata/telegraf"
"go.starlark.net/starlark"
"github.com/influxdata/telegraf"
)
// FieldDict is a starlark.Value for the metric fields. It is heavily based on the
@ -18,17 +19,17 @@ type FieldDict struct {
func (d FieldDict) String() string {
buf := new(strings.Builder)
buf.WriteString("{")
buf.WriteString("{") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
sep := ""
for _, item := range d.Items() {
k, v := item[0], item[1]
buf.WriteString(sep)
buf.WriteString(k.String())
buf.WriteString(": ")
buf.WriteString(v.String())
buf.WriteString(sep) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(k.String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(": ") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(v.String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
sep = ", "
}
buf.WriteString("}")
buf.WriteString("}") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
return buf.String()
}
@ -181,7 +182,7 @@ func (d FieldDict) Delete(k starlark.Value) (v starlark.Value, found bool, err e
return starlark.None, false, errors.New("key must be of type 'str'")
}
// Items implements the starlark.Mapping interface.
// Iterate implements the starlark.Iterator interface.
func (d FieldDict) Iterate() starlark.Iterator {
d.fieldIterCount++
return &FieldIterator{Metric: d.Metric, fields: d.metric.FieldList()}

View File

@ -6,8 +6,9 @@ import (
"strings"
"time"
"github.com/influxdata/telegraf"
"go.starlark.net/starlark"
"github.com/influxdata/telegraf"
)
type Metric struct {
@ -36,15 +37,15 @@ func (m *Metric) Unwrap() telegraf.Metric {
// it behaves more like the repr function would in Python.
func (m *Metric) String() string {
buf := new(strings.Builder)
buf.WriteString("Metric(")
buf.WriteString(m.Name().String())
buf.WriteString(", tags=")
buf.WriteString(m.Tags().String())
buf.WriteString(", fields=")
buf.WriteString(m.Fields().String())
buf.WriteString(", time=")
buf.WriteString(m.Time().String())
buf.WriteString(")")
buf.WriteString("Metric(") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(m.Name().String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(", tags=") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(m.Tags().String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(", fields=") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(m.Fields().String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(", time=") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(m.Time().String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(")") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
return buf.String()
}

View File

@ -5,8 +5,9 @@ import (
"fmt"
"strings"
"github.com/influxdata/telegraf"
"go.starlark.net/starlark"
"github.com/influxdata/telegraf"
)
// TagDict is a starlark.Value for the metric tags. It is heavily based on the
@ -17,17 +18,17 @@ type TagDict struct {
func (d TagDict) String() string {
buf := new(strings.Builder)
buf.WriteString("{")
buf.WriteString("{") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
sep := ""
for _, item := range d.Items() {
k, v := item[0], item[1]
buf.WriteString(sep)
buf.WriteString(k.String())
buf.WriteString(": ")
buf.WriteString(v.String())
buf.WriteString(sep) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(k.String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(": ") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
buf.WriteString(v.String()) //nolint:revive // from builder.go: "It returns the length of r and a nil error."
sep = ", "
}
buf.WriteString("}")
buf.WriteString("}") //nolint:revive // from builder.go: "It returns the length of r and a nil error."
return buf.String()
}
@ -168,7 +169,7 @@ func (d TagDict) Delete(k starlark.Value) (v starlark.Value, found bool, err err
return starlark.None, false, errors.New("key must be of type 'str'")
}
// Items implements the starlark.Mapping interface.
// Iterate implements the starlark.Iterator interface.
func (d TagDict) Iterate() starlark.Iterator {
d.tagIterCount++
return &TagIterator{Metric: d.Metric, tags: d.metric.TagList()}

View File

@ -6,9 +6,10 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
var pki = testutil.NewPKI("../../../testutil/pki")
@ -344,6 +345,8 @@ func TestConnect(t *testing.T) {
resp, err := client.Get(ts.URL)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, 200, resp.StatusCode)
}

View File

@ -10,11 +10,11 @@ func ParseCiphers(ciphers []string) ([]uint16, error) {
suites := []uint16{}
for _, cipher := range ciphers {
if v, ok := tlsCipherMap[cipher]; ok {
suites = append(suites, v)
} else {
v, ok := tlsCipherMap[cipher]
if !ok {
return nil, fmt.Errorf("unsupported cipher %q", cipher)
}
suites = append(suites, v)
}
return suites, nil