chore: Fix linter findings for errorlint (part6) (#12733)

Co-authored-by: Pawel Zak <Pawel Zak>
This commit is contained in:
Paweł Żak 2023-03-01 22:19:38 +01:00 committed by GitHub
parent 5b2346dfa0
commit b2b58bab9e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 168 additions and 160 deletions

View File

@ -94,8 +94,7 @@ func (n *NeptuneApex) parseXML(acc telegraf.Accumulator, data []byte) error {
r := xmlReply{} r := xmlReply{}
err := xml.Unmarshal(data, &r) err := xml.Unmarshal(data, &r)
if err != nil { if err != nil {
return fmt.Errorf("unable to unmarshal XML: %v\nXML DATA: %q", return fmt.Errorf("unable to unmarshal XML: %w\nXML DATA: %q", err, data)
err, data)
} }
mainFields := map[string]interface{}{ mainFields := map[string]interface{}{
@ -143,9 +142,7 @@ func (n *NeptuneApex) parseXML(acc telegraf.Accumulator, data []byte) error {
strings.TrimSpace(r.Probe[pos].Value), 64) strings.TrimSpace(r.Probe[pos].Value), 64)
if err != nil { if err != nil {
acc.AddError( acc.AddError(
fmt.Errorf( fmt.Errorf("cannot convert string value %q to float64: %w", r.Probe[pos].Value, err))
"cannot convert string value %q to float64: %v",
r.Probe[pos].Value, err))
continue // Skip the whole outlet. continue // Skip the whole outlet.
} }
fields["watt"] = value fields["watt"] = value
@ -157,9 +154,7 @@ func (n *NeptuneApex) parseXML(acc telegraf.Accumulator, data []byte) error {
strings.TrimSpace(r.Probe[pos].Value), 64) strings.TrimSpace(r.Probe[pos].Value), 64)
if err != nil { if err != nil {
acc.AddError( acc.AddError(
fmt.Errorf( fmt.Errorf("cannot convert string value %q to float64: %w", r.Probe[pos].Value, err))
"cannot convert string value %q to float64: %v",
r.Probe[pos].Value, err))
break // // Skip the whole outlet. break // // Skip the whole outlet.
} }
fields["amp"] = value fields["amp"] = value
@ -196,9 +191,7 @@ func (n *NeptuneApex) parseXML(acc telegraf.Accumulator, data []byte) error {
for _, p := range r.Probe { for _, p := range r.Probe {
value, err := strconv.ParseFloat(strings.TrimSpace(p.Value), 64) value, err := strconv.ParseFloat(strings.TrimSpace(p.Value), 64)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf( acc.AddError(fmt.Errorf("cannot convert string value %q to float64: %w", p.Value, err))
"cannot convert string value %q to float64: %v",
p.Value, err))
continue continue
} }
fields := map[string]interface{}{ fields := map[string]interface{}{
@ -246,7 +239,7 @@ func parseTime(val string, tz float64) (time.Time, error) {
ts := fmt.Sprintf("%s %s", val, tzs) ts := fmt.Sprintf("%s %s", val, tzs)
t, err := time.Parse(timeLayout, ts) t, err := time.Parse(timeLayout, ts)
if err != nil { if err != nil {
return time.Now(), fmt.Errorf("unable to parse %q (%v)", ts, err) return time.Now(), fmt.Errorf("unable to parse %q: %w", ts, err)
} }
return t, nil return t, nil
} }
@ -255,7 +248,7 @@ func (n *NeptuneApex) sendRequest(server string) ([]byte, error) {
url := fmt.Sprintf("%s/cgi-bin/status.xml", server) url := fmt.Sprintf("%s/cgi-bin/status.xml", server)
resp, err := n.httpClient.Get(url) resp, err := n.httpClient.Get(url)
if err != nil { if err != nil {
return nil, fmt.Errorf("http GET failed: %v", err) return nil, fmt.Errorf("http GET failed: %w", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
@ -266,7 +259,7 @@ func (n *NeptuneApex) sendRequest(server string) ([]byte, error) {
} }
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to read output from %q: %v", url, err) return nil, fmt.Errorf("unable to read output from %q: %w", url, err)
} }
return body, nil return body, nil
} }

View File

@ -32,18 +32,18 @@ func (*NetIOStats) SampleConfig() string {
func (n *NetIOStats) Gather(acc telegraf.Accumulator) error { func (n *NetIOStats) Gather(acc telegraf.Accumulator) error {
netio, err := n.ps.NetIO() netio, err := n.ps.NetIO()
if err != nil { if err != nil {
return fmt.Errorf("error getting net io info: %s", err) return fmt.Errorf("error getting net io info: %w", err)
} }
if n.filter == nil { if n.filter == nil {
if n.filter, err = filter.Compile(n.Interfaces); err != nil { if n.filter, err = filter.Compile(n.Interfaces); err != nil {
return fmt.Errorf("error compiling filter: %s", err) return fmt.Errorf("error compiling filter: %w", err)
} }
} }
interfaces, err := net.Interfaces() interfaces, err := net.Interfaces()
if err != nil { if err != nil {
return fmt.Errorf("error getting list of interfaces: %s", err) return fmt.Errorf("error getting list of interfaces: %w", err)
} }
interfacesByName := map[string]net.Interface{} interfacesByName := map[string]net.Interface{}
for _, iface := range interfaces { for _, iface := range interfaces {

View File

@ -58,7 +58,8 @@ func (n *NetResponse) TCPGather() (map[string]string, map[string]interface{}, er
responseTime := time.Since(start).Seconds() responseTime := time.Since(start).Seconds()
// Handle error // Handle error
if err != nil { if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() { var e net.Error
if errors.As(err, &e) && e.Timeout() {
setResult(Timeout, fields, tags, n.Expect) setResult(Timeout, fields, tags, n.Expect)
} else { } else {
setResult(ConnectionFailed, fields, tags, n.Expect) setResult(ConnectionFailed, fields, tags, n.Expect)

View File

@ -25,7 +25,7 @@ func (*NetStats) SampleConfig() string {
func (ns *NetStats) Gather(acc telegraf.Accumulator) error { func (ns *NetStats) Gather(acc telegraf.Accumulator) error {
netconns, err := ns.PS.NetConnections() netconns, err := ns.PS.NetConnections()
if err != nil { if err != nil {
return fmt.Errorf("error getting net connections info: %s", err) return fmt.Errorf("error getting net connections info: %w", err)
} }
counts := make(map[string]int) counts := make(map[string]int)
counts["UDP"] = 0 counts["UDP"] = 0

View File

@ -4,6 +4,7 @@ package nfsclient
import ( import (
"bufio" "bufio"
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"os" "os"
"regexp" "regexp"
@ -50,8 +51,9 @@ func convertToUint64(line []string) ([]uint64, error) {
for _, l := range line[1:] { for _, l := range line[1:] {
val, err := strconv.ParseUint(l, 10, 64) val, err := strconv.ParseUint(l, 10, 64)
if err != nil { if err != nil {
if numError, ok := err.(*strconv.NumError); ok { var numError *strconv.NumError
if numError.Err == strconv.ErrRange { if errors.As(err, &numError) {
if errors.Is(numError.Err, strconv.ErrRange) {
return nil, fmt.Errorf("errrange: line:[%v] raw:[%v] -> parsed:[%v]", line, l, val) return nil, fmt.Errorf("errrange: line:[%v] raw:[%v] -> parsed:[%v]", line, l, val)
} }
} }

View File

@ -51,7 +51,7 @@ func (n *Nginx) Gather(acc telegraf.Accumulator) error {
for _, u := range n.Urls { for _, u := range n.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 %q: %w", u, err)) acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue continue
} }
@ -89,7 +89,7 @@ func (n *Nginx) createHTTPClient() (*http.Client, error) {
func (n *Nginx) gatherURL(addr *url.URL, acc telegraf.Accumulator) error { func (n *Nginx) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String()) resp, err := n.client.Get(addr.String())
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", addr.String(), err) return fmt.Errorf("error making HTTP request to %q: %w", addr.String(), err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {

View File

@ -5,6 +5,7 @@ import (
"bufio" "bufio"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -52,7 +53,7 @@ func (n *NginxPlus) Gather(acc telegraf.Accumulator) error {
for _, u := range n.Urls { for _, u := range n.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 %q: %w", u, err)) acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue continue
} }
@ -91,7 +92,7 @@ func (n *NginxPlus) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String()) resp, err := n.client.Get(addr.String())
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", addr.String(), err) return fmt.Errorf("error making HTTP request to %q: %w", addr.String(), err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
@ -273,7 +274,7 @@ func gatherStatusURL(r *bufio.Reader, tags map[string]string, acc telegraf.Accum
dec := json.NewDecoder(r) dec := json.NewDecoder(r)
status := &Status{} status := &Status{}
if err := dec.Decode(status); err != nil { if err := dec.Decode(status); err != nil {
return fmt.Errorf("Error while decoding JSON response") return errors.New("error while decoding JSON response")
} }
status.Gather(tags, acc) status.Gather(tags, acc)
return nil return nil

View File

@ -47,7 +47,7 @@ func addError(acc telegraf.Accumulator, err error) {
// //
// The correct solution is to do a GET to /api to get the available paths // The correct solution is to do a GET to /api to get the available paths
// on the server rather than simply ignore. // on the server rather than simply ignore.
if err != errNotFound { if !errors.Is(err, errNotFound) {
acc.AddError(err) acc.AddError(err)
} }
} }
@ -57,7 +57,7 @@ func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
resp, err := n.client.Get(address) resp, err := n.client.Get(address)
if err != nil { if err != nil {
return nil, fmt.Errorf("error making HTTP request to %s: %s", address, err) return nil, fmt.Errorf("error making HTTP request to %q: %w", address, err)
} }
defer resp.Body.Close() defer resp.Body.Close()

View File

@ -5,6 +5,7 @@ import (
"bufio" "bufio"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -51,7 +52,7 @@ func (n *NginxSTS) Gather(acc telegraf.Accumulator) error {
for _, u := range n.Urls { for _, u := range n.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 %q: %w", u, err)) acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue continue
} }
@ -89,7 +90,7 @@ func (n *NginxSTS) createHTTPClient() (*http.Client, error) {
func (n *NginxSTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error { func (n *NginxSTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String()) resp, err := n.client.Get(addr.String())
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", addr.String(), err) return fmt.Errorf("error making HTTP request to %q: %w", addr.String(), err)
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -167,7 +168,7 @@ func gatherStatusURL(r *bufio.Reader, tags map[string]string, acc telegraf.Accum
dec := json.NewDecoder(r) dec := json.NewDecoder(r)
status := &NginxSTSResponse{} status := &NginxSTSResponse{}
if err := dec.Decode(status); err != nil { if err := dec.Decode(status); err != nil {
return fmt.Errorf("Error while decoding JSON response") return errors.New("error while decoding JSON response")
} }
acc.AddFields("nginx_sts_connections", map[string]interface{}{ acc.AddFields("nginx_sts_connections", map[string]interface{}{

View File

@ -5,6 +5,7 @@ import (
"bufio" "bufio"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -51,7 +52,7 @@ func (n *NginxVTS) Gather(acc telegraf.Accumulator) error {
for _, u := range n.Urls { for _, u := range n.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 %q: %w", u, err)) acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue continue
} }
@ -89,7 +90,7 @@ func (n *NginxVTS) createHTTPClient() (*http.Client, error) {
func (n *NginxVTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error { func (n *NginxVTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String()) resp, err := n.client.Get(addr.String())
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", addr.String(), err) return fmt.Errorf("error making HTTP request to %q: %w", addr.String(), err)
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -185,7 +186,7 @@ func gatherStatusURL(r *bufio.Reader, tags map[string]string, acc telegraf.Accum
dec := json.NewDecoder(r) dec := json.NewDecoder(r)
status := &NginxVTSResponse{} status := &NginxVTSResponse{}
if err := dec.Decode(status); err != nil { if err := dec.Decode(status); err != nil {
return fmt.Errorf("Error while decoding JSON response") return errors.New("error while decoding JSON response")
} }
acc.AddFields("nginx_vts_connections", map[string]interface{}{ acc.AddFields("nginx_vts_connections", map[string]interface{}{

View File

@ -49,7 +49,7 @@ func (n *Nomad) Init() error {
tlsCfg, err := n.ClientConfig.TLSConfig() tlsCfg, err := n.ClientConfig.TLSConfig()
if err != nil { if err != nil {
return fmt.Errorf("setting up TLS configuration failed: %v", err) return fmt.Errorf("setting up TLS configuration failed: %w", err)
} }
n.roundTripper = &http.Transport{ n.roundTripper = &http.Transport{
@ -85,7 +85,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
resp, err := n.roundTripper.RoundTrip(req) resp, err := n.roundTripper.RoundTrip(req)
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", url, err) return fmt.Errorf("error making HTTP request to %q: %w", url, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -95,7 +95,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
err = json.NewDecoder(resp.Body).Decode(v) err = json.NewDecoder(resp.Body).Decode(v)
if err != nil { if err != nil {
return fmt.Errorf("error parsing json response: %s", err) return fmt.Errorf("error parsing json response: %w", err)
} }
return nil return nil
@ -105,7 +105,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
func buildNomadMetrics(acc telegraf.Accumulator, summaryMetrics *MetricsSummary) error { func buildNomadMetrics(acc telegraf.Accumulator, summaryMetrics *MetricsSummary) error {
t, err := time.Parse(timeLayout, summaryMetrics.Timestamp) t, err := time.Parse(timeLayout, summaryMetrics.Timestamp)
if err != nil { if err != nil {
return fmt.Errorf("error parsing time: %s", err) return fmt.Errorf("error parsing time: %w", err)
} }
for _, counters := range summaryMetrics.Counters { for _, counters := range summaryMetrics.Counters {

View File

@ -65,7 +65,7 @@ func nsdRunner(cmdName string, timeout config.Duration, useSudo bool, server str
cmd.Stdout = &out cmd.Stdout = &out
err := internal.RunTimeout(cmd, time.Duration(timeout)) err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil { if err != nil {
return &out, fmt.Errorf("error running nsd-control: %s (%s %v)", err, cmdName, cmdArgs) return &out, fmt.Errorf("error running nsd-control: %w (%s %v)", err, cmdName, cmdArgs)
} }
return &out, nil return &out, nil
@ -79,7 +79,7 @@ func (*NSD) SampleConfig() string {
func (s *NSD) Gather(acc telegraf.Accumulator) error { func (s *NSD) Gather(acc telegraf.Accumulator) error {
out, err := s.run(s.Binary, s.Timeout, s.UseSudo, s.Server, s.ConfigFile) out, err := s.run(s.Binary, s.Timeout, s.UseSudo, s.Server, s.ConfigFile)
if err != nil { if err != nil {
return fmt.Errorf("error gathering metrics: %s", err) return fmt.Errorf("error gathering metrics: %w", err)
} }
// Process values // Process values

View File

@ -112,7 +112,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: %w", u.String(), err)
} }
defer r.Body.Close() defer r.Body.Close()
@ -122,20 +122,20 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error {
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return fmt.Errorf(`error reading body: %s`, err) return fmt.Errorf(`error reading body: %w`, 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: %w`, 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: %w`, err)
} }
data = &wrapper.Data data = &wrapper.Data
} }

View File

@ -4,10 +4,11 @@ package nsq_consumer
import ( import (
"context" "context"
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"sync" "sync"
nsq "github.com/nsqio/go-nsq" "github.com/nsqio/go-nsq"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
@ -117,14 +118,14 @@ func (n *NSQConsumer) Start(ac telegraf.Accumulator) error {
if len(n.Nsqlookupd) > 0 { if len(n.Nsqlookupd) > 0 {
err := n.consumer.ConnectToNSQLookupds(n.Nsqlookupd) err := n.consumer.ConnectToNSQLookupds(n.Nsqlookupd)
if err != nil && err != nsq.ErrAlreadyConnected { if err != nil && !errors.Is(err, nsq.ErrAlreadyConnected) {
return err return err
} }
} }
if len(n.Nsqd) > 0 { if len(n.Nsqd) > 0 {
err := n.consumer.ConnectToNSQDs(n.Nsqd) err := n.consumer.ConnectToNSQDs(n.Nsqd)
if err != nil && err != nsq.ErrAlreadyConnected { if err != nil && !errors.Is(err, nsq.ErrAlreadyConnected) {
return err return err
} }
} }

View File

@ -67,7 +67,7 @@ func (o *ReadClient) Connect() error {
NodesToRegister: o.NodeIDs, NodesToRegister: o.NodeIDs,
}) })
if err != nil { if err != nil {
return fmt.Errorf("registerNodes failed: %v", err) return fmt.Errorf("registerNodes failed: %w", err)
} }
for _, v := range regResp.RegisteredNodeIDs { for _, v := range regResp.RegisteredNodeIDs {
@ -83,7 +83,7 @@ func (o *ReadClient) Connect() error {
err = o.read() err = o.read()
if err != nil { if err != nil {
return fmt.Errorf("get Data Failed: %v", err) return fmt.Errorf("get data failed: %w", err)
} }
return nil return nil
@ -135,7 +135,7 @@ func (o *ReadClient) read() error {
resp, err := o.Client.Read(o.req) resp, err := o.Client.Read(o.req)
if err != nil { if err != nil {
o.ReadError.Incr(1) o.ReadError.Incr(1)
return fmt.Errorf("RegisterNodes Read failed: %v", err) return fmt.Errorf("RegisterNodes Read failed: %w", err)
} }
o.ReadSuccess.Incr(1) o.ReadSuccess.Incr(1)
for i, d := range resp.Results { for i, d := range resp.Results {

View File

@ -8,6 +8,7 @@ import (
"github.com/gopcua/opcua" "github.com/gopcua/opcua"
"github.com/gopcua/opcua/ua" "github.com/gopcua/opcua/ua"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/opcua/input" "github.com/influxdata/telegraf/plugins/common/opcua/input"
@ -99,14 +100,13 @@ func (o *SubscribeClient) StartStreamValues(ctx context.Context) (<-chan telegra
resp, err := o.sub.MonitorWithContext(ctx, ua.TimestampsToReturnBoth, o.monitoredItemsReqs...) resp, err := o.sub.MonitorWithContext(ctx, ua.TimestampsToReturnBoth, o.monitoredItemsReqs...)
if err != nil { if err != nil {
o.Log.Error("Failed to create monitored items ", err) return nil, fmt.Errorf("failed to start monitoring items: %w", err)
return nil, fmt.Errorf("failed to start monitoring items %s", err)
} }
o.Log.Debug("Monitoring items") o.Log.Debug("Monitoring items")
for _, res := range resp.Results { for _, res := range resp.Results {
if !o.StatusCodeOK(res.StatusCode) { if !o.StatusCodeOK(res.StatusCode) {
return nil, fmt.Errorf("creating monitored item failed with status code %d", res.StatusCode) return nil, fmt.Errorf("creating monitored item failed with status code: %w", res.StatusCode)
} }
} }

View File

@ -69,7 +69,7 @@ func openntpdRunner(cmdName string, timeout config.Duration, useSudo bool) (*byt
cmd.Stdout = &out cmd.Stdout = &out
err := internal.RunTimeout(cmd, time.Duration(timeout)) err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil { if err != nil {
return &out, fmt.Errorf("error running ntpctl: %s", err) return &out, fmt.Errorf("error running ntpctl: %w", err)
} }
return &out, nil return &out, nil
@ -82,7 +82,7 @@ func (*Openntpd) SampleConfig() string {
func (n *Openntpd) Gather(acc telegraf.Accumulator) error { func (n *Openntpd) Gather(acc telegraf.Accumulator) error {
out, err := n.run(n.Binary, n.Timeout, n.UseSudo) out, err := n.run(n.Binary, n.Timeout, n.UseSudo)
if err != nil { if err != nil {
return fmt.Errorf("error gathering metrics: %s", err) return fmt.Errorf("error gathering metrics: %w", err)
} }
lineCounter := 0 lineCounter := 0

View File

@ -12,12 +12,13 @@ import (
"sync" "sync"
"time" "time"
"github.com/opensearch-project/opensearch-go/v2"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
influxtls "github.com/influxdata/telegraf/plugins/common/tls" influxtls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"github.com/opensearch-project/opensearch-go/v2"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
) )
//go:embed sample.conf //go:embed sample.conf
@ -143,7 +144,7 @@ func (o *OpensearchQuery) Gather(acc telegraf.Accumulator) error {
defer wg.Done() defer wg.Done()
err := o.osAggregationQuery(acc, agg) err := o.osAggregationQuery(acc, agg)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("opensearch query aggregation %s: %s ", agg.MeasurementName, err)) acc.AddError(fmt.Errorf("opensearch query aggregation %q: %w ", agg.MeasurementName, err))
} }
}(agg) }(agg)
} }
@ -212,7 +213,7 @@ func (o *OpensearchQuery) runAggregationQuery(ctx context.Context, aggregation o
return nil, err return nil, err
} }
if resp.IsError() { if resp.IsError() {
return nil, fmt.Errorf("Opensearch SearchRequest failure: [%d] %s", resp.StatusCode, resp.Status()) return nil, fmt.Errorf("opensearch SearchRequest failure: [%d] %s", resp.StatusCode, resp.Status())
} }
defer resp.Body.Close() defer resp.Body.Close()

View File

@ -50,7 +50,7 @@ func opensmtpdRunner(cmdName string, timeout config.Duration, useSudo bool) (*by
cmd.Stdout = &out cmd.Stdout = &out
err := internal.RunTimeout(cmd, time.Duration(timeout)) err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil { if err != nil {
return &out, fmt.Errorf("error running smtpctl: %s", err) return &out, fmt.Errorf("error running smtpctl: %w", err)
} }
return &out, nil return &out, nil
@ -73,7 +73,7 @@ func (s *Opensmtpd) Gather(acc telegraf.Accumulator) error {
out, err := s.run(s.Binary, s.Timeout, s.UseSudo) out, err := s.run(s.Binary, s.Timeout, s.UseSudo)
if err != nil { if err != nil {
return fmt.Errorf("error gathering metrics: %s", err) return fmt.Errorf("error gathering metrics: %w", err)
} }
// Process values // Process values

View File

@ -145,7 +145,7 @@ func (o *OpenStack) Init() error {
} }
provider, err := openstack.NewClient(authOption.IdentityEndpoint) provider, err := openstack.NewClient(authOption.IdentityEndpoint)
if err != nil { if err != nil {
return fmt.Errorf("unable to create client for OpenStack endpoint %v", err) return fmt.Errorf("unable to create client for OpenStack endpoint: %w", err)
} }
ctx := context.Background() ctx := context.Background()
@ -157,38 +157,38 @@ func (o *OpenStack) Init() error {
provider.HTTPClient = *client provider.HTTPClient = *client
if err := openstack.Authenticate(provider, authOption); err != nil { if err := openstack.Authenticate(provider, authOption); err != nil {
return fmt.Errorf("unable to authenticate OpenStack user %v", err) return fmt.Errorf("unable to authenticate OpenStack user: %w", err)
} }
// Create required clients and attach to the OpenStack struct // Create required clients and attach to the OpenStack struct
if o.identity, err = openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}); err != nil { if o.identity, err = openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}); err != nil {
return fmt.Errorf("unable to create V3 identity client %v", err) return fmt.Errorf("unable to create V3 identity client: %w", err)
} }
if err := o.gatherServices(); err != nil { if err := o.gatherServices(); err != nil {
return fmt.Errorf("failed to get resource openstack services %v", err) return fmt.Errorf("failed to get resource openstack services: %w", err)
} }
if o.compute, err = openstack.NewComputeV2(provider, gophercloud.EndpointOpts{}); err != nil { if o.compute, err = openstack.NewComputeV2(provider, gophercloud.EndpointOpts{}); err != nil {
return fmt.Errorf("unable to create V2 compute client %v", err) return fmt.Errorf("unable to create V2 compute client: %w", err)
} }
// Create required clients and attach to the OpenStack struct // Create required clients and attach to the OpenStack struct
if o.network, err = openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{}); err != nil { if o.network, err = openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{}); err != nil {
return fmt.Errorf("unable to create V2 network client %v", err) return fmt.Errorf("unable to create V2 network client: %w", err)
} }
// The Orchestration service is optional // The Orchestration service is optional
if o.containsService("orchestration") { if o.containsService("orchestration") {
if o.stack, err = openstack.NewOrchestrationV1(provider, gophercloud.EndpointOpts{}); err != nil { if o.stack, err = openstack.NewOrchestrationV1(provider, gophercloud.EndpointOpts{}); err != nil {
return fmt.Errorf("unable to create V1 stack client %v", err) return fmt.Errorf("unable to create V1 stack client: %w", err)
} }
} }
// The Cinder volume storage service is optional // The Cinder volume storage service is optional
if o.containsService("volumev3") { if o.containsService("volumev3") {
if o.volume, err = openstack.NewBlockStorageV3(provider, gophercloud.EndpointOpts{}); err != nil { if o.volume, err = openstack.NewBlockStorageV3(provider, gophercloud.EndpointOpts{}); err != nil {
return fmt.Errorf("unable to create V3 volume client %v", err) return fmt.Errorf("unable to create V3 volume client: %w", err)
} }
} }
@ -226,7 +226,7 @@ func (o *OpenStack) Gather(acc telegraf.Accumulator) error {
start := time.Now() start := time.Now()
gatherer := gatherers[service] gatherer := gatherers[service]
if err := gatherer(acc); err != nil { if err := gatherer(acc); err != nil {
acc.AddError(fmt.Errorf("failed to get resource %q %v", service, err)) acc.AddError(fmt.Errorf("failed to get resource %q: %w", service, err))
} }
callDuration[service] = time.Since(start).Nanoseconds() callDuration[service] = time.Since(start).Nanoseconds()
} }
@ -240,7 +240,7 @@ func (o *OpenStack) Gather(acc telegraf.Accumulator) error {
if o.ServerDiagnotics { if o.ServerDiagnotics {
if !choice.Contains("servers", o.EnabledServices) { if !choice.Contains("servers", o.EnabledServices) {
if err := o.gatherServers(acc); err != nil { if err := o.gatherServers(acc); err != nil {
acc.AddError(fmt.Errorf("failed to get resource server diagnostics %v", err)) acc.AddError(fmt.Errorf("failed to get resource server diagnostics: %w", err))
return nil return nil
} }
} }
@ -254,11 +254,11 @@ func (o *OpenStack) Gather(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherServices() error { func (o *OpenStack) gatherServices() error {
page, err := services.List(o.identity, &services.ListOpts{}).AllPages() page, err := services.List(o.identity, &services.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list services %v", err) return fmt.Errorf("unable to list services: %w", err)
} }
extractedServices, err := services.ExtractServices(page) extractedServices, err := services.ExtractServices(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract services %v", err) return fmt.Errorf("unable to extract services: %w", err)
} }
for _, service := range extractedServices { for _, service := range extractedServices {
o.openstackServices[service.ID] = service o.openstackServices[service.ID] = service
@ -271,11 +271,11 @@ func (o *OpenStack) gatherServices() error {
func (o *OpenStack) gatherStacks(acc telegraf.Accumulator) error { func (o *OpenStack) gatherStacks(acc telegraf.Accumulator) error {
page, err := stacks.List(o.stack, &stacks.ListOpts{}).AllPages() page, err := stacks.List(o.stack, &stacks.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list stacks %v", err) return fmt.Errorf("unable to list stacks: %w", err)
} }
extractedStacks, err := stacks.ExtractStacks(page) extractedStacks, err := stacks.ExtractStacks(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract stacks %v", err) return fmt.Errorf("unable to extract stacks: %w", err)
} }
for _, stack := range extractedStacks { for _, stack := range extractedStacks {
tags := map[string]string{ tags := map[string]string{
@ -302,11 +302,11 @@ func (o *OpenStack) gatherStacks(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherNovaServices(acc telegraf.Accumulator) error { func (o *OpenStack) gatherNovaServices(acc telegraf.Accumulator) error {
page, err := nova_services.List(o.compute, &nova_services.ListOpts{}).AllPages() page, err := nova_services.List(o.compute, &nova_services.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list nova_services %v", err) return fmt.Errorf("unable to list nova_services: %w", err)
} }
novaServices, err := nova_services.ExtractServices(page) novaServices, err := nova_services.ExtractServices(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract nova_services %v", err) return fmt.Errorf("unable to extract nova_services: %w", err)
} }
for _, novaService := range novaServices { for _, novaService := range novaServices {
tags := map[string]string{ tags := map[string]string{
@ -332,11 +332,11 @@ func (o *OpenStack) gatherNovaServices(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherSubnets(acc telegraf.Accumulator) error { func (o *OpenStack) gatherSubnets(acc telegraf.Accumulator) error {
page, err := subnets.List(o.network, &subnets.ListOpts{}).AllPages() page, err := subnets.List(o.network, &subnets.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list subnets %v", err) return fmt.Errorf("unable to list subnets: %w", err)
} }
extractedSubnets, err := subnets.ExtractSubnets(page) extractedSubnets, err := subnets.ExtractSubnets(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract subnets %v", err) return fmt.Errorf("unable to extract subnets: %w", err)
} }
for _, subnet := range extractedSubnets { for _, subnet := range extractedSubnets {
var allocationPools []string var allocationPools []string
@ -374,11 +374,11 @@ func (o *OpenStack) gatherSubnets(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherPorts(acc telegraf.Accumulator) error { func (o *OpenStack) gatherPorts(acc telegraf.Accumulator) error {
page, err := ports.List(o.network, &ports.ListOpts{}).AllPages() page, err := ports.List(o.network, &ports.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list ports %v", err) return fmt.Errorf("unable to list ports: %w", err)
} }
extractedPorts, err := ports.ExtractPorts(page) extractedPorts, err := ports.ExtractPorts(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract ports %v", err) return fmt.Errorf("unable to extract ports: %w", err)
} }
for _, port := range extractedPorts { for _, port := range extractedPorts {
tags := map[string]string{ tags := map[string]string{
@ -419,11 +419,11 @@ func (o *OpenStack) gatherPorts(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherNetworks(acc telegraf.Accumulator) error { func (o *OpenStack) gatherNetworks(acc telegraf.Accumulator) error {
page, err := networks.List(o.network, &networks.ListOpts{}).AllPages() page, err := networks.List(o.network, &networks.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list networks %v", err) return fmt.Errorf("unable to list networks: %w", err)
} }
extractedNetworks, err := networks.ExtractNetworks(page) extractedNetworks, err := networks.ExtractNetworks(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract networks %v", err) return fmt.Errorf("unable to extract networks: %w", err)
} }
for _, network := range extractedNetworks { for _, network := range extractedNetworks {
tags := map[string]string{ tags := map[string]string{
@ -461,11 +461,11 @@ func (o *OpenStack) gatherNetworks(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherAgents(acc telegraf.Accumulator) error { func (o *OpenStack) gatherAgents(acc telegraf.Accumulator) error {
page, err := agents.List(o.network, &agents.ListOpts{}).AllPages() page, err := agents.List(o.network, &agents.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list neutron agents %v", err) return fmt.Errorf("unable to list neutron agents: %w", err)
} }
extractedAgents, err := agents.ExtractAgents(page) extractedAgents, err := agents.ExtractAgents(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract neutron agents %v", err) return fmt.Errorf("unable to extract neutron agents: %w", err)
} }
for _, agent := range extractedAgents { for _, agent := range extractedAgents {
tags := map[string]string{ tags := map[string]string{
@ -494,11 +494,11 @@ func (o *OpenStack) gatherAgents(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherAggregates(acc telegraf.Accumulator) error { func (o *OpenStack) gatherAggregates(acc telegraf.Accumulator) error {
page, err := aggregates.List(o.compute).AllPages() page, err := aggregates.List(o.compute).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list aggregates %v", err) return fmt.Errorf("unable to list aggregates: %w", err)
} }
extractedAggregates, err := aggregates.ExtractAggregates(page) extractedAggregates, err := aggregates.ExtractAggregates(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract aggregates %v", err) return fmt.Errorf("unable to extract aggregates: %w", err)
} }
for _, aggregate := range extractedAggregates { for _, aggregate := range extractedAggregates {
tags := map[string]string{ tags := map[string]string{
@ -529,11 +529,11 @@ func (o *OpenStack) gatherAggregates(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherProjects(acc telegraf.Accumulator) error { func (o *OpenStack) gatherProjects(acc telegraf.Accumulator) error {
page, err := projects.List(o.identity, &projects.ListOpts{}).AllPages() page, err := projects.List(o.identity, &projects.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list projects %v", err) return fmt.Errorf("unable to list projects: %w", err)
} }
extractedProjects, err := projects.ExtractProjects(page) extractedProjects, err := projects.ExtractProjects(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract projects %v", err) return fmt.Errorf("unable to extract projects: %w", err)
} }
for _, project := range extractedProjects { for _, project := range extractedProjects {
o.openstackProjects[project.ID] = project o.openstackProjects[project.ID] = project
@ -561,11 +561,11 @@ func (o *OpenStack) gatherProjects(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherHypervisors(acc telegraf.Accumulator) error { func (o *OpenStack) gatherHypervisors(acc telegraf.Accumulator) error {
page, err := hypervisors.List(o.compute, hypervisors.ListOpts{}).AllPages() page, err := hypervisors.List(o.compute, hypervisors.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list hypervisors %v", err) return fmt.Errorf("unable to list hypervisors: %w", err)
} }
extractedHypervisors, err := hypervisors.ExtractHypervisors(page) extractedHypervisors, err := hypervisors.ExtractHypervisors(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract hypervisors %v", err) return fmt.Errorf("unable to extract hypervisors: %w", err)
} }
o.openstackHypervisors = extractedHypervisors o.openstackHypervisors = extractedHypervisors
if choice.Contains("hypervisors", o.EnabledServices) { if choice.Contains("hypervisors", o.EnabledServices) {
@ -614,11 +614,11 @@ func (o *OpenStack) gatherHypervisors(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherFlavors(acc telegraf.Accumulator) error { func (o *OpenStack) gatherFlavors(acc telegraf.Accumulator) error {
page, err := flavors.ListDetail(o.compute, &flavors.ListOpts{}).AllPages() page, err := flavors.ListDetail(o.compute, &flavors.ListOpts{}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list flavors %v", err) return fmt.Errorf("unable to list flavors: %w", err)
} }
extractedflavors, err := flavors.ExtractFlavors(page) extractedflavors, err := flavors.ExtractFlavors(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract flavors %v", err) return fmt.Errorf("unable to extract flavors: %w", err)
} }
for _, flavor := range extractedflavors { for _, flavor := range extractedflavors {
o.openstackFlavors[flavor.ID] = flavor o.openstackFlavors[flavor.ID] = flavor
@ -644,11 +644,11 @@ func (o *OpenStack) gatherFlavors(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherVolumes(acc telegraf.Accumulator) error { func (o *OpenStack) gatherVolumes(acc telegraf.Accumulator) error {
page, err := volumes.List(o.volume, &volumes.ListOpts{AllTenants: true}).AllPages() page, err := volumes.List(o.volume, &volumes.ListOpts{AllTenants: true}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list volumes %v", err) return fmt.Errorf("unable to list volumes: %w", err)
} }
v := []volume{} v := []volume{}
if err := volumes.ExtractVolumesInto(page, &v); err != nil { if err := volumes.ExtractVolumesInto(page, &v); err != nil {
return fmt.Errorf("unable to extract volumes %v", err) return fmt.Errorf("unable to extract volumes: %w", err)
} }
for _, volume := range v { for _, volume := range v {
tags := map[string]string{ tags := map[string]string{
@ -699,11 +699,11 @@ func (o *OpenStack) gatherVolumes(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherStoragePools(acc telegraf.Accumulator) error { func (o *OpenStack) gatherStoragePools(acc telegraf.Accumulator) error {
results, err := schedulerstats.List(o.volume, &schedulerstats.ListOpts{Detail: true}).AllPages() results, err := schedulerstats.List(o.volume, &schedulerstats.ListOpts{Detail: true}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list storage pools %v", err) return fmt.Errorf("unable to list storage pools: %w", err)
} }
storagePools, err := schedulerstats.ExtractStoragePools(results) storagePools, err := schedulerstats.ExtractStoragePools(results)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract storage pools %v", err) return fmt.Errorf("unable to extract storage pools: %w", err)
} }
for _, storagePool := range storagePools { for _, storagePool := range storagePools {
tags := map[string]string{ tags := map[string]string{
@ -726,18 +726,18 @@ func (o *OpenStack) gatherStoragePools(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherServers(acc telegraf.Accumulator) error { func (o *OpenStack) gatherServers(acc telegraf.Accumulator) error {
if !choice.Contains("hypervisors", o.EnabledServices) { if !choice.Contains("hypervisors", o.EnabledServices) {
if err := o.gatherHypervisors(acc); err != nil { if err := o.gatherHypervisors(acc); err != nil {
acc.AddError(fmt.Errorf("failed to get resource hypervisors %v", err)) acc.AddError(fmt.Errorf("failed to get resource hypervisors: %w", err))
} }
} }
serverGather := choice.Contains("servers", o.EnabledServices) serverGather := choice.Contains("servers", o.EnabledServices)
for _, hypervisor := range o.openstackHypervisors { for _, hypervisor := range o.openstackHypervisors {
page, err := servers.List(o.compute, &servers.ListOpts{AllTenants: true, Host: hypervisor.HypervisorHostname}).AllPages() page, err := servers.List(o.compute, &servers.ListOpts{AllTenants: true, Host: hypervisor.HypervisorHostname}).AllPages()
if err != nil { if err != nil {
return fmt.Errorf("unable to list servers %v", err) return fmt.Errorf("unable to list servers: %w", err)
} }
extractedServers, err := servers.ExtractServers(page) extractedServers, err := servers.ExtractServers(page)
if err != nil { if err != nil {
return fmt.Errorf("unable to extract servers %v", err) return fmt.Errorf("unable to extract servers: %w", err)
} }
for _, server := range extractedServers { for _, server := range extractedServers {
if serverGather { if serverGather {
@ -748,7 +748,7 @@ func (o *OpenStack) gatherServers(acc telegraf.Accumulator) error {
} }
diagnostic, err := diagnostics.Get(o.compute, server.ID).Extract() diagnostic, err := diagnostics.Get(o.compute, server.ID).Extract()
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("unable to get diagnostics for server(%v) %v", server.ID, err)) acc.AddError(fmt.Errorf("unable to get diagnostics for server %q: %w", server.ID, err))
continue continue
} }
o.diag[server.ID] = diagnostic o.diag[server.ID] = diagnostic

View File

@ -117,7 +117,7 @@ func (n *OpenWeatherMap) createHTTPClient() *http.Client {
func (n *OpenWeatherMap) gatherURL(addr string) (*Status, error) { func (n *OpenWeatherMap) gatherURL(addr string) (*Status, error) {
resp, err := n.client.Get(addr) resp, err := n.client.Get(addr)
if err != nil { if err != nil {
return nil, fmt.Errorf("error making HTTP request to %s: %s", addr, err) return nil, fmt.Errorf("error making HTTP request to %q: %w", addr, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -197,7 +197,7 @@ func gatherWeatherURL(r io.Reader) (*Status, error) {
dec := json.NewDecoder(r) dec := json.NewDecoder(r)
status := &Status{} status := &Status{}
if err := dec.Decode(status); err != nil { if err := dec.Decode(status); err != nil {
return nil, fmt.Errorf("error while decoding JSON response: %s", err) return nil, fmt.Errorf("error while decoding JSON response: %w", err)
} }
return status, nil return status, nil
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@ -213,7 +214,7 @@ func (p *P4runtime) readAllEntries(counterID uint32) ([]*p4v1.Entity, error) {
} }
rep, err := stream.Recv() rep, err := stream.Recv()
if err != nil && err != io.EOF { if err != nil && !errors.Is(err, io.EOF) {
return nil, err return nil, err
} }

View File

@ -156,7 +156,7 @@ func importMetric(stat []byte, acc telegraf.Accumulator) error {
decoder := xml.NewDecoder(bytes.NewReader(stat)) decoder := xml.NewDecoder(bytes.NewReader(stat))
decoder.CharsetReader = charset.NewReaderLabel decoder.CharsetReader = charset.NewReaderLabel
if err := decoder.Decode(&p); err != nil { if err := decoder.Decode(&p); err != nil {
return fmt.Errorf("cannot parse input with error: %v", err) return fmt.Errorf("cannot parse input with error: %w", err)
} }
tags := map[string]string{ tags := map[string]string{

View File

@ -4,6 +4,7 @@ package pf
import ( import (
"bufio" "bufio"
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"os/exec" "os/exec"
"regexp" "regexp"
@ -37,7 +38,7 @@ func (pf *PF) Gather(acc telegraf.Accumulator) error {
if pf.PfctlCommand == "" { if pf.PfctlCommand == "" {
var err error var err error
if pf.PfctlCommand, pf.PfctlArgs, err = pf.buildPfctlCmd(); err != nil { if pf.PfctlCommand, pf.PfctlArgs, err = pf.buildPfctlCmd(); err != nil {
acc.AddError(fmt.Errorf("Can't construct pfctl commandline: %s", err)) acc.AddError(fmt.Errorf("can't construct pfctl commandline: %w", err))
return nil return nil
} }
} }
@ -54,7 +55,7 @@ func (pf *PF) Gather(acc telegraf.Accumulator) error {
return nil return nil
} }
var errParseHeader = fmt.Errorf("Cannot find header in %s output", pfctlCommand) var errParseHeader = fmt.Errorf("cannot find header in %s output", pfctlCommand)
func errMissingData(tag string) error { func errMissingData(tag string) error {
return fmt.Errorf("struct data for tag %q not found in %s output", tag, pfctlCommand) return fmt.Errorf("struct data for tag %q not found in %s output", tag, pfctlCommand)
@ -186,11 +187,11 @@ func (pf *PF) callPfctl() (string, error) {
cmd := execCommand(pf.PfctlCommand, pf.PfctlArgs...) cmd := execCommand(pf.PfctlCommand, pf.PfctlArgs...)
out, oerr := cmd.Output() out, oerr := cmd.Output()
if oerr != nil { if oerr != nil {
ee, ok := oerr.(*exec.ExitError) var ee *exec.ExitError
if !ok { if !errors.As(oerr, &ee) {
return string(out), fmt.Errorf("error running %s: %s: (unable to get stderr)", pfctlCommand, oerr) return string(out), fmt.Errorf("error running %q: %w: (unable to get stderr)", pfctlCommand, oerr)
} }
return string(out), fmt.Errorf("error running %s: %s: %s", pfctlCommand, oerr, ee.Stderr) return string(out), fmt.Errorf("error running %q: %w - %s", pfctlCommand, oerr, ee.Stderr)
} }
return string(out), oerr return string(out), oerr
} }
@ -201,14 +202,14 @@ var execCommand = exec.Command
func (pf *PF) buildPfctlCmd() (string, []string, error) { func (pf *PF) buildPfctlCmd() (string, []string, error) {
cmd, err := execLookPath(pfctlCommand) cmd, err := execLookPath(pfctlCommand)
if err != nil { if err != nil {
return "", nil, fmt.Errorf("can't locate %s: %v", pfctlCommand, err) return "", nil, fmt.Errorf("can't locate %q: %w", pfctlCommand, err)
} }
args := []string{"-s", "info"} args := []string{"-s", "info"}
if pf.UseSudo { if pf.UseSudo {
args = append([]string{cmd}, args...) args = append([]string{cmd}, args...)
cmd, err = execLookPath("sudo") cmd, err = execLookPath("sudo")
if err != nil { if err != nil {
return "", nil, fmt.Errorf("can't locate sudo: %v", err) return "", nil, fmt.Errorf("can't locate sudo: %w", err)
} }
} }
return cmd, args, nil return cmd, args, nil

View File

@ -61,7 +61,7 @@ READ_LOOP:
for { for {
err1 = rec.read(c.rwc) err1 = rec.read(c.rwc)
if err1 != nil && strings.Contains(err1.Error(), "use of closed network connection") { if err1 != nil && strings.Contains(err1.Error(), "use of closed network connection") {
if err1 != io.EOF { if !errors.Is(err1, io.EOF) {
err = err1 err = err1
} }
break break

View File

@ -10,6 +10,8 @@ import (
"io" "io"
"net/http" "net/http"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
const requestID uint16 = 1 const requestID uint16 = 1
@ -242,9 +244,7 @@ func TestChildServeCleansUp(t *testing.T) {
) { ) {
// block on reading body of request // block on reading body of request
_, err := io.Copy(io.Discard, r.Body) _, err := io.Copy(io.Discard, r.Body)
if err != tt.err { require.ErrorIs(t, err, tt.err)
t.Errorf("Expected %#v, got %#v", tt.err, err)
}
// not reached if body of request isn't closed // not reached if body of request isn't closed
done <- true done <- true
})) }))

View File

@ -158,7 +158,7 @@ func (p *phpfpm) gatherFcgi(fcgi *conn, statusPath string, acc telegraf.Accumula
importMetric(bytes.NewReader(fpmOutput), acc, addr) importMetric(bytes.NewReader(fpmOutput), acc, addr)
return nil return nil
} }
return fmt.Errorf("unable parse phpfpm status, error: %v %v", string(fpmErr), err) return fmt.Errorf("unable parse phpfpm status, error: %s; %w", string(fpmErr), err)
} }
// Gather stat using http protocol // Gather stat using http protocol
@ -262,7 +262,7 @@ func globUnixSocket(address string) ([]string, error) {
pattern, status := unixSocketPaths(address) pattern, status := unixSocketPaths(address)
glob, err := globpath.Compile(pattern) glob, err := globpath.Compile(pattern)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not compile glob %q: %v", pattern, err) return nil, fmt.Errorf("could not compile glob %q: %w", pattern, err)
} }
paths := glob.Match() paths := glob.Match()
if len(paths) == 0 { if len(paths) == 0 {

View File

@ -26,7 +26,8 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
// the output. // the output.
// Linux iputils-ping returns 1, BSD-derived ping returns 2. // Linux iputils-ping returns 1, BSD-derived ping returns 2.
status := -1 status := -1
if exitError, ok := err.(*exec.ExitError); ok { var exitError *exec.ExitError
if errors.As(err, &exitError) {
if ws, ok := exitError.Sys().(syscall.WaitStatus); ok { if ws, ok := exitError.Sys().(syscall.WaitStatus); ok {
status = ws.ExitStatus() status = ws.ExitStatus()
fields["result_code"] = status fields["result_code"] = status
@ -47,9 +48,9 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
// Combine go err + stderr output // Combine go err + stderr output
out = strings.TrimSpace(out) out = strings.TrimSpace(out)
if len(out) > 0 { if len(out) > 0 {
acc.AddError(fmt.Errorf("host %s: %s, %s", u, out, err)) acc.AddError(fmt.Errorf("host %q: %w - %s", u, err, out))
} else { } else {
acc.AddError(fmt.Errorf("host %s: %s", u, err)) acc.AddError(fmt.Errorf("host %q: %w", u, err))
} }
fields["result_code"] = 2 fields["result_code"] = 2
acc.AddFields("ping", fields, tags) acc.AddFields("ping", fields, tags)
@ -59,7 +60,7 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
stats, err := processPingOutput(out) stats, err := processPingOutput(out)
if err != nil { if err != nil {
// fatal error // fatal error
acc.AddError(fmt.Errorf("%s: %s", err, u)) acc.AddError(fmt.Errorf("%q: %w", u, err))
fields["result_code"] = 2 fields["result_code"] = 2
acc.AddFields("ping", fields, tags) acc.AddFields("ping", fields, tags)
return return

View File

@ -362,7 +362,7 @@ func TestFatalPingGather(t *testing.T) {
err := acc.GatherError(p.Gather) err := acc.GatherError(p.Gather)
require.Error(t, err) require.Error(t, err)
require.EqualValues(t, err.Error(), "host www.amazon.com: ping: -i interval too short: Operation not permitted, so very bad") require.EqualValues(t, "host \"www.amazon.com\": so very bad - ping: -i interval too short: Operation not permitted", err.Error())
require.False(t, acc.HasMeasurement("packets_transmitted"), require.False(t, acc.HasMeasurement("packets_transmitted"),
"Fatal ping should not have packet measurements") "Fatal ping should not have packet measurements")
require.False(t, acc.HasMeasurement("packets_received"), require.False(t, acc.HasMeasurement("packets_received"),
@ -384,8 +384,8 @@ func TestErrorWithHostNamePingGather(t *testing.T) {
out string out string
error error error error
}{ }{
{"", errors.New("host www.amazon.com: so very bad")}, {"", errors.New("host \"www.amazon.com\": so very bad")},
{"so bad", errors.New("host www.amazon.com: so bad, so very bad")}, {"so bad", errors.New("host \"www.amazon.com\": so very bad")},
} }
for _, param := range params { for _, param := range params {
@ -397,8 +397,8 @@ func TestErrorWithHostNamePingGather(t *testing.T) {
}, },
} }
require.Error(t, acc.GatherError(p.Gather)) require.Error(t, acc.GatherError(p.Gather))
require.True(t, len(acc.Errors) > 0) require.Equal(t, 1, len(acc.Errors))
require.Contains(t, acc.Errors, param.error) require.Contains(t, acc.Errors[0].Error(), param.error.Error())
} }
} }
@ -414,7 +414,7 @@ func TestPingBinary(t *testing.T) {
} }
err := acc.GatherError(p.Gather) err := acc.GatherError(p.Gather)
require.Error(t, err) require.Error(t, err)
require.EqualValues(t, err.Error(), "fatal error processing ping output: www.google.com") require.EqualValues(t, "\"www.google.com\": fatal error processing ping output", err.Error())
} }
// Test that Gather function works using native ping // Test that Gather function works using native ping

View File

@ -35,7 +35,7 @@ func qScan(path string, acc telegraf.Accumulator) (map[string]interface{}, error
err := filepath.Walk(path, func(_ string, finfo os.FileInfo, err error) error { err := filepath.Walk(path, func(_ string, finfo os.FileInfo, err error) error {
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("error scanning %s: %s", path, err)) acc.AddError(fmt.Errorf("error scanning %q: %w", path, err))
return nil return nil
} }
if finfo.IsDir() { if finfo.IsDir() {
@ -88,14 +88,14 @@ func (p *Postfix) Gather(acc telegraf.Accumulator) error {
var err error var err error
p.QueueDirectory, err = getQueueDirectory() p.QueueDirectory, err = getQueueDirectory()
if err != nil { if err != nil {
return fmt.Errorf("unable to determine queue directory: %s", err) return fmt.Errorf("unable to determine queue directory: %w", err)
} }
} }
for _, q := range []string{"active", "hold", "incoming", "maildrop", "deferred"} { for _, q := range []string{"active", "hold", "incoming", "maildrop", "deferred"} {
fields, err := qScan(filepath.Join(p.QueueDirectory, q), acc) fields, err := qScan(filepath.Join(p.QueueDirectory, q), acc)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("error scanning queue %s: %s", q, err)) acc.AddError(fmt.Errorf("error scanning queue %q: %w", q, err))
continue continue
} }

View File

@ -104,7 +104,7 @@ var socketRegexp = regexp.MustCompile(`/\.s\.PGSQL\.\d+$`)
func (p *Service) Start(telegraf.Accumulator) (err error) { func (p *Service) Start(telegraf.Accumulator) (err error) {
addr, err := p.Address.Get() addr, err := p.Address.Get()
if err != nil { if err != nil {
return fmt.Errorf("getting address failed: %v", err) return fmt.Errorf("getting address failed: %w", err)
} }
defer config.ReleaseSecret(addr) defer config.ReleaseSecret(addr)
@ -156,7 +156,7 @@ func (p *Service) SanitizedAddress() (sanitizedAddress string, err error) {
addr, err := p.Address.Get() addr, err := p.Address.Get()
if err != nil { if err != nil {
return sanitizedAddress, fmt.Errorf("getting address for sanitization failed: %v", err) return sanitizedAddress, fmt.Errorf("getting address for sanitization failed: %w", err)
} }
defer config.ReleaseSecret(addr) defer config.ReleaseSecret(addr)

View File

@ -4,6 +4,7 @@ package powerdns
import ( import (
"bufio" "bufio"
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"io" "io"
"net" "net"
@ -73,7 +74,7 @@ func (p *Powerdns) gatherServer(address string, acc telegraf.Accumulator) error
for { for {
n, err := rw.Read(tmp) n, err := rw.Read(tmp)
if err != nil { if err != nil {
if err != io.EOF { if !errors.Is(err, io.EOF) {
return err return err
} }

View File

@ -37,7 +37,7 @@ func (p *PowerdnsRecursor) Init() error {
if p.SocketMode != "" { if p.SocketMode != "" {
mode, err := strconv.ParseUint(p.SocketMode, 8, 32) mode, err := strconv.ParseUint(p.SocketMode, 8, 32)
if err != nil { if err != nil {
return fmt.Errorf("could not parse socket_mode: %v", err) return fmt.Errorf("could not parse socket_mode: %w", err)
} }
p.mode = uint32(mode) p.mode = uint32(mode)

View File

@ -4,6 +4,7 @@ package processes
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
@ -200,7 +201,8 @@ func readProcFile(filename string) ([]byte, error) {
// Reading from /proc/<PID> fails with ESRCH if the process has // Reading from /proc/<PID> fails with ESRCH if the process has
// been terminated between open() and read(). // been terminated between open() and read().
if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.ESRCH { var perr *os.PathError
if errors.As(err, &perr) && errors.Is(perr.Err, syscall.ESRCH) {
return nil, nil return nil, nil
} }

View File

@ -18,7 +18,7 @@ type Pgrep struct {
func NewPgrep() (PIDFinder, error) { func NewPgrep() (PIDFinder, error) {
path, err := exec.LookPath("pgrep") path, err := exec.LookPath("pgrep")
if err != nil { if err != nil {
return nil, fmt.Errorf("Could not find pgrep binary: %s", err) return nil, fmt.Errorf("could not find pgrep binary: %w", err)
} }
return &Pgrep{path}, nil return &Pgrep{path}, nil
} }
@ -27,7 +27,7 @@ func (pg *Pgrep) PidFile(path string) ([]PID, error) {
var pids []PID var pids []PID
pidString, err := os.ReadFile(path) pidString, err := os.ReadFile(path)
if err != nil { if err != nil {
return pids, fmt.Errorf("Failed to read pidfile %q: %w", return pids, fmt.Errorf("failed to read pidfile %q: %w",
path, err) path, err)
} }
pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32) pid, err := strconv.ParseInt(strings.TrimSpace(string(pidString)), 10, 32)
@ -71,7 +71,7 @@ func run(path string, args []string) (string, error) {
} }
if err != nil { if err != nil {
return "", fmt.Errorf("Error running %s: %s", path, err) return "", fmt.Errorf("error running %q: %w", path, err)
} }
return string(out), err return string(out), err
} }

View File

@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
) )
@ -55,7 +56,7 @@ func (p *Prometheus) startConsul(ctx context.Context) error {
consul, err := api.NewClient(consulAPIConfig) consul, err := api.NewClient(consulAPIConfig)
if err != nil { if err != nil {
return fmt.Errorf("cannot connect to the Consul agent: %v", err) return fmt.Errorf("cannot connect to the Consul agent: %w", err)
} }
// Parse the template for metrics URL, drop queries with template parse errors // Parse the template for metrics URL, drop queries with template parse errors

View File

@ -50,26 +50,26 @@ func loadConfig(kubeconfigPath string) (*rest.Config, error) {
func (p *Prometheus) startK8s(ctx context.Context) error { func (p *Prometheus) startK8s(ctx context.Context) error {
config, err := loadConfig(p.KubeConfig) config, err := loadConfig(p.KubeConfig)
if err != nil { if err != nil {
return fmt.Errorf("failed to get rest.Config from %v - %v", p.KubeConfig, err) return fmt.Errorf("failed to get rest.Config from %q: %w", p.KubeConfig, 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: %w", err)
} }
kubeconfig := filepath.Join(u.HomeDir, ".kube/config") kubeconfig := filepath.Join(u.HomeDir, ".kube/config")
config, err = loadConfig(kubeconfig) config, err = loadConfig(kubeconfig)
if err != nil { if err != nil {
return fmt.Errorf("failed to get rest.Config from %v - %v", kubeconfig, err) return fmt.Errorf("failed to get rest.Config from %q: %w", kubeconfig, err)
} }
client, err = kubernetes.NewForConfig(config) client, err = kubernetes.NewForConfig(config)
if err != nil { if err != nil {
return fmt.Errorf("failed to get kubernetes client - %v", err) return fmt.Errorf("failed to get kubernetes client: %w", err)
} }
} }
@ -240,7 +240,7 @@ func updateCadvisorPodList(p *Prometheus, req *http.Request) error {
// Will have expected type errors for some parts of corev1.Pod struct for some unused fields // Will have expected type errors for some parts of corev1.Pod struct for some unused fields
// Instead have nil checks for every used field in case of incorrect decoding // Instead have nil checks for every used field in case of incorrect decoding
if err := json.NewDecoder(resp.Body).Decode(&cadvisorPodsResponse); err != nil { if err := json.NewDecoder(resp.Body).Decode(&cadvisorPodsResponse); err != nil {
return fmt.Errorf("decoding response failed: %v", err) return fmt.Errorf("decoding response failed: %w", err)
} }
pods := cadvisorPodsResponse.Items pods := cadvisorPodsResponse.Items

View File

@ -3,6 +3,7 @@ package prometheus
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"math" "math"
@ -36,17 +37,17 @@ func Parse(buf []byte, header http.Header, ignoreTimestamp bool) ([]telegraf.Met
for { for {
mf := &dto.MetricFamily{} mf := &dto.MetricFamily{}
if _, ierr := pbutil.ReadDelimited(reader, mf); ierr != nil { if _, ierr := pbutil.ReadDelimited(reader, mf); ierr != nil {
if ierr == io.EOF { if errors.Is(ierr, io.EOF) {
break break
} }
return nil, fmt.Errorf("reading metric family protocol buffer failed: %s", ierr) return nil, fmt.Errorf("reading metric family protocol buffer failed: %w", ierr)
} }
metricFamilies[mf.GetName()] = mf metricFamilies[mf.GetName()] = mf
} }
} else { } else {
metricFamilies, err = parser.TextToMetricFamilies(reader) metricFamilies, err = parser.TextToMetricFamilies(reader)
if err != nil { if err != nil {
return nil, fmt.Errorf("reading text format failed: %s", err) return nil, fmt.Errorf("reading text format failed: %w", err)
} }
} }

View File

@ -149,15 +149,15 @@ func (p *Prometheus) Init() error {
var err error var err error
p.podLabelSelector, err = labels.Parse(p.KubernetesLabelSelector) p.podLabelSelector, err = labels.Parse(p.KubernetesLabelSelector)
if err != nil { if err != nil {
return fmt.Errorf("error parsing the specified label selector(s): %s", err.Error()) return fmt.Errorf("error parsing the specified label selector(s): %w", err)
} }
p.podFieldSelector, err = fields.ParseSelector(p.KubernetesFieldSelector) p.podFieldSelector, err = fields.ParseSelector(p.KubernetesFieldSelector)
if err != nil { if err != nil {
return fmt.Errorf("error parsing the specified field selector(s): %s", err.Error()) return fmt.Errorf("error parsing the specified field selector(s): %w", err)
} }
isValid, invalidSelector := fieldSelectorIsSupported(p.podFieldSelector) isValid, invalidSelector := fieldSelectorIsSupported(p.podFieldSelector)
if !isValid { if !isValid {
return fmt.Errorf("the field selector %s is not supported for pods", invalidSelector) return fmt.Errorf("the field selector %q is not supported for pods", invalidSelector)
} }
p.Log.Infof("Using the label selector: %v and field selector: %v", p.podLabelSelector, p.podFieldSelector) p.Log.Infof("Using the label selector: %v and field selector: %v", p.podLabelSelector, p.podFieldSelector)
@ -339,17 +339,17 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
resp, err = uClient.Do(req) resp, err = uClient.Do(req)
} }
if err != nil { if err != nil {
return fmt.Errorf("error making HTTP request to %s: %s", u.URL, err) return fmt.Errorf("error making HTTP request to %q: %w", u.URL, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s returned HTTP status %s", u.URL, resp.Status) return fmt.Errorf("%q returned HTTP status %q", u.URL, resp.Status)
} }
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return fmt.Errorf("error reading body: %s", err) return fmt.Errorf("error reading body: %w", err)
} }
if p.MetricVersion == 2 { if p.MetricVersion == 2 {
@ -363,8 +363,7 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
} }
if err != nil { if err != nil {
return fmt.Errorf("error reading metrics for %s: %s", return fmt.Errorf("error reading metrics for %q: %w", u.URL, err)
u.URL, err)
} }
for _, metric := range metrics { for _, metric := range metrics {

View File

@ -189,11 +189,11 @@ func TestPrometheusGeneratesMetricsSlowEndpointHitTheTimeout(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
err = acc.GatherError(p.Gather) err = acc.GatherError(p.Gather)
errMessage := fmt.Sprintf("error making HTTP request to %s/metrics: Get \"%s/metrics\": "+ errMessage := fmt.Sprintf("error making HTTP request to \"%s/metrics\": Get \"%s/metrics\": "+
"context deadline exceeded (Client.Timeout exceeded while awaiting headers)", ts.URL, ts.URL) "context deadline exceeded (Client.Timeout exceeded while awaiting headers)", ts.URL, ts.URL)
errExpected := errors.New(errMessage) errExpected := errors.New(errMessage)
require.Equal(t, errExpected, err)
require.Error(t, err) require.Error(t, err)
require.Equal(t, errExpected.Error(), err.Error())
} }
func TestPrometheusGeneratesMetricsSlowEndpointNewConfigParameter(t *testing.T) { func TestPrometheusGeneratesMetricsSlowEndpointNewConfigParameter(t *testing.T) {
@ -246,7 +246,7 @@ func TestPrometheusGeneratesMetricsSlowEndpointHitTheTimeoutNewConfigParameter(t
var acc testutil.Accumulator var acc testutil.Accumulator
err = acc.GatherError(p.Gather) err = acc.GatherError(p.Gather)
require.ErrorContains(t, err, "error making HTTP request to "+ts.URL+"/metrics") require.ErrorContains(t, err, "error making HTTP request to \""+ts.URL+"/metrics\"")
} }
func TestPrometheusGeneratesSummaryMetricsV2(t *testing.T) { func TestPrometheusGeneratesSummaryMetricsV2(t *testing.T) {