Skip to content

Commit

Permalink
Revive fixes - part 1 (influxdata#8797)
Browse files Browse the repository at this point in the history
* Revive fixes regarding following set of rules:
[rule.blank-imports]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
[rule.error-return]
[rule.error-strings]
[rule.indent-error-flow]
[rule.errorf]
  • Loading branch information
zak-pawel authored Feb 8, 2021
1 parent 90392e1 commit ba66d4f
Show file tree
Hide file tree
Showing 88 changed files with 460 additions and 472 deletions.
4 changes: 2 additions & 2 deletions config/aws/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ type CredentialConfig struct {
func (c *CredentialConfig) Credentials() client.ConfigProvider {
if c.RoleARN != "" {
return c.assumeCredentials()
} else {
return c.rootCredentials()
}

return c.rootCredentials()
}

func (c *CredentialConfig) rootCredentials() client.ConfigProvider {
Expand Down
2 changes: 1 addition & 1 deletion internal/exec_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func WaitTimeout(c *exec.Cmd, timeout time.Duration) error {

// If SIGTERM was sent then treat any process error as a timeout.
if termSent {
return TimeoutErr
return ErrTimeout
}

// Otherwise there was an error unrelated to termination.
Expand Down
2 changes: 1 addition & 1 deletion internal/exec_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func WaitTimeout(c *exec.Cmd, timeout time.Duration) error {

// If SIGTERM was sent then treat any process error as a timeout.
if termSent {
return TimeoutErr
return ErrTimeout
}

// Otherwise there was an error unrelated to termination.
Expand Down
10 changes: 4 additions & 6 deletions internal/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ import (
const alphanum string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

var (
TimeoutErr = errors.New("Command timed out.")

NotImplementedError = errors.New("not implemented yet")

VersionAlreadySetError = errors.New("version has already been set")
ErrTimeout = errors.New("command timed out")
ErrorNotImplemented = errors.New("not implemented yet")
ErrorVersionAlreadySet = errors.New("version has already been set")
)

// Set via the main module
Expand Down Expand Up @@ -58,7 +56,7 @@ type ReadWaitCloser struct {
// SetVersion sets the telegraf agent version
func SetVersion(v string) error {
if version != "" {
return VersionAlreadySetError
return ErrorVersionAlreadySet
}
version = v
return nil
Expand Down
6 changes: 3 additions & 3 deletions internal/internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func TestRunTimeout(t *testing.T) {
err := RunTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start)

assert.Equal(t, TimeoutErr, err)
assert.Equal(t, ErrTimeout, err)
// Verify that command gets killed in 20ms, with some breathing room
assert.True(t, elapsed < time.Millisecond*75)
}
Expand Down Expand Up @@ -102,7 +102,7 @@ func TestCombinedOutputTimeout(t *testing.T) {
_, err := CombinedOutputTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start)

assert.Equal(t, TimeoutErr, err)
assert.Equal(t, ErrTimeout, err)
// Verify that command gets killed in 20ms, with some breathing room
assert.True(t, elapsed < time.Millisecond*75)
}
Expand Down Expand Up @@ -273,7 +273,7 @@ func TestVersionAlreadySet(t *testing.T) {
err = SetVersion("bar")

assert.Error(t, err)
assert.IsType(t, VersionAlreadySetError, err)
assert.IsType(t, ErrorVersionAlreadySet, err)

assert.Equal(t, "foo", Version())
}
Expand Down
3 changes: 1 addition & 2 deletions models/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,8 @@ func (b *Buffer) Reject(batch []telegraf.Metric) {
func (b *Buffer) dist(begin, end int) int {
if begin <= end {
return end - begin
} else {
return b.cap - begin + end
}
return b.cap - begin + end
}

// next returns the next index with wrapping.
Expand Down
4 changes: 2 additions & 2 deletions models/running_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ func (m *mockOutput) Write(metrics []telegraf.Metric) error {
m.Lock()
defer m.Unlock()
if m.failWrite {
return fmt.Errorf("Failed Write!")
return fmt.Errorf("failed write")
}

if m.metrics == nil {
Expand Down Expand Up @@ -583,7 +583,7 @@ func (m *perfOutput) SampleConfig() string {

func (m *perfOutput) Write(metrics []telegraf.Metric) error {
if m.failWrite {
return fmt.Errorf("Failed Write!")
return fmt.Errorf("failed write")
}
return nil
}
1 change: 1 addition & 0 deletions plugins/aggregators/all/all.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package all

import (
//Blank imports for plugins to register themselves
_ "github.com/influxdata/telegraf/plugins/aggregators/basicstats"
_ "github.com/influxdata/telegraf/plugins/aggregators/final"
_ "github.com/influxdata/telegraf/plugins/aggregators/histogram"
Expand Down
1 change: 1 addition & 0 deletions plugins/inputs/all/all.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package all

import (
//Blank imports for plugins to register themselves
_ "github.com/influxdata/telegraf/plugins/inputs/activemq"
_ "github.com/influxdata/telegraf/plugins/inputs/aerospike"
_ "github.com/influxdata/telegraf/plugins/inputs/amqp_consumer"
Expand Down
6 changes: 3 additions & 3 deletions plugins/inputs/apache/apache.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (n *Apache) Gather(acc telegraf.Accumulator) error {
for _, u := range n.Urls {
addr, err := url.Parse(u)
if err != nil {
acc.AddError(fmt.Errorf("Unable to parse address '%s': %s", u, err))
acc.AddError(fmt.Errorf("unable to parse address '%s': %s", u, err))
continue
}

Expand Down Expand Up @@ -111,7 +111,7 @@ func (n *Apache) createHttpClient() (*http.Client, error) {
func (n *Apache) gatherUrl(addr *url.URL, acc telegraf.Accumulator) error {
req, err := http.NewRequest("GET", addr.String(), nil)
if err != nil {
return fmt.Errorf("error on new request to %s : %s\n", addr.String(), err)
return fmt.Errorf("error on new request to %s : %s", addr.String(), err)
}

if len(n.Username) != 0 && len(n.Password) != 0 {
Expand All @@ -120,7 +120,7 @@ func (n *Apache) gatherUrl(addr *url.URL, acc telegraf.Accumulator) error {

resp, err := n.client.Do(req)
if err != nil {
return fmt.Errorf("error on request to %s : %s\n", addr.String(), err)
return fmt.Errorf("error on request to %s : %s", addr.String(), err)
}
defer resp.Body.Close()

Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/bind/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (b *Bind) Gather(acc telegraf.Accumulator) error {
for _, u := range b.Urls {
addr, err := url.Parse(u)
if err != nil {
acc.AddError(fmt.Errorf("Unable to parse address '%s': %s", u, err))
acc.AddError(fmt.Errorf("unable to parse address '%s': %s", u, err))
continue
}

Expand Down Expand Up @@ -88,7 +88,7 @@ func (b *Bind) gatherUrl(addr *url.URL, acc telegraf.Accumulator) error {
// BIND 9.9+
return b.readStatsXMLv3(addr, acc)
default:
return fmt.Errorf("URL %s is ambiguous. Please check plugin documentation for supported URL formats.",
return fmt.Errorf("provided URL %s is ambiguous, please check plugin documentation for supported URL formats",
addr)
}
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/bind/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,5 +623,5 @@ func TestBindUnparseableURL(t *testing.T) {

var acc testutil.Accumulator
err := acc.GatherError(b.Gather)
assert.Contains(t, err.Error(), "Unable to parse address")
assert.Contains(t, err.Error(), "unable to parse address")
}
32 changes: 14 additions & 18 deletions plugins/inputs/cassandra/cassandra.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
Expand All @@ -28,9 +27,10 @@ func (c JolokiaClientImpl) MakeRequest(req *http.Request) (*http.Response, error

type Cassandra struct {
jClient JolokiaClient
Context string
Servers []string
Metrics []string
Context string `toml:"context"`
Servers []string `toml:"servers"`
Metrics []string `toml:"metrics"`
Log telegraf.Logger `toml:"-"`
}

type javaMetric struct {
Expand Down Expand Up @@ -125,8 +125,7 @@ func (j javaMetric) addTagsFields(out map[string]interface{}) {
}
j.acc.AddFields(tokens["class"]+tokens["type"], fields, tags)
} else {
j.acc.AddError(fmt.Errorf("Missing key 'value' in '%s' output response\n%v\n",
j.metric, out))
j.acc.AddError(fmt.Errorf("missing key 'value' in '%s' output response: %v", j.metric, out))
}
}

Expand Down Expand Up @@ -157,17 +156,15 @@ func (c cassandraMetric) addTagsFields(out map[string]interface{}) {
addCassandraMetric(k, c, v.(map[string]interface{}))
}
} else {
c.acc.AddError(fmt.Errorf("Missing key 'value' in '%s' output response\n%v\n",
c.metric, out))
c.acc.AddError(fmt.Errorf("missing key 'value' in '%s' output response: %v", c.metric, out))
return
}
} else {
if values, ok := out["value"]; ok {
addCassandraMetric(r.(map[string]interface{})["mbean"].(string),
c, values.(map[string]interface{}))
} else {
c.acc.AddError(fmt.Errorf("Missing key 'value' in '%s' output response\n%v\n",
c.metric, out))
c.acc.AddError(fmt.Errorf("missing key 'value' in '%s' output response: %v", c.metric, out))
return
}
}
Expand Down Expand Up @@ -215,7 +212,7 @@ func (j *Cassandra) getAttr(requestUrl *url.URL) (map[string]interface{}, error)

// Process response
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("Response from url \"%s\" has status code %d (%s), expected %d (%s)",
err = fmt.Errorf("response from url \"%s\" has status code %d (%s), expected %d (%s)",
requestUrl,
resp.StatusCode,
http.StatusText(resp.StatusCode),
Expand All @@ -232,8 +229,8 @@ func (j *Cassandra) getAttr(requestUrl *url.URL) (map[string]interface{}, error)

// Unmarshal json
var jsonOut map[string]interface{}
if err = json.Unmarshal([]byte(body), &jsonOut); err != nil {
return nil, errors.New("Error decoding JSON response")
if err = json.Unmarshal(body, &jsonOut); err != nil {
return nil, errors.New("error decoding JSON response")
}

return jsonOut, nil
Expand Down Expand Up @@ -263,8 +260,8 @@ func parseServerTokens(server string) map[string]string {
return serverTokens
}

func (c *Cassandra) Start(acc telegraf.Accumulator) error {
log.Println("W! DEPRECATED: The cassandra plugin has been deprecated. " +
func (c *Cassandra) Start(_ telegraf.Accumulator) error {
c.Log.Warn("DEPRECATED: The cassandra plugin has been deprecated. " +
"Please use the jolokia2 plugin instead. " +
"https://github.com/influxdata/telegraf/tree/master/plugins/inputs/jolokia2")
return nil
Expand All @@ -290,8 +287,7 @@ func (c *Cassandra) Gather(acc telegraf.Accumulator) error {
m = newCassandraMetric(serverTokens["host"], metric, acc)
} else {
// unsupported metric type
acc.AddError(fmt.Errorf("E! Unsupported Cassandra metric [%s], skipping",
metric))
acc.AddError(fmt.Errorf("unsupported Cassandra metric [%s], skipping", metric))
continue
}

Expand All @@ -313,7 +309,7 @@ func (c *Cassandra) Gather(acc telegraf.Accumulator) error {
continue
}
if out["status"] != 200.0 {
acc.AddError(fmt.Errorf("URL returned with status %v - %s\n", out["status"], requestUrl))
acc.AddError(fmt.Errorf("provided URL returned with status %v - %s", out["status"], requestUrl))
continue
}
m.addTagsFields(out)
Expand Down
6 changes: 3 additions & 3 deletions plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (
internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials" // Register GRPC gzip decoder to support compressed telemetry
_ "google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/credentials"
_ "google.golang.org/grpc/encoding/gzip" // Register GRPC gzip decoder to support compressed telemetry
"google.golang.org/grpc/peer"
)

Expand Down Expand Up @@ -261,7 +261,7 @@ func (c *CiscoTelemetryMDT) handleTelemetry(data []byte) {
msg := &telemetry.Telemetry{}
err := proto.Unmarshal(data, msg)
if err != nil {
c.acc.AddError(fmt.Errorf("Cisco MDT failed to decode: %v", err))
c.acc.AddError(fmt.Errorf("failed to decode: %v", err))
return
}

Expand Down
3 changes: 1 addition & 2 deletions plugins/inputs/docker_log/docker_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,9 +308,8 @@ func (d *DockerLogs) tailContainerLogs(
// multiplexed.
if hasTTY {
return tailStream(acc, tags, container.ID, logReader, "tty")
} else {
return tailMultiplexed(acc, tags, container.ID, logReader)
}
return tailMultiplexed(acc, tags, container.ID, logReader)
}

func parseLine(line []byte) (time.Time, string, error) {
Expand Down
3 changes: 1 addition & 2 deletions plugins/inputs/dovecot/dovecot.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ const defaultPort = "24242"
// Reads stats from all configured servers.
func (d *Dovecot) Gather(acc telegraf.Accumulator) error {
if !validQuery[d.Type] {
return fmt.Errorf("Error: %s is not a valid query type\n",
d.Type)
return fmt.Errorf("error: %s is not a valid query type", d.Type)
}

if len(d.Servers) == 0 {
Expand Down
7 changes: 3 additions & 4 deletions plugins/inputs/haproxy/haproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,13 @@ func (g *haproxy) gatherServerSocket(addr string, acc telegraf.Accumulator) erro
c, err := net.Dial("unix", socketPath)

if err != nil {
return fmt.Errorf("Could not connect to socket '%s': %s", addr, err)
return fmt.Errorf("could not connect to socket '%s': %s", addr, err)
}

_, errw := c.Write([]byte("show stat\n"))

if errw != nil {
return fmt.Errorf("Could not write to socket '%s': %s", addr, errw)
return fmt.Errorf("could not write to socket '%s': %s", addr, errw)
}

return g.importCsvResult(c, acc, socketPath)
Expand Down Expand Up @@ -202,9 +202,8 @@ func getSocketAddr(sock string) string {

if len(socketAddr) >= 2 {
return socketAddr[1]
} else {
return socketAddr[0]
}
return socketAddr[0]
}

var typeNames = []string{"frontend", "backend", "server", "listener"}
Expand Down
7 changes: 3 additions & 4 deletions plugins/inputs/intel_rdt/intel_rdt.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,17 +239,16 @@ func (r *IntelRDT) createArgsAndStartPQOS(ctx context.Context) {
if len(r.parsedCores) != 0 {
coresArg := createArgCores(r.parsedCores)
args = append(args, coresArg)
go r.readData(args, nil, ctx)

go r.readData(ctx, args, nil)
} else if len(r.processesPIDsMap) != 0 {
processArg := createArgProcess(r.processesPIDsMap)
args = append(args, processArg)
go r.readData(args, r.processesPIDsMap, ctx)
go r.readData(ctx, args, r.processesPIDsMap)
}
return
}

func (r *IntelRDT) readData(args []string, processesPIDsAssociation map[string]string, ctx context.Context) {
func (r *IntelRDT) readData(ctx context.Context, args []string, processesPIDsAssociation map[string]string) {
r.wg.Add(1)
defer r.wg.Done()

Expand Down
Loading

0 comments on commit ba66d4f

Please sign in to comment.