refactor (discovery): move from github.com/pkg/errors to 'errors' and 'fmt' (#10807)

Signed-off-by: Matthieu MOREL <mmorel-35@users.noreply.github.com>

Co-authored-by: Matthieu MOREL <mmorel-35@users.noreply.github.com>
This commit is contained in:
Matthieu MOREL 2022-06-03 13:47:14 +02:00 committed by GitHub
parent 12de742ae4
commit f43749e82f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
35 changed files with 139 additions and 131 deletions

View file

@ -15,6 +15,7 @@ package aws
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"strings" "strings"
@ -29,7 +30,6 @@ import (
"github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -179,7 +179,7 @@ func (d *EC2Discovery) ec2Client(ctx context.Context) (*ec2.EC2, error) {
Profile: d.cfg.Profile, Profile: d.cfg.Profile,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create aws session") return nil, fmt.Errorf("could not create aws session: %w", err)
} }
if d.cfg.RoleARN != "" { if d.cfg.RoleARN != "" {
@ -328,10 +328,11 @@ func (d *EC2Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error
} }
return true return true
}); err != nil { }); err != nil {
if awsErr, ok := err.(awserr.Error); ok && (awsErr.Code() == "AuthFailure" || awsErr.Code() == "UnauthorizedOperation") { var awsErr awserr.Error
if errors.As(err, &awsErr) && (awsErr.Code() == "AuthFailure" || awsErr.Code() == "UnauthorizedOperation") {
d.ec2 = nil d.ec2 = nil
} }
return nil, errors.Wrap(err, "could not describe instances") return nil, fmt.Errorf("could not describe instances: %w", err)
} }
return []*targetgroup.Group{tg}, nil return []*targetgroup.Group{tg}, nil
} }

View file

@ -15,6 +15,7 @@ package aws
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"strings" "strings"
@ -28,7 +29,6 @@ import (
"github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lightsail" "github.com/aws/aws-sdk-go/service/lightsail"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -152,7 +152,7 @@ func (d *LightsailDiscovery) lightsailClient() (*lightsail.Lightsail, error) {
Profile: d.cfg.Profile, Profile: d.cfg.Profile,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create aws session") return nil, fmt.Errorf("could not create aws session: %w", err)
} }
if d.cfg.RoleARN != "" { if d.cfg.RoleARN != "" {
@ -179,10 +179,11 @@ func (d *LightsailDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group,
output, err := lightsailClient.GetInstancesWithContext(ctx, input) output, err := lightsailClient.GetInstancesWithContext(ctx, input)
if err != nil { if err != nil {
if awsErr, ok := err.(awserr.Error); ok && (awsErr.Code() == "AuthFailure" || awsErr.Code() == "UnauthorizedOperation") { var awsErr awserr.Error
if errors.As(err, &awsErr) && (awsErr.Code() == "AuthFailure" || awsErr.Code() == "UnauthorizedOperation") {
d.lightsail = nil d.lightsail = nil
} }
return nil, errors.Wrap(err, "could not get instances") return nil, fmt.Errorf("could not get instances: %w", err)
} }
for _, inst := range output.Instances { for _, inst := range output.Instances {

View file

@ -15,6 +15,7 @@ package azure
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
@ -29,7 +30,6 @@ import (
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
config_util "github.com/prometheus/common/config" config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -109,7 +109,7 @@ func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Di
func validateAuthParam(param, name string) error { func validateAuthParam(param, name string) error {
if len(param) == 0 { if len(param) == 0 {
return errors.Errorf("azure SD configuration requires a %s", name) return fmt.Errorf("azure SD configuration requires a %s", name)
} }
return nil return nil
} }
@ -140,7 +140,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
if c.AuthenticationMethod != authMethodOAuth && c.AuthenticationMethod != authMethodManagedIdentity { if c.AuthenticationMethod != authMethodOAuth && c.AuthenticationMethod != authMethodManagedIdentity {
return errors.Errorf("unknown authentication_type %q. Supported types are %q or %q", c.AuthenticationMethod, authMethodOAuth, authMethodManagedIdentity) return fmt.Errorf("unknown authentication_type %q. Supported types are %q or %q", c.AuthenticationMethod, authMethodOAuth, authMethodManagedIdentity)
} }
return nil return nil
@ -271,7 +271,7 @@ func newAzureResourceFromID(id string, logger log.Logger) (azureResource, error)
// /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/PROVIDER/TYPE/NAME/TYPE/NAME // /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/PROVIDER/TYPE/NAME/TYPE/NAME
s := strings.Split(id, "/") s := strings.Split(id, "/")
if len(s) != 9 && len(s) != 11 { if len(s) != 9 && len(s) != 11 {
err := errors.Errorf("invalid ID '%s'. Refusing to create azureResource", id) err := fmt.Errorf("invalid ID '%s'. Refusing to create azureResource", id)
level.Error(logger).Log("err", err) level.Error(logger).Log("err", err)
return azureResource{}, err return azureResource{}, err
} }
@ -288,13 +288,13 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
client, err := createAzureClient(*d.cfg) client, err := createAzureClient(*d.cfg)
if err != nil { if err != nil {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Wrap(err, "could not create Azure client") return nil, fmt.Errorf("could not create Azure client: %w", err)
} }
machines, err := client.getVMs(ctx, d.cfg.ResourceGroup) machines, err := client.getVMs(ctx, d.cfg.ResourceGroup)
if err != nil { if err != nil {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Wrap(err, "could not get virtual machines") return nil, fmt.Errorf("could not get virtual machines: %w", err)
} }
level.Debug(d.logger).Log("msg", "Found virtual machines during Azure discovery.", "count", len(machines)) level.Debug(d.logger).Log("msg", "Found virtual machines during Azure discovery.", "count", len(machines))
@ -303,14 +303,14 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
scaleSets, err := client.getScaleSets(ctx, d.cfg.ResourceGroup) scaleSets, err := client.getScaleSets(ctx, d.cfg.ResourceGroup)
if err != nil { if err != nil {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Wrap(err, "could not get virtual machine scale sets") return nil, fmt.Errorf("could not get virtual machine scale sets: %w", err)
} }
for _, scaleSet := range scaleSets { for _, scaleSet := range scaleSets {
scaleSetVms, err := client.getScaleSetVMs(ctx, scaleSet) scaleSetVms, err := client.getScaleSetVMs(ctx, scaleSet)
if err != nil { if err != nil {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Wrap(err, "could not get virtual machine scale set vms") return nil, fmt.Errorf("could not get virtual machine scale set vms: %w", err)
} }
machines = append(machines, scaleSetVms...) machines = append(machines, scaleSetVms...)
} }
@ -396,7 +396,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
} }
// If we made it here, we don't have a private IP which should be impossible. // If we made it here, we don't have a private IP which should be impossible.
// Return an empty target and error to ensure an all or nothing situation. // Return an empty target and error to ensure an all or nothing situation.
err = errors.Errorf("unable to find a private IP for VM %s", vm.Name) err = fmt.Errorf("unable to find a private IP for VM %s", vm.Name)
ch <- target{labelSet: nil, err: err} ch <- target{labelSet: nil, err: err}
return return
} }
@ -412,7 +412,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
for tgt := range ch { for tgt := range ch {
if tgt.err != nil { if tgt.err != nil {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Wrap(tgt.err, "unable to complete Azure service discovery") return nil, fmt.Errorf("unable to complete Azure service discovery: %w", tgt.err)
} }
if tgt.labelSet != nil { if tgt.labelSet != nil {
tg.Targets = append(tg.Targets, tgt.labelSet) tg.Targets = append(tg.Targets, tgt.labelSet)
@ -432,7 +432,7 @@ func (client *azureClient) getVMs(ctx context.Context, resourceGroup string) ([]
result, err = client.vm.List(ctx, resourceGroup) result, err = client.vm.List(ctx, resourceGroup)
} }
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machines") return nil, fmt.Errorf("could not list virtual machines: %w", err)
} }
for result.NotDone() { for result.NotDone() {
for _, vm := range result.Values() { for _, vm := range result.Values() {
@ -440,7 +440,7 @@ func (client *azureClient) getVMs(ctx context.Context, resourceGroup string) ([]
} }
err = result.NextWithContext(ctx) err = result.NextWithContext(ctx)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machines") return nil, fmt.Errorf("could not list virtual machines: %w", err)
} }
} }
@ -461,14 +461,14 @@ func (client *azureClient) getScaleSets(ctx context.Context, resourceGroup strin
var rtn compute.VirtualMachineScaleSetListWithLinkResultPage var rtn compute.VirtualMachineScaleSetListWithLinkResultPage
rtn, err = client.vmss.ListAll(ctx) rtn, err = client.vmss.ListAll(ctx)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machine scale sets") return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err)
} }
result = &rtn result = &rtn
} else { } else {
var rtn compute.VirtualMachineScaleSetListResultPage var rtn compute.VirtualMachineScaleSetListResultPage
rtn, err = client.vmss.List(ctx, resourceGroup) rtn, err = client.vmss.List(ctx, resourceGroup)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machine scale sets") return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err)
} }
result = &rtn result = &rtn
} }
@ -477,7 +477,7 @@ func (client *azureClient) getScaleSets(ctx context.Context, resourceGroup strin
scaleSets = append(scaleSets, result.Values()...) scaleSets = append(scaleSets, result.Values()...)
err = result.NextWithContext(ctx) err = result.NextWithContext(ctx)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machine scale sets") return nil, fmt.Errorf("could not list virtual machine scale sets: %w", err)
} }
} }
@ -489,12 +489,12 @@ func (client *azureClient) getScaleSetVMs(ctx context.Context, scaleSet compute.
// TODO do we really need to fetch the resourcegroup this way? // TODO do we really need to fetch the resourcegroup this way?
r, err := newAzureResourceFromID(*scaleSet.ID, nil) r, err := newAzureResourceFromID(*scaleSet.ID, nil)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not parse scale set ID") return nil, fmt.Errorf("could not parse scale set ID: %w", err)
} }
result, err := client.vmssvm.List(ctx, r.ResourceGroup, *(scaleSet.Name), "", "", "") result, err := client.vmssvm.List(ctx, r.ResourceGroup, *(scaleSet.Name), "", "", "")
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machine scale set vms") return nil, fmt.Errorf("could not list virtual machine scale set vms: %w", err)
} }
for result.NotDone() { for result.NotDone() {
for _, vm := range result.Values() { for _, vm := range result.Values() {
@ -502,7 +502,7 @@ func (client *azureClient) getScaleSetVMs(ctx context.Context, scaleSet compute.
} }
err = result.NextWithContext(ctx) err = result.NextWithContext(ctx)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not list virtual machine scale set vms") return nil, fmt.Errorf("could not list virtual machine scale set vms: %w", err)
} }
} }

