Skip to content

Commit

Permalink
chore: Fix linter findings for errorlint (part3) (#12704)
Browse files Browse the repository at this point in the history
Co-authored-by: Pawel Zak <Pawel Zak>
(cherry picked from commit 39d6b1d)
  • Loading branch information
zak-pawel authored and powersj committed Feb 27, 2023
1 parent afe0dd3 commit 2920c16
Show file tree
Hide file tree
Showing 49 changed files with 164 additions and 148 deletions.
8 changes: 4 additions & 4 deletions plugins/outputs/amon/amon.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,17 @@ func (a *Amon) Write(metrics []telegraf.Metric) error {
copy(ts.Series, tempSeries[0:])
tsBytes, err := json.Marshal(ts)
if err != nil {
return fmt.Errorf("unable to marshal TimeSeries, %s", err.Error())
return fmt.Errorf("unable to marshal TimeSeries: %w", err)
}
req, err := http.NewRequest("POST", a.authenticatedURL(), bytes.NewBuffer(tsBytes))
if err != nil {
return fmt.Errorf("unable to create http.Request, %s", err.Error())
return fmt.Errorf("unable to create http.Request: %w", err)
}
req.Header.Add("Content-Type", "application/json")

resp, err := a.client.Do(req)
if err != nil {
return fmt.Errorf("error POSTing metrics, %s", err.Error())
return fmt.Errorf("error POSTing metrics: %w", err)
}
defer resp.Body.Close()

Expand All @@ -113,7 +113,7 @@ func buildMetrics(m telegraf.Metric) (map[string]Point, error) {
for k, v := range m.Fields() {
var p Point
if err := p.setValue(v); err != nil {
return ms, fmt.Errorf("unable to extract value from Fields, %s", err.Error())
return ms, fmt.Errorf("unable to extract value from Fields: %w", err)
}
p[0] = float64(m.Time().Unix())
ms[k] = p
Expand Down
4 changes: 3 additions & 1 deletion plugins/outputs/amqp/amqp.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package amqp
import (
"bytes"
_ "embed"
"errors"
"strings"
"time"

Expand Down Expand Up @@ -160,7 +161,8 @@ func (q *AMQP) Write(metrics []telegraf.Metric) error {
// If this is the first attempt to publish and the connection is
// closed, try to reconnect and retry once.

if aerr, ok := err.(*amqp.Error); first && ok && aerr == amqp.ErrClosed {
var aerr *amqp.Error
if first && errors.As(err, &aerr) && errors.Is(aerr, amqp.ErrClosed) {
q.client = nil
err := q.publish(key, body)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions plugins/outputs/amqp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func newClient(config *ClientConfig) (*client, error) {

channel, err := client.conn.Channel()
if err != nil {
return nil, fmt.Errorf("error opening channel: %v", err)
return nil, fmt.Errorf("error opening channel: %w", err)
}
client.channel = channel

Expand Down Expand Up @@ -110,7 +110,7 @@ func (c *client) DeclareExchange() error {
)
}
if err != nil {
return fmt.Errorf("error declaring exchange: %v", err)
return fmt.Errorf("error declaring exchange: %w", err)
}
return nil
}
Expand Down Expand Up @@ -139,7 +139,7 @@ func (c *client) Close() error {
}

err := c.conn.Close()
if err != nil && err != amqp.ErrClosed {
if err != nil && !errors.Is(err, amqp.ErrClosed) {
return err
}
return nil
Expand Down
12 changes: 6 additions & 6 deletions plugins/outputs/azure_data_explorer/azure_data_explorer.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,12 @@ func (adx *AzureDataExplorer) getMetricIngestor(ctx context.Context, tableName s

if ingestor == nil {
if err := adx.createAzureDataExplorerTable(ctx, tableName); err != nil {
return nil, fmt.Errorf("creating table for %q failed: %v", tableName, err)
return nil, fmt.Errorf("creating table for %q failed: %w", tableName, err)
}
//create a new ingestor client for the table
tempIngestor, err := createIngestorByTable(adx.kustoClient, adx.Database, tableName, adx.IngestionType)
if err != nil {
return nil, fmt.Errorf("creating ingestor for %q failed: %v", tableName, err)
return nil, fmt.Errorf("creating ingestor for %q failed: %w", tableName, err)
}
adx.metricIngestors[tableName] = tempIngestor
adx.Log.Debugf("Ingestor for table %s created", tableName)
Expand Down Expand Up @@ -225,21 +225,21 @@ func (adx *AzureDataExplorer) createAzureDataExplorerTable(ctx context.Context,

func (adx *AzureDataExplorer) Init() error {
if adx.Endpoint == "" {
return errors.New("Endpoint configuration cannot be empty")
return errors.New("endpoint configuration cannot be empty")
}
if adx.Database == "" {
return errors.New("Database configuration cannot be empty")
return errors.New("database configuration cannot be empty")
}

adx.MetricsGrouping = strings.ToLower(adx.MetricsGrouping)
if adx.MetricsGrouping == singleTable && adx.TableName == "" {
return errors.New("Table name cannot be empty for SingleTable metrics grouping type")
return errors.New("table name cannot be empty for SingleTable metrics grouping type")
}
if adx.MetricsGrouping == "" {
adx.MetricsGrouping = tablePerMetric
}
if !(adx.MetricsGrouping == singleTable || adx.MetricsGrouping == tablePerMetric) {
return errors.New("Metrics grouping type is not valid")
return errors.New("metrics grouping type is not valid")
}

if adx.IngestionType == "" {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ func TestInitBlankEndpointData(t *testing.T) {

errorInit := plugin.Init()
require.Error(t, errorInit)
require.Equal(t, "Endpoint configuration cannot be empty", errorInit.Error())
require.Equal(t, "endpoint configuration cannot be empty", errorInit.Error())
}

type fakeIngestor struct {
Expand Down
8 changes: 4 additions & 4 deletions plugins/outputs/azure_monitor/azure_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import (
_ "embed"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
Expand Down Expand Up @@ -187,7 +187,7 @@ func (a *AzureMonitor) initHTTPClient() {
func vmInstanceMetadata(c *http.Client) (region string, resourceID string, err error) {
req, err := http.NewRequest("GET", vmInstanceMetadataURL, nil)
if err != nil {
return "", "", fmt.Errorf("error creating request: %v", err)
return "", "", fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Metadata", "true")

Expand Down Expand Up @@ -323,12 +323,12 @@ func (a *AzureMonitor) send(body []byte) error {
// refresh the token if needed.
req, err = autorest.CreatePreparer(a.auth.WithAuthorization()).Prepare(req)
if err != nil {
return fmt.Errorf("unable to fetch authentication credentials: %v", err)
return fmt.Errorf("unable to fetch authentication credentials: %w", err)
}

resp, err := a.client.Do(req)
if err != nil {
if err.(*url.Error).Unwrap() == context.DeadlineExceeded {
if errors.Is(err, context.DeadlineExceeded) {
a.initHTTPClient()
}

Expand Down
2 changes: 1 addition & 1 deletion plugins/outputs/cloud_pubsub/cloud_pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (ps *PubSub) initPubSubClient() error {
option.WithUserAgent(internal.ProductToken()),
)
if err != nil {
return fmt.Errorf("unable to generate PubSub client: %v", err)
return fmt.Errorf("unable to generate PubSub client: %w", err)
}
ps.c = client
return nil
Expand Down
4 changes: 2 additions & 2 deletions plugins/outputs/datadog/datadog.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func (d *Datadog) Write(metrics []telegraf.Metric) error {
copy(ts.Series, tempSeries[0:])
tsBytes, err := json.Marshal(ts)
if err != nil {
return fmt.Errorf("unable to marshal TimeSeries, %s", err.Error())
return fmt.Errorf("unable to marshal TimeSeries: %w", err)
}

var req *http.Request
Expand Down Expand Up @@ -192,7 +192,7 @@ func buildMetrics(m telegraf.Metric) (map[string]Point, error) {
}
var p Point
if err := p.setValue(field.Value); err != nil {
return ms, fmt.Errorf("unable to extract value from Fields %v error %v", field.Key, err.Error())
return ms, fmt.Errorf("unable to extract value from Field %v: %w", field.Key, err)
}
p[0] = float64(m.Time().Unix())
ms[field.Key] = p
Expand Down
8 changes: 4 additions & 4 deletions plugins/outputs/dynatrace/dynatrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func (d *Dynatrace) Write(metrics []telegraf.Metric) error {
output := strings.Join(batch, "\n")
if output != "" {
if err := d.send(output); err != nil {
return fmt.Errorf("error processing data:, %s", err.Error())
return fmt.Errorf("error processing data: %w", err)
}
}
}
Expand All @@ -147,7 +147,7 @@ func (d *Dynatrace) send(msg string) error {
req, err := http.NewRequest("POST", d.URL, bytes.NewBufferString(msg))
if err != nil {
d.Log.Errorf("Dynatrace error: %s", err.Error())
return fmt.Errorf("error while creating HTTP request:, %s", err.Error())
return fmt.Errorf("error while creating HTTP request: %w", err)
}
req.Header.Add("Content-Type", "text/plain; charset=UTF-8")

Expand All @@ -160,12 +160,12 @@ func (d *Dynatrace) send(msg string) error {
resp, err := d.client.Do(req)
if err != nil {
d.Log.Errorf("Dynatrace error: %s", err.Error())
return fmt.Errorf("error while sending HTTP request:, %s", err.Error())
return fmt.Errorf("error while sending HTTP request: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusBadRequest {
return fmt.Errorf("request failed with response code:, %d", resp.StatusCode)
return fmt.Errorf("request failed with response code: %d", resp.StatusCode)
}

// print metric line results as info log
Expand Down
10 changes: 5 additions & 5 deletions plugins/outputs/elasticsearch/elasticsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (a *Elasticsearch) Connect() error {

elasticURL, err := url.Parse(a.URLs[0])
if err != nil {
return fmt.Errorf("parsing URL failed: %v", err)
return fmt.Errorf("parsing URL failed: %w", err)
}

clientOptions = append(clientOptions,
Expand Down Expand Up @@ -213,7 +213,7 @@ func (a *Elasticsearch) Connect() error {
esVersion, err := client.ElasticsearchVersion(a.URLs[0])

if err != nil {
return fmt.Errorf("elasticsearch version check failed: %s", err)
return fmt.Errorf("elasticsearch version check failed: %w", err)
}

// quit if ES version is not supported
Expand Down Expand Up @@ -318,7 +318,7 @@ func (a *Elasticsearch) Write(metrics []telegraf.Metric) error {
res, err := bulkRequest.Do(ctx)

if err != nil {
return fmt.Errorf("error sending bulk request to Elasticsearch: %s", err)
return fmt.Errorf("error sending bulk request to Elasticsearch: %w", err)
}

if res.Errors {
Expand Down Expand Up @@ -346,7 +346,7 @@ func (a *Elasticsearch) manageTemplate(ctx context.Context) error {
templateExists, errExists := a.Client.IndexTemplateExists(a.TemplateName).Do(ctx)

if errExists != nil {
return fmt.Errorf("elasticsearch template check failed, template name: %s, error: %s", a.TemplateName, errExists)
return fmt.Errorf("elasticsearch template check failed, template name: %s, error: %w", a.TemplateName, errExists)
}

templatePattern := a.IndexName
Expand Down Expand Up @@ -378,7 +378,7 @@ func (a *Elasticsearch) manageTemplate(ctx context.Context) error {
_, errCreateTemplate := a.Client.IndexPutTemplate(a.TemplateName).BodyString(tmpl.String()).Do(ctx)

if errCreateTemplate != nil {
return fmt.Errorf("elasticsearch failed to create index template %s : %s", a.TemplateName, errCreateTemplate)
return fmt.Errorf("elasticsearch failed to create index template %s: %w", a.TemplateName, errCreateTemplate)
}

a.Log.Debugf("Template %s created or updated\n", a.TemplateName)
Expand Down
9 changes: 5 additions & 4 deletions plugins/outputs/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package exec
import (
"bytes"
_ "embed"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -100,7 +101,7 @@ func (c *CommandRunner) Run(timeout time.Duration, command []string, environment
s := stderr

if err != nil {
if err == internal.ErrTimeout {
if errors.Is(err, internal.ErrTimeout) {
return fmt.Errorf("%q timed out and was killed", command)
}

Expand All @@ -114,10 +115,10 @@ func (c *CommandRunner) Run(timeout time.Duration, command []string, environment
}

if status, ok := internal.ExitStatus(err); ok {
return fmt.Errorf("%q exited %d with %s", command, status, err.Error())
return fmt.Errorf("%q exited %d with %w", command, status, err)
}

return fmt.Errorf("%q failed with %s", command, err.Error())
return fmt.Errorf("%q failed with %w", command, err)
}

c.cmd = cmd
Expand Down Expand Up @@ -164,7 +165,7 @@ func removeWindowsCarriageReturns(b bytes.Buffer) bytes.Buffer {
if len(byt) > 0 {
_, _ = buf.Write(byt)
}
if err == io.EOF {
if errors.Is(err, io.EOF) {
return buf
}
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/outputs/execd/execd.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,12 @@ func (e *Execd) Write(metrics []telegraf.Metric) error {
if !e.IgnoreSerializationError {
return fmt.Errorf("error serializing metrics: %w", err)
}
e.Log.Error("Skipping metric due to a serialization error: %w", err)
e.Log.Errorf("Skipping metric due to a serialization error: %v", err)
continue
}

if _, err = e.process.Stdin.Write(b); err != nil {
return fmt.Errorf("error writing metrics %s", err)
return fmt.Errorf("error writing metrics: %w", err)
}
}
return nil
Expand Down
6 changes: 4 additions & 2 deletions plugins/outputs/execd/execd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package execd

import (
"bufio"
"errors"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -162,10 +163,11 @@ func runOutputConsumerProgram() {
for {
m, err := parser.Next()
if err != nil {
if err == influx.EOF {
if errors.Is(err, influx.EOF) {
return // stream ended
}
if parseErr, isParseError := err.(*influx.ParseError); isParseError {
var parseErr *influx.ParseError
if errors.As(err, &parseErr) {
fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr)
//nolint:revive // error code is important for this "test"
os.Exit(1)
Expand Down
2 changes: 1 addition & 1 deletion plugins/outputs/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (f *File) Write(metrics []telegraf.Metric) error {

_, err = f.writer.Write(b)
if err != nil {
writeErr = fmt.Errorf("failed to write message: %v", err)
writeErr = fmt.Errorf("failed to write message: %w", err)
}
}
}
Expand Down
7 changes: 4 additions & 3 deletions plugins/outputs/graphite/graphite.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func (g *Graphite) checkEOF(conn net.Conn) error {
return err
}
num, err := conn.Read(b)
if err == io.EOF {
if errors.Is(err, io.EOF) {
g.Log.Debugf("Conn %s is closed. closing conn explicitly", conn.RemoteAddr().String())
err = conn.Close()
g.Log.Debugf("Failed to close the connection: %v", err)
Expand All @@ -149,7 +149,8 @@ func (g *Graphite) checkEOF(conn net.Conn) error {
g.Log.Infof("conn %s .conn.Read data? did not expect that. data: %s", conn, b[:num])
}
// Log non-timeout errors and close.
if e, ok := err.(net.Error); !(ok && e.Timeout()) {
var netErr net.Error
if !(errors.As(err, &netErr) && netErr.Timeout()) {
g.Log.Debugf("conn %s checkEOF .conn.Read returned err != EOF, which is unexpected. closing conn. error: %s", conn, err)
err = conn.Close()
g.Log.Debugf("Failed to close the connection: %v", err)
Expand Down Expand Up @@ -184,7 +185,7 @@ func (g *Graphite) Write(metrics []telegraf.Metric) error {
g.Log.Debugf("Reconnecting and retrying for the following servers: %s", strings.Join(g.failedServers, ","))
err = g.Connect()
if err != nil {
return fmt.Errorf("Failed to reconnect: %v", err)
return fmt.Errorf("failed to reconnect: %w", err)
}
err = g.send(batch)
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/outputs/graylog/graylog.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,9 +457,9 @@ func (g *Graylog) Write(metrics []telegraf.Metric) error {
}

for _, value := range values {
_, err := writer.Write([]byte(value))
_, err = writer.Write([]byte(value))
if err != nil {
return fmt.Errorf("error writing message: %q, %v", value, err)
return fmt.Errorf("error writing message: %q: %w", value, err)
}
}
}
Expand Down
Loading

0 comments on commit 2920c16

Please sign in to comment.