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

View File

@ -32,18 +32,18 @@ func (*NetIOStats) SampleConfig() string {
func (n *NetIOStats) Gather(acc telegraf.Accumulator) error {
netio, err := n.ps.NetIO()
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, 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()
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{}
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()
// Handle error
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)
} else {
setResult(ConnectionFailed, fields, tags, n.Expect)

View File

@ -25,7 +25,7 @@ func (*NetStats) SampleConfig() string {
func (ns *NetStats) Gather(acc telegraf.Accumulator) error {
netconns, err := ns.PS.NetConnections()
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["UDP"] = 0

View File

@ -4,6 +4,7 @@ package nfsclient
import (
"bufio"
_ "embed"
"errors"
"fmt"
"os"
"regexp"
@ -50,8 +51,9 @@ func convertToUint64(line []string) ([]uint64, error) {
for _, l := range line[1:] {
val, err := strconv.ParseUint(l, 10, 64)
if err != nil {
if numError, ok := err.(*strconv.NumError); ok {
if numError.Err == strconv.ErrRange {
var numError *strconv.NumError
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)
}
}

View File

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

View File

@ -5,6 +5,7 @@ import (
"bufio"
_ "embed"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
@ -52,7 +53,7 @@ func (n *NginxPlus) 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 %q: %w", u, err))
acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue
}
@ -91,7 +92,7 @@ func (n *NginxPlus) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String())
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()
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)
status := &Status{}
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)
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
// on the server rather than simply ignore.
if err != errNotFound {
if !errors.Is(err, errNotFound) {
acc.AddError(err)
}
}
@ -57,7 +57,7 @@ func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
resp, err := n.client.Get(address)
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()

View File

@ -5,6 +5,7 @@ import (
"bufio"
_ "embed"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
@ -51,7 +52,7 @@ func (n *NginxSTS) 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 %q: %w", u, err))
acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue
}
@ -89,7 +90,7 @@ func (n *NginxSTS) createHTTPClient() (*http.Client, error) {
func (n *NginxSTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String())
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()
@ -167,7 +168,7 @@ func gatherStatusURL(r *bufio.Reader, tags map[string]string, acc telegraf.Accum
dec := json.NewDecoder(r)
status := &NginxSTSResponse{}
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{}{

View File

@ -5,6 +5,7 @@ import (
"bufio"
_ "embed"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
@ -51,7 +52,7 @@ func (n *NginxVTS) 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 %q: %w", u, err))
acc.AddError(fmt.Errorf("unable to parse address %q: %w", u, err))
continue
}
@ -89,7 +90,7 @@ func (n *NginxVTS) createHTTPClient() (*http.Client, error) {
func (n *NginxVTS) gatherURL(addr *url.URL, acc telegraf.Accumulator) error {
resp, err := n.client.Get(addr.String())
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()
@ -185,7 +186,7 @@ func gatherStatusURL(r *bufio.Reader, tags map[string]string, acc telegraf.Accum
dec := json.NewDecoder(r)
status := &NginxVTSResponse{}
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{}{

View File

@ -49,7 +49,7 @@ func (n *Nomad) Init() error {
tlsCfg, err := n.ClientConfig.TLSConfig()
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{
@ -85,7 +85,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
resp, err := n.roundTripper.RoundTrip(req)
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()
@ -95,7 +95,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return fmt.Errorf("error parsing json response: %s", err)
return fmt.Errorf("error parsing json response: %w", err)
}
return nil
@ -105,7 +105,7 @@ func (n *Nomad) loadJSON(url string, v interface{}) error {
func buildNomadMetrics(acc telegraf.Accumulator, summaryMetrics *MetricsSummary) error {
t, err := time.Parse(timeLayout, summaryMetrics.Timestamp)
if err != nil {
return fmt.Errorf("error parsing time: %s", err)
return fmt.Errorf("error parsing time: %w", err)
}
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
err := internal.RunTimeout(cmd, time.Duration(timeout))
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
@ -79,7 +79,7 @@ func (*NSD) SampleConfig() string {
func (s *NSD) Gather(acc telegraf.Accumulator) error {
out, err := s.run(s.Binary, s.Timeout, s.UseSudo, s.Server, s.ConfigFile)
if err != nil {
return fmt.Errorf("error gathering metrics: %s", err)
return fmt.Errorf("error gathering metrics: %w", err)
}
// 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())
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()
@ -122,20 +122,20 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return fmt.Errorf(`error reading body: %s`, err)
return fmt.Errorf(`error reading body: %w`, err)
}
data := &NSQStatsData{}
err = json.Unmarshal(body, data)
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.
if len(data.Version) < 1 {
wrapper := &NSQStats{}
err = json.Unmarshal(body, wrapper)
if err != nil {
return fmt.Errorf(`error parsing response: %s`, err)
return fmt.Errorf(`error parsing response: %w`, err)
}
data = &wrapper.Data
}

View File

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

View File

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

View File

@ -8,6 +8,7 @@ import (
"github.com/gopcua/opcua"
"github.com/gopcua/opcua/ua"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"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...)
if err != nil {
o.Log.Error("Failed to create monitored items ", err)
return nil, fmt.Errorf("failed to start monitoring items %s", err)
return nil, fmt.Errorf("failed to start monitoring items: %w", err)
}
o.Log.Debug("Monitoring items")
for _, res := range resp.Results {
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
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running ntpctl: %s", err)
return &out, fmt.Errorf("error running ntpctl: %w", err)
}
return &out, nil
@ -82,7 +82,7 @@ func (*Openntpd) SampleConfig() string {
func (n *Openntpd) Gather(acc telegraf.Accumulator) error {
out, err := n.run(n.Binary, n.Timeout, n.UseSudo)
if err != nil {
return fmt.Errorf("error gathering metrics: %s", err)
return fmt.Errorf("error gathering metrics: %w", err)
}
lineCounter := 0

View File

@ -12,12 +12,13 @@ import (
"sync"
"time"
"github.com/opensearch-project/opensearch-go/v2"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
influxtls "github.com/influxdata/telegraf/plugins/common/tls"
"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
@ -143,7 +144,7 @@ func (o *OpensearchQuery) Gather(acc telegraf.Accumulator) error {
defer wg.Done()
err := o.osAggregationQuery(acc, agg)
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)
}
@ -212,7 +213,7 @@ func (o *OpensearchQuery) runAggregationQuery(ctx context.Context, aggregation o
return nil, err
}
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()

View File

@ -50,7 +50,7 @@ func opensmtpdRunner(cmdName string, timeout config.Duration, useSudo bool) (*by
cmd.Stdout = &out
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running smtpctl: %s", err)
return &out, fmt.Errorf("error running smtpctl: %w", err)
}
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)
if err != nil {
return fmt.Errorf("error gathering metrics: %s", err)
return fmt.Errorf("error gathering metrics: %w", err)
}
// Process values

View File

@ -145,7 +145,7 @@ func (o *OpenStack) Init() error {
}
provider, err := openstack.NewClient(authOption.IdentityEndpoint)
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()
@ -157,38 +157,38 @@ func (o *OpenStack) Init() error {
provider.HTTPClient = *client
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
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 {
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 {
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
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
if o.containsService("orchestration") {
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
if o.containsService("volumev3") {
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()
gatherer := gatherers[service]
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()
}
@ -240,7 +240,7 @@ func (o *OpenStack) Gather(acc telegraf.Accumulator) error {
if o.ServerDiagnotics {
if !choice.Contains("servers", o.EnabledServices) {
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
}
}
@ -254,11 +254,11 @@ func (o *OpenStack) Gather(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherServices() error {
page, err := services.List(o.identity, &services.ListOpts{}).AllPages()
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)
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 {
o.openstackServices[service.ID] = service
@ -271,11 +271,11 @@ func (o *OpenStack) gatherServices() error {
func (o *OpenStack) gatherStacks(acc telegraf.Accumulator) error {
page, err := stacks.List(o.stack, &stacks.ListOpts{}).AllPages()
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)
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 {
tags := map[string]string{
@ -302,11 +302,11 @@ func (o *OpenStack) gatherStacks(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherNovaServices(acc telegraf.Accumulator) error {
page, err := nova_services.List(o.compute, &nova_services.ListOpts{}).AllPages()
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)
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 {
tags := map[string]string{
@ -332,11 +332,11 @@ func (o *OpenStack) gatherNovaServices(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherSubnets(acc telegraf.Accumulator) error {
page, err := subnets.List(o.network, &subnets.ListOpts{}).AllPages()
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)
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 {
var allocationPools []string
@ -374,11 +374,11 @@ func (o *OpenStack) gatherSubnets(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherPorts(acc telegraf.Accumulator) error {
page, err := ports.List(o.network, &ports.ListOpts{}).AllPages()
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)
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 {
tags := map[string]string{
@ -419,11 +419,11 @@ func (o *OpenStack) gatherPorts(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherNetworks(acc telegraf.Accumulator) error {
page, err := networks.List(o.network, &networks.ListOpts{}).AllPages()
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)
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 {
tags := map[string]string{
@ -461,11 +461,11 @@ func (o *OpenStack) gatherNetworks(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherAgents(acc telegraf.Accumulator) error {
page, err := agents.List(o.network, &agents.ListOpts{}).AllPages()
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)
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 {
tags := map[string]string{
@ -494,11 +494,11 @@ func (o *OpenStack) gatherAgents(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherAggregates(acc telegraf.Accumulator) error {
page, err := aggregates.List(o.compute).AllPages()
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)
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 {
tags := map[string]string{
@ -529,11 +529,11 @@ func (o *OpenStack) gatherAggregates(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherProjects(acc telegraf.Accumulator) error {
page, err := projects.List(o.identity, &projects.ListOpts{}).AllPages()
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)
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 {
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 {
page, err := hypervisors.List(o.compute, hypervisors.ListOpts{}).AllPages()
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)
if err != nil {
return fmt.Errorf("unable to extract hypervisors %v", err)
return fmt.Errorf("unable to extract hypervisors: %w", err)
}
o.openstackHypervisors = extractedHypervisors
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 {
page, err := flavors.ListDetail(o.compute, &flavors.ListOpts{}).AllPages()
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)
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 {
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 {
page, err := volumes.List(o.volume, &volumes.ListOpts{AllTenants: true}).AllPages()
if err != nil {
return fmt.Errorf("unable to list volumes %v", err)
return fmt.Errorf("unable to list volumes: %w", err)
}
v := []volume{}
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 {
tags := map[string]string{
@ -699,11 +699,11 @@ func (o *OpenStack) gatherVolumes(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherStoragePools(acc telegraf.Accumulator) error {
results, err := schedulerstats.List(o.volume, &schedulerstats.ListOpts{Detail: true}).AllPages()
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)
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 {
tags := map[string]string{
@ -726,18 +726,18 @@ func (o *OpenStack) gatherStoragePools(acc telegraf.Accumulator) error {
func (o *OpenStack) gatherServers(acc telegraf.Accumulator) error {
if !choice.Contains("hypervisors", o.EnabledServices) {
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)
for _, hypervisor := range o.openstackHypervisors {
page, err := servers.List(o.compute, &servers.ListOpts{AllTenants: true, Host: hypervisor.HypervisorHostname}).AllPages()
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)
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 {
if serverGather {
@ -748,7 +748,7 @@ func (o *OpenStack) gatherServers(acc telegraf.Accumulator) error {
}
diagnostic, err := diagnostics.Get(o.compute, server.ID).Extract()
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
}
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) {
resp, err := n.client.Get(addr)
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()
@ -197,7 +197,7 @@ func gatherWeatherURL(r io.Reader) (*Status, error) {
dec := json.NewDecoder(r)
status := &Status{}
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
}

View File

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

View File

@ -156,7 +156,7 @@ func importMetric(stat []byte, acc telegraf.Accumulator) error {
decoder := xml.NewDecoder(bytes.NewReader(stat))
decoder.CharsetReader = charset.NewReaderLabel
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{

View File

@ -4,6 +4,7 @@ package pf
import (
"bufio"
_ "embed"
"errors"
"fmt"
"os/exec"
"regexp"
@ -37,7 +38,7 @@ func (pf *PF) Gather(acc telegraf.Accumulator) error {
if pf.PfctlCommand == "" {
var err error
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
}
}
@ -54,7 +55,7 @@ func (pf *PF) Gather(acc telegraf.Accumulator) error {
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 {
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...)
out, oerr := cmd.Output()
if oerr != nil {
ee, ok := oerr.(*exec.ExitError)
if !ok {
return string(out), fmt.Errorf("error running %s: %s: (unable to get stderr)", pfctlCommand, oerr)
var ee *exec.ExitError
if !errors.As(oerr, &ee) {
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
}
@ -201,14 +202,14 @@ var execCommand = exec.Command
func (pf *PF) buildPfctlCmd() (string, []string, error) {
cmd, err := execLookPath(pfctlCommand)
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"}
if pf.UseSudo {
args = append([]string{cmd}, args...)
cmd, err = execLookPath("sudo")
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

View File

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

View File

@ -10,6 +10,8 @@ import (
"io"
"net/http"
"testing"
"github.com/stretchr/testify/require"
)
const requestID uint16 = 1
@ -242,9 +244,7 @@ func TestChildServeCleansUp(t *testing.T) {
) {
// block on reading body of request
_, err := io.Copy(io.Discard, r.Body)
if err != tt.err {
t.Errorf("Expected %#v, got %#v", tt.err, err)
}
require.ErrorIs(t, err, tt.err)
// not reached if body of request isn't closed
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)
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
@ -262,7 +262,7 @@ func globUnixSocket(address string) ([]string, error) {
pattern, status := unixSocketPaths(address)
glob, err := globpath.Compile(pattern)
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()
if len(paths) == 0 {

View File

@ -26,7 +26,8 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
// the output.
// Linux iputils-ping returns 1, BSD-derived ping returns 2.
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 {
status = ws.ExitStatus()
fields["result_code"] = status
@ -47,9 +48,9 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
// Combine go err + stderr output
out = strings.TrimSpace(out)
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 {
acc.AddError(fmt.Errorf("host %s: %s", u, err))
acc.AddError(fmt.Errorf("host %q: %w", u, err))
}
fields["result_code"] = 2
acc.AddFields("ping", fields, tags)
@ -59,7 +60,7 @@ func (p *Ping) pingToURL(u string, acc telegraf.Accumulator) {
stats, err := processPingOutput(out)
if err != nil {
// fatal error
acc.AddError(fmt.Errorf("%s: %s", err, u))
acc.AddError(fmt.Errorf("%q: %w", u, err))
fields["result_code"] = 2
acc.AddFields("ping", fields, tags)
return

View File

@ -362,7 +362,7 @@ func TestFatalPingGather(t *testing.T) {
err := acc.GatherError(p.Gather)
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"),
"Fatal ping should not have packet measurements")
require.False(t, acc.HasMeasurement("packets_received"),
@ -384,8 +384,8 @@ func TestErrorWithHostNamePingGather(t *testing.T) {
out string
error error
}{
{"", errors.New("host www.amazon.com: so very bad")},
{"so bad", errors.New("host www.amazon.com: so bad, so very bad")},
{"", errors.New("host \"www.amazon.com\": so very bad")},
{"so bad", errors.New("host \"www.amazon.com\": so very bad")},
}
for _, param := range params {
@ -397,8 +397,8 @@ func TestErrorWithHostNamePingGather(t *testing.T) {
},
}
require.Error(t, acc.GatherError(p.Gather))
require.True(t, len(acc.Errors) > 0)
require.Contains(t, acc.Errors, param.error)
require.Equal(t, 1, len(acc.Errors))
require.Contains(t, acc.Errors[0].Error(), param.error.Error())
}
}
@ -414,7 +414,7 @@ func TestPingBinary(t *testing.T) {
}
err := acc.GatherError(p.Gather)
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

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 {
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
}
if finfo.IsDir() {
@ -88,14 +88,14 @@ func (p *Postfix) Gather(acc telegraf.Accumulator) error {
var err error
p.QueueDirectory, err = getQueueDirectory()
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"} {
fields, err := qScan(filepath.Join(p.QueueDirectory, q), acc)
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
}

View File

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

View File

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

View File

@ -37,7 +37,7 @@ func (p *PowerdnsRecursor) Init() error {
if p.SocketMode != "" {
mode, err := strconv.ParseUint(p.SocketMode, 8, 32)
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)

View File

@ -4,6 +4,7 @@ package processes
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
@ -200,7 +201,8 @@ func readProcFile(filename string) ([]byte, error) {
// Reading from /proc/<PID> fails with ESRCH if the process has
// 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
}

View File

@ -18,7 +18,7 @@ type Pgrep struct {
func NewPgrep() (PIDFinder, error) {
path, err := exec.LookPath("pgrep")
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
}
@ -27,7 +27,7 @@ func (pg *Pgrep) PidFile(path string) ([]PID, error) {
var pids []PID
pidString, err := os.ReadFile(path)
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)
}
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 {
return "", fmt.Errorf("Error running %s: %s", path, err)
return "", fmt.Errorf("error running %q: %w", path, err)
}
return string(out), err
}

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/hashicorp/consul/api"
"github.com/influxdata/telegraf/config"
)
@ -55,7 +56,7 @@ func (p *Prometheus) startConsul(ctx context.Context) error {
consul, err := api.NewClient(consulAPIConfig)
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

View File

@ -50,26 +50,26 @@ func loadConfig(kubeconfigPath string) (*rest.Config, error) {
func (p *Prometheus) startK8s(ctx context.Context) error {
config, err := loadConfig(p.KubeConfig)
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)
if err != nil {
u, err := user.Current()
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")
config, err = loadConfig(kubeconfig)
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)
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
// Instead have nil checks for every used field in case of incorrect decoding
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

View File

@ -3,6 +3,7 @@ package prometheus
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math"
@ -36,17 +37,17 @@ func Parse(buf []byte, header http.Header, ignoreTimestamp bool) ([]telegraf.Met
for {
mf := &dto.MetricFamily{}
if _, ierr := pbutil.ReadDelimited(reader, mf); ierr != nil {
if ierr == io.EOF {
if errors.Is(ierr, io.EOF) {
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
}
} else {
metricFamilies, err = parser.TextToMetricFamilies(reader)
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
p.podLabelSelector, err = labels.Parse(p.KubernetesLabelSelector)
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)
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)
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)
@ -339,17 +339,17 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
resp, err = uClient.Do(req)
}
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()
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)
if err != nil {
return fmt.Errorf("error reading body: %s", err)
return fmt.Errorf("error reading body: %w", err)
}
if p.MetricVersion == 2 {
@ -363,8 +363,7 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
}
if err != nil {
return fmt.Errorf("error reading metrics for %s: %s",
u.URL, err)
return fmt.Errorf("error reading metrics for %q: %w", u.URL, err)
}
for _, metric := range metrics {

View File

@ -189,11 +189,11 @@ func TestPrometheusGeneratesMetricsSlowEndpointHitTheTimeout(t *testing.T) {
var acc testutil.Accumulator
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)
errExpected := errors.New(errMessage)
require.Equal(t, errExpected, err)
require.Error(t, err)
require.Equal(t, errExpected.Error(), err.Error())
}
func TestPrometheusGeneratesMetricsSlowEndpointNewConfigParameter(t *testing.T) {
@ -246,7 +246,7 @@ func TestPrometheusGeneratesMetricsSlowEndpointHitTheTimeoutNewConfigParameter(t
var acc testutil.Accumulator
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) {