View file

@ -15,6 +15,7 @@ package consul
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"strconv" "strconv"
@ -24,7 +25,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
consul "github.com/hashicorp/consul/api" consul "github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -291,7 +291,7 @@ func (d *Discovery) getDatacenter() error {
dc, ok := info["Config"]["Datacenter"].(string) dc, ok := info["Config"]["Datacenter"].(string)
if !ok { if !ok {
err := errors.Errorf("invalid value '%v' for Config.Datacenter", info["Config"]["Datacenter"]) err := fmt.Errorf("invalid value '%v' for Config.Datacenter", info["Config"]["Datacenter"])
level.Error(d.logger).Log("msg", "Error retrieving datacenter name", "err", err) level.Error(d.logger).Log("msg", "Error retrieving datacenter name", "err", err)
return err return err
} }

View file

@ -15,6 +15,7 @@ package dns
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net" "net"
"strings" "strings"
@ -24,7 +25,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/miekg/dns" "github.com/miekg/dns"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -105,7 +105,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
return errors.New("a port is required in DNS-SD configs for all record types except SRV") return errors.New("a port is required in DNS-SD configs for all record types except SRV")
} }
default: default:
return errors.Errorf("invalid DNS-SD records type %s", c.Type) return fmt.Errorf("invalid DNS-SD records type %s", c.Type)
} }
return nil return nil
} }
@ -163,7 +163,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
wg.Add(len(d.names)) wg.Add(len(d.names))
for _, name := range d.names { for _, name := range d.names {
go func(n string) { go func(n string) {
if err := d.refreshOne(ctx, n, ch); err != nil && err != context.Canceled { if err := d.refreshOne(ctx, n, ch); err != nil && !errors.Is(err, context.Canceled) {
level.Error(d.logger).Log("msg", "Error refreshing DNS targets", "err", err) level.Error(d.logger).Log("msg", "Error refreshing DNS targets", "err", err)
} }
wg.Done() wg.Done()
@ -265,7 +265,7 @@ func (d *Discovery) refreshOne(ctx context.Context, name string, ch chan<- *targ
func lookupWithSearchPath(name string, qtype uint16, logger log.Logger) (*dns.Msg, error) { func lookupWithSearchPath(name string, qtype uint16, logger log.Logger) (*dns.Msg, error) {
conf, err := dns.ClientConfigFromFile(resolvConf) conf, err := dns.ClientConfigFromFile(resolvConf)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not load resolv.conf") return nil, fmt.Errorf("could not load resolv.conf: %w", err)
} }
allResponsesValid := true allResponsesValid := true
@ -291,7 +291,7 @@ func lookupWithSearchPath(name string, qtype uint16, logger log.Logger) (*dns.Ms
return &dns.Msg{}, nil return &dns.Msg{}, nil
} }
// Outcome 3: boned. // Outcome 3: boned.
return nil, errors.Errorf("could not resolve %q: all servers responded with errors to at least one search domain", name) return nil, fmt.Errorf("could not resolve %q: all servers responded with errors to at least one search domain", name)
} }
// lookupFromAnyServer uses all configured servers to try and resolve a specific // lookupFromAnyServer uses all configured servers to try and resolve a specific
@ -327,7 +327,7 @@ func lookupFromAnyServer(name string, qtype uint16, conf *dns.ClientConfig, logg
} }
} }
return nil, errors.Errorf("could not resolve %s: no servers returned a viable answer", name) return nil, fmt.Errorf("could not resolve %s: no servers returned a viable answer", name)
} }
// askServerForName makes a request to a specific DNS server for a specific // askServerForName makes a request to a specific DNS server for a specific

View file

@ -20,7 +20,6 @@ import (
"io" "io"
"net/http" "net/http"
"github.com/pkg/errors"
"github.com/prometheus/common/version" "github.com/prometheus/common/version"
) )
@ -99,13 +98,13 @@ func fetchApps(ctx context.Context, server string, client *http.Client) (*Applic
}() }()
if resp.StatusCode/100 != 2 { if resp.StatusCode/100 != 2 {
return nil, errors.Errorf("non 2xx status '%d' response during eureka service discovery", resp.StatusCode) return nil, fmt.Errorf("non 2xx status '%d' response during eureka service discovery", resp.StatusCode)
} }
var apps Applications var apps Applications
err = xml.NewDecoder(resp.Body).Decode(&apps) err = xml.NewDecoder(resp.Body).Decode(&apps)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "%q", url) return nil, fmt.Errorf("%q: %w", url, err)
} }
return &apps, nil return &apps, nil
} }

View file

@ -15,6 +15,7 @@ package eureka
import ( import (
"context" "context"
"errors"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -22,7 +23,6 @@ import (
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"

View file

@ -16,6 +16,7 @@ package file
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -28,7 +29,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/grafana/regexp" "github.com/grafana/regexp"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -99,7 +99,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
for _, name := range c.Files { for _, name := range c.Files {
if !patFileSDName.MatchString(name) { if !patFileSDName.MatchString(name) {
return errors.Errorf("path name %q is not valid for file discovery", name) return fmt.Errorf("path name %q is not valid for file discovery", name)
} }
} }
return nil return nil
@ -398,7 +398,7 @@ func (d *Discovery) readFile(filename string) ([]*targetgroup.Group, error) {
return nil, err return nil, err
} }
default: default:
panic(errors.Errorf("discovery.File.readFile: unhandled file extension %q", ext)) panic(fmt.Errorf("discovery.File.readFile: unhandled file extension %q", ext))
} }
for i, tg := range targetGroups { for i, tg := range targetGroups {

View file

@ -15,6 +15,7 @@ package gce
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"strconv" "strconv"
@ -22,7 +23,6 @@ import (
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
compute "google.golang.org/api/compute/v1" compute "google.golang.org/api/compute/v1"
@ -132,11 +132,11 @@ func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) {
var err error var err error
d.client, err = google.DefaultClient(context.Background(), compute.ComputeReadonlyScope) d.client, err = google.DefaultClient(context.Background(), compute.ComputeReadonlyScope)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error setting up communication with GCE service") return nil, fmt.Errorf("error setting up communication with GCE service: %w", err)
} }
d.svc, err = compute.NewService(context.Background(), option.WithHTTPClient(d.client)) d.svc, err = compute.NewService(context.Background(), option.WithHTTPClient(d.client))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error setting up communication with GCE service") return nil, fmt.Errorf("error setting up communication with GCE service: %w", err)
} }
d.isvc = compute.NewInstancesService(d.svc) d.isvc = compute.NewInstancesService(d.svc)
@ -221,7 +221,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
return nil return nil
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "error retrieving refresh targets from gce") return nil, fmt.Errorf("error retrieving refresh targets from gce: %w", err)
} }
return []*targetgroup.Group{tg}, nil return []*targetgroup.Group{tg}, nil
} }

View file

@ -15,11 +15,12 @@ package hetzner
import ( import (
"context" "context"
"errors"
"fmt"
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/hetznercloud/hcloud-go/hcloud" "github.com/hetznercloud/hcloud-go/hcloud"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -95,7 +96,7 @@ func (c *role) UnmarshalYAML(unmarshal func(interface{}) error) error {
case hetznerRoleRobot, hetznerRoleHcloud: case hetznerRoleRobot, hetznerRoleHcloud:
return nil return nil
default: default:
return errors.Errorf("unknown role %q", *c) return fmt.Errorf("unknown role %q", *c)
} }
} }

View file

@ -25,7 +25,6 @@ import (
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/common/version" "github.com/prometheus/common/version"
@ -89,7 +88,7 @@ func (d *robotDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, err
}() }()
if resp.StatusCode/100 != 2 { if resp.StatusCode/100 != 2 {
return nil, errors.Errorf("non 2xx status '%d' response during hetzner service discovery with role robot", resp.StatusCode) return nil, fmt.Errorf("non 2xx status '%d' response during hetzner service discovery with role robot", resp.StatusCode)
} }
b, err := io.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)

View file

@ -16,6 +16,7 @@ package http
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -26,7 +27,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/grafana/regexp" "github.com/grafana/regexp"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -162,12 +162,12 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Errorf("server returned HTTP status %s", resp.Status) return nil, fmt.Errorf("server returned HTTP status %s", resp.Status)
} }
if !matchContentType.MatchString(strings.TrimSpace(resp.Header.Get("Content-Type"))) { if !matchContentType.MatchString(strings.TrimSpace(resp.Header.Get("Content-Type"))) {
failuresCount.Inc() failuresCount.Inc()
return nil, errors.Errorf("unsupported content type %q", resp.Header.Get("Content-Type")) return nil, fmt.Errorf("unsupported content type %q", resp.Header.Get("Content-Type"))
} }
b, err := io.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)

View file

@ -15,12 +15,13 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt"
"net" "net"
"strconv" "strconv"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
apiv1 "k8s.io/api/core/v1" apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
@ -135,7 +136,7 @@ func (e *Endpoints) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
defer e.queue.ShutDown() defer e.queue.ShutDown()
if !cache.WaitForCacheSync(ctx.Done(), e.endpointsInf.HasSynced, e.serviceInf.HasSynced, e.podInf.HasSynced) { if !cache.WaitForCacheSync(ctx.Done(), e.endpointsInf.HasSynced, e.serviceInf.HasSynced, e.podInf.HasSynced) {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(e.logger).Log("msg", "endpoints informer unable to sync cache") level.Error(e.logger).Log("msg", "endpoints informer unable to sync cache")
} }
return return
@ -188,7 +189,7 @@ func convertToEndpoints(o interface{}) (*apiv1.Endpoints, error) {
return endpoints, nil return endpoints, nil
} }
return nil, errors.Errorf("received unexpected object: %v", o) return nil, fmt.Errorf("received unexpected object: %v", o)
} }
func endpointsSource(ep *apiv1.Endpoints) string { func endpointsSource(ep *apiv1.Endpoints) string {

View file

@ -15,12 +15,12 @@ package kubernetes
import ( import (
"context" "context"
"fmt"
"net" "net"
"strconv" "strconv"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
apiv1 "k8s.io/api/core/v1" apiv1 "k8s.io/api/core/v1"
v1 "k8s.io/api/discovery/v1" v1 "k8s.io/api/discovery/v1"
@ -193,7 +193,7 @@ func (e *EndpointSlice) getEndpointSliceAdaptor(o interface{}) (endpointSliceAda
case *v1beta1.EndpointSlice: case *v1beta1.EndpointSlice:
return newEndpointSliceAdaptorFromV1beta1(endpointSlice), nil return newEndpointSliceAdaptorFromV1beta1(endpointSlice), nil
default: default:
return nil, errors.Errorf("received unexpected object: %v", o) return nil, fmt.Errorf("received unexpected object: %v", o)
} }
} }

View file

@ -15,11 +15,12 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt"
"strings" "strings"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
v1 "k8s.io/api/networking/v1" v1 "k8s.io/api/networking/v1"
"k8s.io/api/networking/v1beta1" "k8s.io/api/networking/v1beta1"
@ -78,7 +79,7 @@ func (i *Ingress) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
defer i.queue.ShutDown() defer i.queue.ShutDown()
if !cache.WaitForCacheSync(ctx.Done(), i.informer.HasSynced) { if !cache.WaitForCacheSync(ctx.Done(), i.informer.HasSynced) {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(i.logger).Log("msg", "ingress informer unable to sync cache") level.Error(i.logger).Log("msg", "ingress informer unable to sync cache")
} }
return return
@ -123,7 +124,7 @@ func (i *Ingress) process(ctx context.Context, ch chan<- []*targetgroup.Group) b
ia = newIngressAdaptorFromV1beta1(ingress) ia = newIngressAdaptorFromV1beta1(ingress)
default: default:
level.Error(i.logger).Log("msg", "converting to Ingress object failed", "err", level.Error(i.logger).Log("msg", "converting to Ingress object failed", "err",
errors.Errorf("received unexpected object: %v", o)) fmt.Errorf("received unexpected object: %v", o))
return true return true
} }
send(ctx, ch, i.buildIngress(ia)) send(ctx, ch, i.buildIngress(ia))

View file

@ -15,6 +15,7 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"os" "os"
"reflect" "reflect"
@ -24,7 +25,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -114,7 +114,7 @@ func (c *Role) UnmarshalYAML(unmarshal func(interface{}) error) error {
case RoleNode, RolePod, RoleService, RoleEndpoint, RoleEndpointSlice, RoleIngress: case RoleNode, RolePod, RoleService, RoleEndpoint, RoleEndpointSlice, RoleIngress:
return nil return nil
default: default:
return errors.Errorf("unknown Kubernetes SD role %q", *c) return fmt.Errorf("unknown Kubernetes SD role %q", *c)
} }
} }
@ -178,7 +178,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
return err return err
} }
if c.Role == "" { if c.Role == "" {
return errors.Errorf("role missing (one of: pod, service, endpoints, endpointslice, node, ingress)") return fmt.Errorf("role missing (one of: pod, service, endpoints, endpointslice, node, ingress)")
} }
err = c.HTTPClientConfig.Validate() err = c.HTTPClientConfig.Validate()
if err != nil { if err != nil {
@ -186,20 +186,20 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
if c.APIServer.URL != nil && c.KubeConfig != "" { if c.APIServer.URL != nil && c.KubeConfig != "" {
// Api-server and kubeconfig_file are mutually exclusive // Api-server and kubeconfig_file are mutually exclusive
return errors.Errorf("cannot use 'kubeconfig_file' and 'api_server' simultaneously") return fmt.Errorf("cannot use 'kubeconfig_file' and 'api_server' simultaneously")
} }
if c.KubeConfig != "" && !reflect.DeepEqual(c.HTTPClientConfig, config.DefaultHTTPClientConfig) { if c.KubeConfig != "" && !reflect.DeepEqual(c.HTTPClientConfig, config.DefaultHTTPClientConfig) {
// Kubeconfig_file and custom http config are mutually exclusive // Kubeconfig_file and custom http config are mutually exclusive
return errors.Errorf("cannot use a custom HTTP client configuration together with 'kubeconfig_file'") return fmt.Errorf("cannot use a custom HTTP client configuration together with 'kubeconfig_file'")
} }
if c.APIServer.URL == nil && !reflect.DeepEqual(c.HTTPClientConfig, config.DefaultHTTPClientConfig) { if c.APIServer.URL == nil && !reflect.DeepEqual(c.HTTPClientConfig, config.DefaultHTTPClientConfig) {
return errors.Errorf("to use custom HTTP client configuration please provide the 'api_server' URL explicitly") return fmt.Errorf("to use custom HTTP client configuration please provide the 'api_server' URL explicitly")
} }
if c.APIServer.URL != nil && c.NamespaceDiscovery.IncludeOwnNamespace { if c.APIServer.URL != nil && c.NamespaceDiscovery.IncludeOwnNamespace {
return errors.Errorf("cannot use 'api_server' and 'namespaces.own_namespace' simultaneously") return fmt.Errorf("cannot use 'api_server' and 'namespaces.own_namespace' simultaneously")
} }
if c.KubeConfig != "" && c.NamespaceDiscovery.IncludeOwnNamespace { if c.KubeConfig != "" && c.NamespaceDiscovery.IncludeOwnNamespace {
return errors.Errorf("cannot use 'kubeconfig_file' and 'namespaces.own_namespace' simultaneously") return fmt.Errorf("cannot use 'kubeconfig_file' and 'namespaces.own_namespace' simultaneously")
} }
foundSelectorRoles := make(map[Role]struct{}) foundSelectorRoles := make(map[Role]struct{})
@ -214,12 +214,12 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
for _, selector := range c.Selectors { for _, selector := range c.Selectors {
if _, ok := foundSelectorRoles[selector.Role]; ok { if _, ok := foundSelectorRoles[selector.Role]; ok {
return errors.Errorf("duplicated selector role: %s", selector.Role) return fmt.Errorf("duplicated selector role: %s", selector.Role)
} }
foundSelectorRoles[selector.Role] = struct{}{} foundSelectorRoles[selector.Role] = struct{}{}
if _, ok := allowedSelectors[c.Role]; !ok { if _, ok := allowedSelectors[c.Role]; !ok {
return errors.Errorf("invalid role: %q, expecting one of: pod, service, endpoints, endpointslice, node or ingress", c.Role) return fmt.Errorf("invalid role: %q, expecting one of: pod, service, endpoints, endpointslice, node or ingress", c.Role)
} }
var allowed bool var allowed bool
for _, role := range allowedSelectors[c.Role] { for _, role := range allowedSelectors[c.Role] {
@ -230,7 +230,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
if !allowed { if !allowed {
return errors.Errorf("%s role supports only %s selectors", c.Role, strings.Join(allowedSelectors[c.Role], ", ")) return fmt.Errorf("%s role supports only %s selectors", c.Role, strings.Join(allowedSelectors[c.Role], ", "))
} }
_, err := fields.ParseSelector(selector.Field) _, err := fields.ParseSelector(selector.Field)

View file

@ -16,11 +16,11 @@ package kubernetes
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"testing" "testing"
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/version" "k8s.io/apimachinery/pkg/version"

View file

@ -15,12 +15,13 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt"
"net" "net"
"strconv" "strconv"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
apiv1 "k8s.io/api/core/v1" apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
@ -85,7 +86,7 @@ func (n *Node) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
defer n.queue.ShutDown() defer n.queue.ShutDown()
if !cache.WaitForCacheSync(ctx.Done(), n.informer.HasSynced) { if !cache.WaitForCacheSync(ctx.Done(), n.informer.HasSynced) {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(n.logger).Log("msg", "node informer unable to sync cache") level.Error(n.logger).Log("msg", "node informer unable to sync cache")
} }
return return
@ -136,7 +137,7 @@ func convertToNode(o interface{}) (*apiv1.Node, error) {
return node, nil return node, nil
} }
return nil, errors.Errorf("received unexpected object: %v", o) return nil, fmt.Errorf("received unexpected object: %v", o)
} }
func nodeSource(n *apiv1.Node) string { func nodeSource(n *apiv1.Node) string {

View file

@ -15,13 +15,14 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt"
"net" "net"
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
apiv1 "k8s.io/api/core/v1" apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -118,7 +119,7 @@ func (p *Pod) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
} }
if !cache.WaitForCacheSync(ctx.Done(), cacheSyncs...) { if !cache.WaitForCacheSync(ctx.Done(), cacheSyncs...) {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(p.logger).Log("msg", "pod informer unable to sync cache") level.Error(p.logger).Log("msg", "pod informer unable to sync cache")
} }
return return
@ -169,7 +170,7 @@ func convertToPod(o interface{}) (*apiv1.Pod, error) {
return pod, nil return pod, nil
} }
return nil, errors.Errorf("received unexpected object: %v", o) return nil, fmt.Errorf("received unexpected object: %v", o)
} }
const ( const (

View file

@ -15,12 +15,13 @@ package kubernetes
import ( import (
"context" "context"
"errors"
"fmt"
"net" "net"
"strconv" "strconv"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
apiv1 "k8s.io/api/core/v1" apiv1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
@ -81,7 +82,7 @@ func (s *Service) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
defer s.queue.ShutDown() defer s.queue.ShutDown()
if !cache.WaitForCacheSync(ctx.Done(), s.informer.HasSynced) { if !cache.WaitForCacheSync(ctx.Done(), s.informer.HasSynced) {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(s.logger).Log("msg", "service informer unable to sync cache") level.Error(s.logger).Log("msg", "service informer unable to sync cache")
} }
return return
@ -131,7 +132,7 @@ func convertToService(o interface{}) (*apiv1.Service, error) {
if ok { if ok {
return service, nil return service, nil
} }
return nil, errors.Errorf("received unexpected object: %v", o) return nil, fmt.Errorf("received unexpected object: %v", o)
} }
func serviceSource(s *apiv1.Service) string { func serviceSource(s *apiv1.Service) string {

View file

@ -14,6 +14,7 @@
package legacymanager package legacymanager
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sort" "sort"
@ -248,7 +249,8 @@ func writeConfigs(structVal reflect.Value, configs discovery.Configs) error {
} }
func replaceYAMLTypeError(err error, oldTyp, newTyp reflect.Type) error { func replaceYAMLTypeError(err error, oldTyp, newTyp reflect.Type) error {
if e, ok := err.(*yaml.TypeError); ok { var e *yaml.TypeError
if errors.As(err, &e) {
oldStr := oldTyp.String() oldStr := oldTyp.String()
newStr := newTyp.String() newStr := newTyp.String()
for i, s := range e.Errors { for i, s := range e.Errors {

View file

@ -16,6 +16,7 @@ package marathon
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"math/rand" "math/rand"
@ -27,7 +28,6 @@ import (
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -188,7 +188,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.
// fail-fast if we can't read the file. // fail-fast if we can't read the file.
_, err := os.ReadFile(tokenFile) _, err := os.ReadFile(tokenFile)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read auth token file %s", tokenFile) return nil, fmt.Errorf("unable to read auth token file %s: %w", tokenFile, err)
} }
return &authTokenFileRoundTripper{tokenFile, rt}, nil return &authTokenFileRoundTripper{tokenFile, rt}, nil
} }
@ -196,7 +196,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.
func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
b, err := os.ReadFile(rt.authTokenFile) b, err := os.ReadFile(rt.authTokenFile)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read auth token file %s", rt.authTokenFile) return nil, fmt.Errorf("unable to read auth token file %s: %w", rt.authTokenFile, err)
} }
authToken := strings.TrimSpace(string(b)) authToken := strings.TrimSpace(string(b))
@ -336,7 +336,7 @@ func fetchApps(ctx context.Context, client *http.Client, url string) (*appList,
}() }()
if (resp.StatusCode < 200) || (resp.StatusCode >= 300) { if (resp.StatusCode < 200) || (resp.StatusCode >= 300) {
return nil, errors.Errorf("non 2xx status '%v' response during marathon service discovery", resp.StatusCode) return nil, fmt.Errorf("non 2xx status '%v' response during marathon service discovery", resp.StatusCode)
} }
b, err := io.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)
@ -347,7 +347,7 @@ func fetchApps(ctx context.Context, client *http.Client, url string) (*appList,
var apps appList var apps appList
err = json.Unmarshal(b, &apps) err = json.Unmarshal(b, &apps)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "%q", url) return nil, fmt.Errorf("%q: %w", url, err)
} }
return &apps, nil return &apps, nil
} }

View file

@ -54,7 +54,7 @@ func TestMarathonSDHandleError(t *testing.T) {
} }
) )
tgs, err := testUpdateServices(client) tgs, err := testUpdateServices(client)
if err != errTesting { if !errors.Is(err, errTesting) {
t.Fatalf("Expected error: %s", err) t.Fatalf("Expected error: %s", err)
} }
if len(tgs) != 0 { if len(tgs) != 0 {

View file

@ -23,7 +23,6 @@ import (
"github.com/gophercloud/gophercloud/openstack" "github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/hypervisors" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/hypervisors"
"github.com/gophercloud/gophercloud/pagination" "github.com/gophercloud/gophercloud/pagination"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup" "github.com/prometheus/prometheus/discovery/targetgroup"
@ -62,14 +61,14 @@ func (h *HypervisorDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group
h.provider.Context = ctx h.provider.Context = ctx
err := openstack.Authenticate(h.provider, *h.authOpts) err := openstack.Authenticate(h.provider, *h.authOpts)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not authenticate to OpenStack") return nil, fmt.Errorf("could not authenticate to OpenStack: %w", err)
} }
client, err := openstack.NewComputeV2(h.provider, gophercloud.EndpointOpts{ client, err := openstack.NewComputeV2(h.provider, gophercloud.EndpointOpts{
Region: h.region, Availability: h.availability, Region: h.region, Availability: h.availability,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create OpenStack compute session") return nil, fmt.Errorf("could not create OpenStack compute session: %w", err)
} }
tg := &targetgroup.Group{ tg := &targetgroup.Group{
@ -81,7 +80,7 @@ func (h *HypervisorDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group
err = pagerHypervisors.EachPage(func(page pagination.Page) (bool, error) { err = pagerHypervisors.EachPage(func(page pagination.Page) (bool, error) {
hypervisorList, err := hypervisors.ExtractHypervisors(page) hypervisorList, err := hypervisors.ExtractHypervisors(page)
if err != nil { if err != nil {
return false, errors.Wrap(err, "could not extract hypervisors") return false, fmt.Errorf("could not extract hypervisors: %w", err)
} }
for _, hypervisor := range hypervisorList { for _, hypervisor := range hypervisorList {
labels := model.LabelSet{} labels := model.LabelSet{}

View file

@ -25,7 +25,6 @@ import (
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips" "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers" "github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/pagination" "github.com/gophercloud/gophercloud/pagination"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup" "github.com/prometheus/prometheus/discovery/targetgroup"
@ -79,14 +78,14 @@ func (i *InstanceDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group,
i.provider.Context = ctx i.provider.Context = ctx
err := openstack.Authenticate(i.provider, *i.authOpts) err := openstack.Authenticate(i.provider, *i.authOpts)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not authenticate to OpenStack") return nil, fmt.Errorf("could not authenticate to OpenStack: %w", err)
} }
client, err := openstack.NewComputeV2(i.provider, gophercloud.EndpointOpts{ client, err := openstack.NewComputeV2(i.provider, gophercloud.EndpointOpts{
Region: i.region, Availability: i.availability, Region: i.region, Availability: i.availability,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "could not create OpenStack compute session") return nil, fmt.Errorf("could not create OpenStack compute session: %w", err)
} }
// OpenStack API reference // OpenStack API reference
@ -97,7 +96,7 @@ func (i *InstanceDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group,
err = pagerFIP.EachPage(func(page pagination.Page) (bool, error) { err = pagerFIP.EachPage(func(page pagination.Page) (bool, error) {
result, err := floatingips.ExtractFloatingIPs(page) result, err := floatingips.ExtractFloatingIPs(page)
if err != nil { if err != nil {
return false, errors.Wrap(err, "could not extract floatingips") return false, fmt.Errorf("could not extract floatingips: %w", err)
} }
for _, ip := range result { for _, ip := range result {
// Skip not associated ips // Skip not associated ips
@ -124,11 +123,11 @@ func (i *InstanceDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group,
} }
err = pager.EachPage(func(page pagination.Page) (bool, error) { err = pager.EachPage(func(page pagination.Page) (bool, error) {
if ctx.Err() != nil { if ctx.Err() != nil {
return false, errors.Wrap(ctx.Err(), "could not extract instances") return false, fmt.Errorf("could not extract instances: %w", ctx.Err())
} }
instanceList, err := servers.ExtractServers(page) instanceList, err := servers.ExtractServers(page)
if err != nil { if err != nil {
return false, errors.Wrap(err, "could not extract instances") return false, fmt.Errorf("could not extract instances: %w", err)
} }
for _, s := range instanceList { for _, s := range instanceList {

View file

@ -15,6 +15,7 @@ package openstack
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
@ -23,7 +24,6 @@ import (
"github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack" "github.com/gophercloud/gophercloud/openstack"
conntrack "github.com/mwitkow/go-conntrack" conntrack "github.com/mwitkow/go-conntrack"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -100,7 +100,7 @@ func (c *Role) UnmarshalYAML(unmarshal func(interface{}) error) error {
case OpenStackRoleHypervisor, OpenStackRoleInstance: case OpenStackRoleHypervisor, OpenStackRoleInstance:
return nil return nil
default: default:
return errors.Errorf("unknown OpenStack SD role %q", *c) return fmt.Errorf("unknown OpenStack SD role %q", *c)
} }
} }

View file

@ -29,7 +29,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/grafana/regexp" "github.com/grafana/regexp"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/common/version" "github.com/prometheus/common/version"
@ -191,11 +190,11 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
}() }()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("server returned HTTP status %s", resp.Status) return nil, fmt.Errorf("server returned HTTP status %s", resp.Status)
} }
if ct := resp.Header.Get("Content-Type"); !matchContentType.MatchString(ct) { if ct := resp.Header.Get("Content-Type"); !matchContentType.MatchString(ct) {
return nil, errors.Errorf("unsupported content type %s", resp.Header.Get("Content-Type")) return nil, fmt.Errorf("unsupported content type %s", resp.Header.Get("Content-Type"))
} }
b, err := io.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)

View file

@ -15,6 +15,7 @@ package refresh
import ( import (
"context" "context"
"errors"
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
@ -75,7 +76,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
// Get an initial set right away. // Get an initial set right away.
tgs, err := d.refresh(ctx) tgs, err := d.refresh(ctx)
if err != nil { if err != nil {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(d.logger).Log("msg", "Unable to refresh target groups", "err", err.Error()) level.Error(d.logger).Log("msg", "Unable to refresh target groups", "err", err.Error())
} }
} else { } else {
@ -94,7 +95,7 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {
case <-ticker.C: case <-ticker.C:
tgs, err := d.refresh(ctx) tgs, err := d.refresh(ctx)
if err != nil { if err != nil {
if ctx.Err() != context.Canceled { if !errors.Is(ctx.Err(), context.Canceled) {
level.Error(d.logger).Log("msg", "Unable to refresh target groups", "err", err.Error()) level.Error(d.logger).Log("msg", "Unable to refresh target groups", "err", err.Error())
} }
continue continue

View file

@ -14,6 +14,7 @@
package discovery package discovery
import ( import (
"errors"
"fmt" "fmt"
"reflect" "reflect"
"sort" "sort"
@ -247,7 +248,8 @@ func writeConfigs(structVal reflect.Value, configs Configs) error {
} }
func replaceYAMLTypeError(err error, oldTyp, newTyp reflect.Type) error { func replaceYAMLTypeError(err error, oldTyp, newTyp reflect.Type) error {
if e, ok := err.(*yaml.TypeError); ok { var e *yaml.TypeError
if errors.As(err, &e) {
oldStr := oldTyp.String() oldStr := oldTyp.String()
newStr := newTyp.String() newStr := newTyp.String()
for i, s := range e.Errors { for i, s := range e.Errors {

View file

@ -15,13 +15,14 @@ package scaleway
import ( import (
"context" "context"
"errors"
"fmt"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/scaleway/scaleway-sdk-go/scw" "github.com/scaleway/scaleway-sdk-go/scw"
@ -61,7 +62,7 @@ func (c *role) UnmarshalYAML(unmarshal func(interface{}) error) error {
case roleInstance, roleBaremetal: case roleInstance, roleBaremetal:
return nil return nil
default: default:
return errors.Errorf("unknown role %q", *c) return fmt.Errorf("unknown role %q", *c)
} }
} }
@ -228,7 +229,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.
// fail-fast if we can't read the file. // fail-fast if we can't read the file.
_, err := os.ReadFile(tokenFile) _, err := os.ReadFile(tokenFile)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read auth token file %s", tokenFile) return nil, fmt.Errorf("unable to read auth token file %s: %w", tokenFile, err)
} }
return &authTokenFileRoundTripper{tokenFile, rt}, nil return &authTokenFileRoundTripper{tokenFile, rt}, nil
} }
@ -236,7 +237,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.
func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
b, err := os.ReadFile(rt.authTokenFile) b, err := os.ReadFile(rt.authTokenFile)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read auth token file %s", rt.authTokenFile) return nil, fmt.Errorf("unable to read auth token file %s: %w", rt.authTokenFile, err)
} }
authToken := strings.TrimSpace(string(b)) authToken := strings.TrimSpace(string(b))

View file

@ -16,6 +16,7 @@ package triton
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -25,7 +26,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
conntrack "github.com/mwitkow/go-conntrack" conntrack "github.com/mwitkow/go-conntrack"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -202,7 +202,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
req = req.WithContext(ctx) req = req.WithContext(ctx)
resp, err := d.client.Do(req) resp, err := d.client.Do(req)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "an error occurred when requesting targets from the discovery endpoint") return nil, fmt.Errorf("an error occurred when requesting targets from the discovery endpoint: %w", err)
} }
defer func() { defer func() {
@ -212,7 +212,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
data, err := io.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "an error occurred when reading the response body") return nil, fmt.Errorf("an error occurred when reading the response body: %w", err)
} }
// The JSON response body is different so it needs to be processed/mapped separately. // The JSON response body is different so it needs to be processed/mapped separately.
@ -234,7 +234,7 @@ func (d *Discovery) processContainerResponse(data []byte, endpoint string) ([]*t
dr := DiscoveryResponse{} dr := DiscoveryResponse{}
err := json.Unmarshal(data, &dr) err := json.Unmarshal(data, &dr)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "an error occurred unmarshaling the discovery response json") return nil, fmt.Errorf("an error occurred unmarshaling the discovery response json: %w", err)
} }
for _, container := range dr.Containers { for _, container := range dr.Containers {
@ -267,7 +267,7 @@ func (d *Discovery) processComputeNodeResponse(data []byte, endpoint string) ([]
dr := ComputeNodeDiscoveryResponse{} dr := ComputeNodeDiscoveryResponse{}
err := json.Unmarshal(data, &dr) err := json.Unmarshal(data, &dr)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "an error occurred unmarshaling the compute node discovery response json") return nil, fmt.Errorf("an error occurred unmarshaling the compute node discovery response json: %w", err)
} }
for _, cn := range dr.ComputeNodes { for _, cn := range dr.ComputeNodes {

View file

@ -15,6 +15,7 @@ package uyuni
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -24,7 +25,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/kolo/xmlrpc" "github.com/kolo/xmlrpc"
"github.com/pkg/errors"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -131,7 +131,7 @@ func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
_, err = url.Parse(c.Server) _, err = url.Parse(c.Server)
if err != nil { if err != nil {
return errors.Wrap(err, "Uyuni Server URL is not valid") return fmt.Errorf("Uyuni Server URL is not valid: %w", err)
} }
if c.Username == "" { if c.Username == "" {
@ -276,7 +276,7 @@ func (d *Discovery) getTargetsForSystems(
systemGroupIDsBySystemID, err := getSystemGroupsInfoOfMonitoredClients(rpcClient, d.token, entitlement) systemGroupIDsBySystemID, err := getSystemGroupsInfoOfMonitoredClients(rpcClient, d.token, entitlement)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "unable to get the managed system groups information of monitored clients") return nil, fmt.Errorf("unable to get the managed system groups information of monitored clients: %w", err)
} }
systemIDs := make([]int, 0, len(systemGroupIDsBySystemID)) systemIDs := make([]int, 0, len(systemGroupIDsBySystemID))
@ -286,12 +286,12 @@ func (d *Discovery) getTargetsForSystems(
endpointInfos, err := getEndpointInfoForSystems(rpcClient, d.token, systemIDs) endpointInfos, err := getEndpointInfoForSystems(rpcClient, d.token, systemIDs)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "unable to get endpoints information") return nil, fmt.Errorf("unable to get endpoints information: %w", err)
} }
networkInfoBySystemID, err := getNetworkInformationForSystems(rpcClient, d.token, systemIDs) networkInfoBySystemID, err := getNetworkInformationForSystems(rpcClient, d.token, systemIDs)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "unable to get the systems network information") return nil, fmt.Errorf("unable to get the systems network information: %w", err)
} }
for _, endpoint := range endpointInfos { for _, endpoint := range endpointInfos {
@ -317,7 +317,7 @@ func (d *Discovery) refresh(_ context.Context) ([]*targetgroup.Group, error) {
// Uyuni API takes duration in seconds. // Uyuni API takes duration in seconds.
d.token, err = login(rpcClient, d.username, d.password, int(tokenDuration.Seconds())) d.token, err = login(rpcClient, d.username, d.password, int(tokenDuration.Seconds()))
if err != nil { if err != nil {
return nil, errors.Wrap(err, "unable to login to Uyuni API") return nil, fmt.Errorf("unable to login to Uyuni API: %w", err)
} }
// Login again at half the token lifetime. // Login again at half the token lifetime.
d.tokenExpiration = time.Now().Add(tokenDuration / 2) d.tokenExpiration = time.Now().Add(tokenDuration / 2)

View file

@ -20,7 +20,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/config" "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -92,7 +91,7 @@ func (c *KumaSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
if len(c.Server) == 0 { if len(c.Server) == 0 {
return errors.Errorf("kuma SD server must not be empty: %s", c.Server) return fmt.Errorf("kuma SD server must not be empty: %s", c.Server)
} }
parsedURL, err := url.Parse(c.Server) parsedURL, err := url.Parse(c.Server)
if err != nil { if err != nil {
@ -100,7 +99,7 @@ func (c *KumaSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
if len(parsedURL.Scheme) == 0 || len(parsedURL.Host) == 0 { if len(parsedURL.Scheme) == 0 || len(parsedURL.Host) == 0 {
return errors.Errorf("kuma SD server must not be empty and have a scheme: %s", c.Server) return fmt.Errorf("kuma SD server must not be empty and have a scheme: %s", c.Server)
} }
return c.HTTPClientConfig.Validate() return c.HTTPClientConfig.Validate()
@ -159,7 +158,7 @@ func convertKumaUserLabels(labels map[string]string) model.LabelSet {
// kumaMadsV1ResourceParser is an xds.resourceParser. // kumaMadsV1ResourceParser is an xds.resourceParser.
func kumaMadsV1ResourceParser(resources []*anypb.Any, typeURL string) ([]model.LabelSet, error) { func kumaMadsV1ResourceParser(resources []*anypb.Any, typeURL string) ([]model.LabelSet, error) {
if typeURL != KumaMadsV1ResourceTypeURL { if typeURL != KumaMadsV1ResourceTypeURL {
return nil, errors.Errorf("received invalid typeURL for Kuma MADS v1 Resource: %s", typeURL) return nil, fmt.Errorf("received invalid typeURL for Kuma MADS v1 Resource: %s", typeURL)
} }
var targets []model.LabelSet var targets []model.LabelSet

View file

@ -15,12 +15,12 @@ package xds
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"testing" "testing"
"time" "time"
v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" v3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"

View file

@ -16,6 +16,7 @@ package zookeeper
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net" "net"
"strconv" "strconv"
@ -24,7 +25,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-zookeeper/zk" "github.com/go-zookeeper/zk"
"github.com/pkg/errors"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery" "github.com/prometheus/prometheus/discovery"
@ -80,7 +80,7 @@ func (c *ServersetSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) err
} }
for _, path := range c.Paths { for _, path := range c.Paths {
if !strings.HasPrefix(path, "/") { if !strings.HasPrefix(path, "/") {
return errors.Errorf("serverset SD config paths must begin with '/': %s", path) return fmt.Errorf("serverset SD config paths must begin with '/': %s", path)
} }
} }
return nil return nil
@ -117,7 +117,7 @@ func (c *NerveSDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
} }
for _, path := range c.Paths { for _, path := range c.Paths {
if !strings.HasPrefix(path, "/") { if !strings.HasPrefix(path, "/") {
return errors.Errorf("nerve SD config paths must begin with '/': %s", path) return fmt.Errorf("nerve SD config paths must begin with '/': %s", path)
} }
} }
return nil return nil
@ -263,7 +263,7 @@ func parseServersetMember(data []byte, path string) (model.LabelSet, error) {
member := serversetMember{} member := serversetMember{}
if err := json.Unmarshal(data, &member); err != nil { if err := json.Unmarshal(data, &member); err != nil {
return nil, errors.Wrapf(err, "error unmarshaling serverset member %q", path) return nil, fmt.Errorf("error unmarshaling serverset member %q: %w", path, err)
} }
labels := model.LabelSet{} labels := model.LabelSet{}
@ -305,7 +305,7 @@ func parseNerveMember(data []byte, path string) (model.LabelSet, error) {
member := nerveMember{} member := nerveMember{}
err := json.Unmarshal(data, &member) err := json.Unmarshal(data, &member)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "error unmarshaling nerve member %q", path) return nil, fmt.Errorf("error unmarshaling nerve member %q: %w", path, err)
} }
labels := model.LabelSet{} labels := model.LabelSet{}