cleanup: purge github.com/pkg/errors

This commit is contained in:
Seth Hoenig 2022-04-01 19:24:02 -05:00
parent de191e8068
commit 9670adb6c6
27 changed files with 144 additions and 156 deletions

View File

@ -59,8 +59,9 @@ linters-settings:
# disallow packages from being used
list-type: blacklist
packages:
- github.com/hashicorp/consul/command/flags
- github.com/boltdb/bolt
- github.com/hashicorp/consul/command/flags
- github.com/pkg/errors
gocritic:
disabled-checks:
- commentFormatting

View File

@ -2,6 +2,7 @@ package allocrunner
import (
"context"
"errors"
"fmt"
"io"
"net"
@ -11,12 +12,11 @@ import (
"sync"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/allocdir"
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/pkg/errors"
)
const (

View File

@ -2,18 +2,19 @@ package allocrunner
import (
"context"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"sync"
"time"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/allocdir"
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/pkg/errors"
)
func tgFirstNetworkIsBridge(tg *structs.TaskGroup) bool {
@ -161,7 +162,7 @@ func (p *httpSocketProxy) run(alloc *structs.Allocation) error {
listener, err := net.Listen("unix", hostHTTPSockPath)
if err != nil {
return errors.Wrap(err, "unable to create unix socket for Consul HTTP endpoint")
return fmt.Errorf("unable to create unix socket for Consul HTTP endpoint: %w", err)
}
// The Consul HTTP socket should be usable by all users in case a task is
@ -169,7 +170,7 @@ func (p *httpSocketProxy) run(alloc *structs.Allocation) error {
// socket permissions when creating the file, so we must manually call
// chmod afterwards.
if err := os.Chmod(hostHTTPSockPath, os.ModePerm); err != nil {
return errors.Wrap(err, "unable to set permissions on unix socket")
return fmt.Errorf("unable to set permissions on unix socket: %w", err)
}
go func() {
@ -203,7 +204,7 @@ func maybeRemoveOldSocket(socketPath string) error {
_, err := os.Stat(socketPath)
if err == nil {
if err = os.Remove(socketPath); err != nil {
return errors.Wrap(err, "unable to remove existing unix socket")
return fmt.Errorf("unable to remove existing unix socket: %w", err)
}
}
return nil

View File

@ -2,15 +2,13 @@ package allocrunner
import (
"context"
"errors"
"fmt"
"path/filepath"
"testing"
"time"
"github.com/hashicorp/nomad/ci"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
"github.com/hashicorp/nomad/client/pluginmanager"
"github.com/hashicorp/nomad/client/pluginmanager/csimanager"
@ -20,6 +18,7 @@ import (
"github.com/hashicorp/nomad/nomad/mock"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/plugins/drivers"
"github.com/stretchr/testify/require"
)
var _ interfaces.RunnerPrerunHook = (*csiHook)(nil)

View File

@ -2,17 +2,17 @@ package taskrunner
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/allocdir"
ifs "github.com/hashicorp/nomad/client/allocrunner/interfaces"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/pkg/errors"
)
const (
@ -149,23 +149,23 @@ func (connectNativeHook) copyCertificate(source, dir, name string) error {
original, err := os.Open(source)
if err != nil {
return errors.Wrap(err, "failed to open consul TLS certificate")
return fmt.Errorf("failed to open consul TLS certificate: %w", err)
}
defer original.Close()
destination := filepath.Join(dir, name)
fd, err := os.Create(destination)
if err != nil {
return errors.Wrapf(err, "failed to create secrets/%s", name)
return fmt.Errorf("failed to create secrets/%s: %w", name, err)
}
defer fd.Close()
if _, err := io.Copy(fd, original); err != nil {
return errors.Wrapf(err, "failed to copy certificate secrets/%s", name)
return fmt.Errorf("failed to copy certificate secrets/%s: %w", name, err)
}
if err := fd.Sync(); err != nil {
return errors.Wrapf(err, "failed to write secrets/%s", name)
return fmt.Errorf("failed to write secrets/%s: %w", name, err)
}
return nil
@ -273,7 +273,7 @@ func (h *connectNativeHook) maybeSetSITokenEnv(dir, task string, env map[string]
token, err := ioutil.ReadFile(filepath.Join(dir, sidsTokenFile))
if err != nil {
if !os.IsNotExist(err) {
return errors.Wrapf(err, "failed to load SI token for native task %s", task)
return fmt.Errorf("failed to load SI token for native task %s: %w", task, err)
}
h.logger.Trace("no SI token to load for native task", "task", task)
return nil // token file DNE; acls not enabled

View File

@ -3,6 +3,7 @@ package taskrunner
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -22,7 +23,6 @@ import (
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/nomad/structs/config"
"github.com/pkg/errors"
"oss.indeed.com/go/libtime/decay"
)
@ -271,7 +271,7 @@ func (h *envoyBootstrapHook) Prestart(ctx context.Context, req *ifs.TaskPrestart
siToken, err := h.maybeLoadSIToken(req.Task.Name, req.TaskDir.SecretsDir)
if err != nil {
h.logger.Error("failed to generate envoy bootstrap config", "sidecar_for", service.Name)
return errors.Wrap(err, "failed to generate envoy bootstrap config")
return fmt.Errorf("failed to generate envoy bootstrap config: %w", err)
}
h.logger.Debug("check for SI token for task", "task", req.Task.Name, "exists", siToken != "")
@ -283,11 +283,11 @@ func (h *envoyBootstrapHook) Prestart(ctx context.Context, req *ifs.TaskPrestart
// Write args to file for debugging
argsFile, err := os.Create(bootstrapCmdPath)
if err != nil {
return errors.Wrap(err, "failed to write bootstrap command line")
return fmt.Errorf("failed to write bootstrap command line: %w", err)
}
defer argsFile.Close()
if _, err := io.WriteString(argsFile, strings.Join(bootstrapArgs, " ")+"\n"); err != nil {
return errors.Wrap(err, "failed to encode bootstrap command line")
return fmt.Errorf("failed to encode bootstrap command line: %w", err)
}
// Create environment
@ -296,13 +296,13 @@ func (h *envoyBootstrapHook) Prestart(ctx context.Context, req *ifs.TaskPrestart
// Write env to file for debugging
envFile, err := os.Create(bootstrapEnvPath)
if err != nil {
return errors.Wrap(err, "failed to write bootstrap environment")
return fmt.Errorf("failed to write bootstrap environment: %w", err)
}
defer envFile.Close()
envEnc := json.NewEncoder(envFile)
envEnc.SetIndent("", " ")
if err := envEnc.Encode(bootstrapEnv); err != nil {
return errors.Wrap(err, "failed to encode bootstrap environment")
return fmt.Errorf("failed to encode bootstrap environment: %w", err)
}
// keep track of latest error returned from exec-ing consul envoy bootstrap
@ -586,7 +586,7 @@ func (h *envoyBootstrapHook) maybeLoadSIToken(task, dir string) (string, error)
if err != nil {
if !os.IsNotExist(err) {
h.logger.Error("failed to load SI token", "task", task, "error", err)
return "", errors.Wrapf(err, "failed to load SI token for %s", task)
return "", fmt.Errorf("failed to load SI token for %s: %w", task, err)
}
h.logger.Trace("no SI token to load", "task", task)
return "", nil // token file does not exist

View File

@ -2,6 +2,7 @@ package taskrunner
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/go-hclog"
@ -11,7 +12,6 @@ import (
"github.com/hashicorp/nomad/client/taskenv"
"github.com/hashicorp/nomad/helper/envoy"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
const (
@ -81,7 +81,7 @@ func (h *envoyVersionHook) Prestart(_ context.Context, request *ifs.TaskPrestart
// to the legacy default. Query Consul and use the (possibly empty) result.
proxies, err := h.proxiesClient.Proxies()
if err != nil {
return errors.Wrap(err, "error retrieving supported Envoy versions from Consul")
return fmt.Errorf("error retrieving supported Envoy versions from Consul: %w", err)
}
// Second [pseudo] interpolation of task image. This determines the concrete
@ -89,7 +89,7 @@ func (h *envoyVersionHook) Prestart(_ context.Context, request *ifs.TaskPrestart
// ${NOMAD_envoy_version} acquired from Consul.
image, err := h.tweakImage(h.taskImage(request.Task.Config), proxies)
if err != nil {
return errors.Wrap(err, "error interpreting desired Envoy version from Consul")
return fmt.Errorf("error interpreting desired Envoy version from Consul: %w", err)
}
// Set the resulting image.
@ -187,7 +187,7 @@ func (h *envoyVersionHook) tweakImage(configured string, supported map[string][]
func semver(chosen string) (string, error) {
v, err := version.NewVersion(chosen)
if err != nil {
return "", errors.Wrap(err, "unexpected envoy version format")
return "", fmt.Errorf("unexpected envoy version format: %w", err)
}
return v.String(), nil
}

View File

@ -2,6 +2,7 @@ package taskrunner
import (
"context"
"errors"
"testing"
"github.com/hashicorp/nomad/ci"
@ -13,7 +14,6 @@ import (
"github.com/hashicorp/nomad/helper/testlog"
"github.com/hashicorp/nomad/nomad/mock"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)

View File

@ -2,6 +2,8 @@ package taskrunner
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -13,7 +15,6 @@ import (
ti "github.com/hashicorp/nomad/client/allocrunner/taskrunner/interfaces"
"github.com/hashicorp/nomad/client/consul"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
const (
@ -147,7 +148,7 @@ func (h *sidsHook) earlyExit() bool {
func (h *sidsHook) writeToken(dir string, token string) error {
tokenPath := filepath.Join(dir, sidsTokenFile)
if err := ioutil.WriteFile(tokenPath, []byte(token), sidsTokenFilePerms); err != nil {
return errors.Wrap(err, "failed to write SI token")
return fmt.Errorf("failed to write SI token: %w", err)
}
return nil
}
@ -161,7 +162,7 @@ func (h *sidsHook) recoverToken(dir string) (string, error) {
if err != nil {
if !os.IsNotExist(err) {
h.logger.Error("failed to recover SI token", "error", err)
return "", errors.Wrap(err, "failed to recover SI token")
return "", fmt.Errorf("failed to recover SI token: %w", err)
}
h.logger.Trace("no pre-existing SI token to recover", "task", h.task.Name)
return "", nil // token file does not exist yet
@ -195,7 +196,7 @@ func (h *sidsHook) deriveSIToken(ctx context.Context) (string, error) {
case result := <-resultCh:
if result.err != nil {
h.logger.Error("failed to derive SI token", "error", result.err)
h.kill(ctx, errors.Wrap(result.err, "failed to derive SI token"))
h.kill(ctx, fmt.Errorf("failed to derive SI token: %w", result.err))
return "", result.err
}
return result.token, nil

View File

@ -1,6 +1,7 @@
package client
import (
"errors"
"fmt"
"io/ioutil"
"net"
@ -19,11 +20,6 @@ import (
"github.com/hashicorp/consul/lib"
hclog "github.com/hashicorp/go-hclog"
multierror "github.com/hashicorp/go-multierror"
"github.com/hashicorp/nomad/helper/envoy"
vaultapi "github.com/hashicorp/vault/api"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/v3/host"
"github.com/hashicorp/nomad/client/allocdir"
"github.com/hashicorp/nomad/client/allocrunner"
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
@ -48,6 +44,7 @@ import (
"github.com/hashicorp/nomad/client/vaultclient"
"github.com/hashicorp/nomad/command/agent/consul"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/envoy"
"github.com/hashicorp/nomad/helper/pool"
hstats "github.com/hashicorp/nomad/helper/stats"
"github.com/hashicorp/nomad/helper/tlsutil"
@ -57,6 +54,8 @@ import (
"github.com/hashicorp/nomad/plugins/csi"
"github.com/hashicorp/nomad/plugins/device"
"github.com/hashicorp/nomad/plugins/drivers"
vaultapi "github.com/hashicorp/vault/api"
"github.com/shirou/gopsutil/v3/host"
)
const (
@ -536,7 +535,7 @@ func NewClient(cfg *config.Config, consulCatalog consul.CatalogAPI, consulProxie
}
if err := c.setupConsulTokenClient(); err != nil {
return nil, errors.Wrap(err, "failed to setup consul tokens client")
return nil, fmt.Errorf("failed to setup consul tokens client: %w", err)
}
// Setup the vault client for token and secret renewals

View File

@ -15,12 +15,11 @@ import (
"github.com/armon/go-metrics"
"github.com/hashicorp/consul/api"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/serviceregistration"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/envoy"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
const (
@ -374,7 +373,7 @@ type ServiceClient struct {
agentAPI AgentAPI
namespacesClient *NamespacesClient
logger log.Logger
logger hclog.Logger
retryInterval time.Duration
maxRetryInterval time.Duration
periodicInterval time.Duration
@ -429,7 +428,7 @@ type ServiceClient struct {
// Client, logger and takes whether the client is being used by a Nomad Client agent.
// When being used by a Nomad client, this Consul client reconciles all services and
// checks created by Nomad on behalf of running tasks.
func NewServiceClient(agentAPI AgentAPI, namespacesClient *NamespacesClient, logger log.Logger, isNomadClient bool) *ServiceClient {
func NewServiceClient(agentAPI AgentAPI, namespacesClient *NamespacesClient, logger hclog.Logger, isNomadClient bool) *ServiceClient {
logger = logger.ResetNamed("consul.sync")
return &ServiceClient{
agentAPI: agentAPI,
@ -671,7 +670,7 @@ func (c *ServiceClient) sync(reason syncReason) error {
namespaces, err := c.namespacesClient.List()
if err != nil {
metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
return errors.Wrap(err, "failed to query Consul namespaces")
return fmt.Errorf("failed to query Consul namespaces: %w", err)
}
// Accumulate all services in Consul across all namespaces.
@ -679,7 +678,7 @@ func (c *ServiceClient) sync(reason syncReason) error {
for _, namespace := range namespaces {
if nsServices, err := c.agentAPI.ServicesWithFilterOpts("", &api.QueryOptions{Namespace: normalizeNamespace(namespace)}); err != nil {
metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
return errors.Wrap(err, "failed to query Consul services")
return fmt.Errorf("failed to query Consul services: %w", err)
} else {
for k, v := range nsServices {
servicesInConsul[k] = v
@ -769,7 +768,7 @@ func (c *ServiceClient) sync(reason syncReason) error {
nsChecks, err := c.agentAPI.ChecksWithFilterOpts("", &api.QueryOptions{Namespace: normalizeNamespace(namespace)})
if err != nil {
metrics.IncrCounter([]string{"client", "consul", "sync_failure"}, 1)
return errors.Wrap(err, "failed to query Consul checks")
return fmt.Errorf("failed to query Consul checks: %w", err)
}
for k, v := range nsChecks {
checksInConsul[k] = v
@ -1321,7 +1320,7 @@ func (c *ServiceClient) AllocRegistrations(allocID string) (*serviceregistration
// Get the list of all namespaces created so we can iterate them.
namespaces, err := c.namespacesClient.List()
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve namespaces from consul")
return nil, fmt.Errorf("failed to retrieve namespaces from consul: %w", err)
}
services := make(map[string]*api.AgentService)
@ -1331,7 +1330,7 @@ func (c *ServiceClient) AllocRegistrations(allocID string) (*serviceregistration
for _, namespace := range namespaces {
nsServices, err := c.agentAPI.ServicesWithFilterOpts("", &api.QueryOptions{Namespace: normalizeNamespace(namespace)})
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve services from consul")
return nil, fmt.Errorf("failed to retrieve services from consul: %w", err)
}
for k, v := range nsServices {
services[k] = v
@ -1339,7 +1338,7 @@ func (c *ServiceClient) AllocRegistrations(allocID string) (*serviceregistration
nsChecks, err := c.agentAPI.ChecksWithFilterOpts("", &api.QueryOptions{Namespace: normalizeNamespace(namespace)})
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve checks from consul")
return nil, fmt.Errorf("failed to retrieve checks from consul: %w", err)
}
for k, v := range nsChecks {
checks[k] = v

View File

@ -1,17 +1,17 @@
package command
import (
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
humanize "github.com/dustin/go-humanize"
"github.com/dustin/go-humanize"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/api/contexts"
flaghelper "github.com/hashicorp/nomad/helper/flags"
"github.com/pkg/errors"
"github.com/posener/complete"
)

View File

@ -5,8 +5,6 @@ import (
"os"
"regexp"
"strings"
"github.com/pkg/errors"
)
// This code is taken from github.com/docker/volume/mounts/windows_parser.go
@ -73,7 +71,7 @@ const (
)
func errInvalidSpec(spec string) error {
return errors.Errorf("invalid volume specification: '%s'", spec)
return fmt.Errorf("invalid volume specification: '%s'", spec)
}
type fileInfoProvider interface {

View File

@ -10,7 +10,6 @@ import (
"testing"
"time"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
@ -84,11 +83,11 @@ func extractSerial(filename string) (int, error) {
}
b, err := ioutil.ReadFile(filename)
if err != nil {
return 0, errors.Wrap(err, "failed to extract TF serial")
return 0, fmt.Errorf("failed to extract TF serial: %w", err)
}
var state tfState
if err := json.Unmarshal(b, &state); err != nil {
return 0, errors.Wrap(err, "failed to extract TF serial")
return 0, fmt.Errorf("failed to extract TF serial: %w", err)
}
return state.Serial, nil
}

2
go.mod
View File

@ -100,7 +100,6 @@ require (
github.com/moby/sys/mountinfo v0.6.0
github.com/opencontainers/runc v1.0.3
github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417
github.com/pkg/errors v0.9.1
github.com/posener/complete v1.2.3
github.com/prometheus/client_golang v1.12.0
github.com/prometheus/common v0.32.1
@ -236,6 +235,7 @@ require (
github.com/opencontainers/selinux v1.10.0 // indirect
github.com/packethost/packngo v0.1.1-0.20180711074735-b9cb5096f54c // indirect
github.com/pierrec/lz4 v2.6.1+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/prometheus/client_model v0.2.0 // indirect

View File

@ -2,6 +2,7 @@ package nomad
import (
"context"
"errors"
"fmt"
"strings"
"sync"
@ -13,7 +14,6 @@ import (
"github.com/hashicorp/nomad/command/agent/consul"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
)
@ -195,7 +195,7 @@ func (c *consulACLsAPI) readToken(ctx context.Context, secretID string) (*api.AC
// Ensure we are under our rate limit.
if err := c.limiter.Wait(ctx); err != nil {
return nil, errors.Wrap(err, "unable to read consul token")
return nil, fmt.Errorf("unable to read consul token: %w", err)
}
consulToken, _, err := c.aclClient.TokenReadSelf(&api.QueryOptions{
@ -203,7 +203,7 @@ func (c *consulACLsAPI) readToken(ctx context.Context, secretID string) (*api.AC
Token: secretID,
})
if err != nil {
return nil, errors.Wrap(err, "unable to read consul token")
return nil, fmt.Errorf("unable to read consul token: %w", err)
}
return consulToken, nil
@ -248,7 +248,7 @@ func (c *consulACLsAPI) CheckPermissions(ctx context.Context, namespace string,
if err != nil {
return err
} else if !allowable {
return errors.Errorf("insufficient Consul ACL permissions to write service %q", service)
return fmt.Errorf("insufficient Consul ACL permissions to write service %q", service)
}
}
@ -259,7 +259,7 @@ func (c *consulACLsAPI) CheckPermissions(ctx context.Context, namespace string,
if err != nil {
return err
} else if !allowable {
return errors.Errorf("insufficient Consul ACL permissions to write Connect service %q", service)
return fmt.Errorf("insufficient Consul ACL permissions to write Connect service %q", service)
}
}
@ -389,9 +389,9 @@ func (c *consulACLsAPI) parallelRevoke(ctx context.Context, accessors []*structs
return nil
}
if err := c.singleRevoke(ctx, accessor); err != nil {
return errors.Wrapf(err,
"failed to revoke SI token accessor (alloc %q, node %q, task %q)",
accessor.AllocID, accessor.NodeID, accessor.TaskName,
return fmt.Errorf(
"failed to revoke SI token accessor (alloc %q, node %q, task %q): %w",
accessor.AllocID, accessor.NodeID, accessor.TaskName, err,
)
}
case <-pCtx.Done():

View File

@ -1,11 +1,11 @@
package nomad
import (
"fmt"
"strings"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/hcl"
"github.com/pkg/errors"
)
const (
@ -44,7 +44,7 @@ type ConsulPolicy struct {
func parseConsulPolicy(s string) (*ConsulPolicy, error) {
cp := new(ConsulPolicy)
if err := hcl.Decode(cp, s); err != nil {
return nil, errors.Wrap(err, "failed to parse ACL policy")
return nil, fmt.Errorf("failed to parse ACL policy: %w", err)
}
return cp, nil
}
@ -98,10 +98,10 @@ func namespaceCheck(namespace string, token *api.ACLToken) error {
case namespace == "" && token.Namespace != "default":
// ACLs enabled with non-default token, but namespace on job not set, so
// provide a more informative error message.
return errors.Errorf("consul ACL token requires using namespace %q", token.Namespace)
return fmt.Errorf("consul ACL token requires using namespace %q", token.Namespace)
default:
return errors.Errorf("consul ACL token cannot use namespace %q", namespace)
return fmt.Errorf("consul ACL token cannot use namespace %q", namespace)
}
}

View File

@ -7,9 +7,9 @@ import (
"sync"
"time"
metrics "github.com/armon/go-metrics"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-msgpack/codec"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/uuid"
@ -17,7 +17,6 @@ import (
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/scheduler"
"github.com/hashicorp/raft"
"github.com/pkg/errors"
)
const (
@ -80,7 +79,7 @@ type nomadFSM struct {
evalBroker *EvalBroker
blockedEvals *BlockedEvals
periodicDispatcher *PeriodicDispatch
logger log.Logger
logger hclog.Logger
state *state.StateStore
timetable *TimeTable
@ -126,7 +125,7 @@ type FSMConfig struct {
Blocked *BlockedEvals
// Logger is the logger used by the FSM
Logger log.Logger
Logger hclog.Logger
// Region is the region of the server embedding the FSM
Region string
@ -975,7 +974,7 @@ func (n *nomadFSM) applyUpsertSIAccessor(buf []byte, index uint64) interface{} {
defer metrics.MeasureSince([]string{"nomad", "fsm", "upsert_si_accessor"}, time.Now())
var request structs.SITokenAccessorsRequest
if err := structs.Decode(buf, &request); err != nil {
panic(errors.Wrap(err, "failed to decode request"))
panic(fmt.Errorf("failed to decode request: %w", err))
}
if err := n.state.UpsertSITokenAccessors(index, request.Accessors); err != nil {
@ -990,7 +989,7 @@ func (n *nomadFSM) applyDeregisterSIAccessor(buf []byte, index uint64) interface
defer metrics.MeasureSince([]string{"nomad", "fsm", "deregister_si_accessor"}, time.Now())
var request structs.SITokenAccessorsRequest
if err := structs.Decode(buf, &request); err != nil {
panic(errors.Wrap(err, "failed to decode request"))
panic(fmt.Errorf("failed to decode request: %w", err))
}
if err := n.state.DeleteSITokenAccessors(index, request.Accessors); err != nil {

View File

@ -2,21 +2,19 @@ package nomad
import (
"context"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"time"
metrics "github.com/armon/go-metrics"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
multierror "github.com/hashicorp/go-multierror"
"github.com/armon/go-metrics"
"github.com/golang/snappy"
"github.com/hashicorp/consul/lib"
"github.com/pkg/errors"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/nomad/acl"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/helper/uuid"
@ -51,7 +49,7 @@ var (
// Job endpoint is used for job interactions
type Job struct {
srv *Server
logger log.Logger
logger hclog.Logger
// builtin admission controllers
mutators []jobMutator
@ -278,7 +276,7 @@ func (j *Job) Register(args *structs.JobRegisterRequest, reply *structs.JobRegis
ctx := context.Background()
for namespace, usage := range usages {
if err := j.srv.consulACLs.CheckPermissions(ctx, namespace, usage, args.Job.ConsulToken); err != nil {
return errors.Wrap(err, "job-submitter consul token denied")
return fmt.Errorf("job-submitter consul token denied: %w", err)
}
}

View File

@ -1,6 +1,7 @@
package nomad
import (
"errors"
"fmt"
"strings"
"time"
@ -10,7 +11,6 @@ import (
"github.com/hashicorp/nomad/helper/envoy"
"github.com/hashicorp/nomad/helper/uuid"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
const (
@ -184,7 +184,7 @@ func getNamedTaskForNativeService(tg *structs.TaskGroup, serviceName, taskName s
if len(tg.Tasks) == 1 {
return tg.Tasks[0], nil
}
return nil, errors.Errorf("task for Consul Connect Native service %s->%s is ambiguous and must be set", tg.Name, serviceName)
return nil, fmt.Errorf("task for Consul Connect Native service %s->%s is ambiguous and must be set", tg.Name, serviceName)
}
for _, t := range tg.Tasks {
@ -192,7 +192,7 @@ func getNamedTaskForNativeService(tg *structs.TaskGroup, serviceName, taskName s
return t, nil
}
}
return nil, errors.Errorf("task %s named by Consul Connect Native service %s->%s does not exist", taskName, tg.Name, serviceName)
return nil, fmt.Errorf("task %s named by Consul Connect Native service %s->%s does not exist", taskName, tg.Name, serviceName)
}
func injectPort(group *structs.TaskGroup, label string) {

View File

@ -6,7 +6,6 @@ import (
"strings"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
type jobExposeCheckHook struct{}
@ -111,7 +110,7 @@ func tgValidateUseOfCheckExpose(tg *structs.TaskGroup) error {
for _, s := range tg.Services {
for _, check := range s.Checks {
if check.Expose && !s.Connect.HasSidecar() {
return errors.Errorf(
return fmt.Errorf(
"exposed service check %s->%s->%s requires use of sidecar_proxy",
tg.Name, s.Name, check.Name,
)
@ -124,7 +123,7 @@ func tgValidateUseOfCheckExpose(tg *structs.TaskGroup) error {
for _, s := range t.Services {
for _, check := range s.Checks {
if check.Expose {
return errors.Errorf(
return fmt.Errorf(
"exposed service check %s[%s]->%s->%s is not a task-group service",
tg.Name, t.Name, s.Name, check.Name,
)
@ -141,10 +140,10 @@ func tgValidateUseOfCheckExpose(tg *structs.TaskGroup) error {
func tgValidateUseOfBridgeMode(tg *structs.TaskGroup) error {
if tgUsesExposeCheck(tg) {
if len(tg.Networks) != 1 {
return errors.Errorf("group %q must specify one bridge network for exposing service check(s)", tg.Name)
return fmt.Errorf("group %q must specify one bridge network for exposing service check(s)", tg.Name)
}
if tg.Networks[0].Mode != "bridge" {
return errors.Errorf("group %q must use bridge network for exposing service check(s)", tg.Name)
return fmt.Errorf("group %q must use bridge network for exposing service check(s)", tg.Name)
}
}
return nil
@ -223,7 +222,7 @@ func exposePathForCheck(tg *structs.TaskGroup, s *structs.Service, check *struct
var port int
if mapping := tg.Networks.Port(s.PortLabel); mapping.Value <= 0 { // try looking up by port label
if port, _ = strconv.Atoi(s.PortLabel); port <= 0 { // then try direct port value
return nil, errors.Errorf(
return nil, fmt.Errorf(
"unable to determine local service port for service check %s->%s->%s",
tg.Name, s.Name, check.Name,
)

View File

@ -1,8 +1,9 @@
package nomad
import (
"fmt"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
type jobNamespaceConstraintCheckHook struct {
@ -20,7 +21,7 @@ func (c jobNamespaceConstraintCheckHook) Validate(job *structs.Job) (warnings []
return nil, err
}
if ns == nil {
return nil, errors.Errorf("job %q is in nonexistent namespace %q", job.ID, job.Namespace)
return nil, fmt.Errorf("job %q is in nonexistent namespace %q", job.ID, job.Namespace)
}
var disallowedDrivers []string
@ -33,12 +34,14 @@ func (c jobNamespaceConstraintCheckHook) Validate(job *structs.Job) (warnings []
}
if len(disallowedDrivers) > 0 {
if len(disallowedDrivers) == 1 {
return nil, errors.Errorf(
"used task driver %q is not allowed in namespace %q", disallowedDrivers[0], ns.Name)
return nil, fmt.Errorf(
"used task driver %q is not allowed in namespace %q", disallowedDrivers[0], ns.Name,
)
} else {
return nil, errors.Errorf(
"used task drivers %q are not allowed in namespace %q", disallowedDrivers, ns.Name)
return nil, fmt.Errorf(
"used task drivers %q are not allowed in namespace %q", disallowedDrivers, ns.Name,
)
}
}
return nil, nil

View File

@ -10,18 +10,16 @@ import (
"sync"
"time"
"golang.org/x/time/rate"
metrics "github.com/armon/go-metrics"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
version "github.com/hashicorp/go-version"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-version"
"github.com/hashicorp/nomad/helper/uuid"
"github.com/hashicorp/nomad/nomad/state"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/raft"
"github.com/hashicorp/serf/serf"
"github.com/pkg/errors"
"golang.org/x/time/rate"
)
const (
@ -640,7 +638,7 @@ func (s *Server) revokeSITokenAccessorsOnRestore() error {
fsmState := s.fsm.State()
iter, err := fsmState.SITokenAccessors(ws)
if err != nil {
return errors.Wrap(err, "failed to get SI token accessors")
return fmt.Errorf("failed to get SI token accessors: %w", err)
}
var toRevoke []*structs.SITokenAccessor
@ -650,7 +648,7 @@ func (s *Server) revokeSITokenAccessorsOnRestore() error {
// Check the allocation
alloc, err := fsmState.AllocByID(ws, accessor.AllocID)
if err != nil {
return errors.Wrapf(err, "failed to lookup alloc %q", accessor.AllocID)
return fmt.Errorf("failed to lookup alloc %q: %w", accessor.AllocID, err)
}
if alloc == nil || alloc.Terminated() {
// no longer running and associated accessors should be revoked
@ -661,7 +659,7 @@ func (s *Server) revokeSITokenAccessorsOnRestore() error {
// Check the node
node, err := fsmState.NodeByID(ws, accessor.NodeID)
if err != nil {
return errors.Wrapf(err, "failed to lookup node %q", accessor.NodeID)
return fmt.Errorf("failed to lookup node %q: %w", accessor.NodeID, err)
}
if node == nil || node.TerminalStatus() {
// node is terminal and associated accessors should be revoked
@ -854,7 +852,7 @@ func (s *Server) reapFailedEvaluations(stopCh chan struct{}) {
updateEval.Status = structs.EvalStatusFailed
updateEval.StatusDescription = fmt.Sprintf("evaluation reached delivery limit (%d)", s.config.EvalDeliveryLimit)
s.logger.Warn("eval reached delivery limit, marking as failed",
"eval", log.Fmt("%#v", updateEval))
"eval", hclog.Fmt("%#v", updateEval))
// Core job evals that fail or span leader elections will never
// succeed because the follow-up doesn't have the leader ACL. We
@ -878,7 +876,7 @@ func (s *Server) reapFailedEvaluations(stopCh chan struct{}) {
}
if _, _, err := s.raftApply(structs.EvalUpdateRequestType, &req); err != nil {
s.logger.Error("failed to update failed eval and create a follow-up",
"eval", log.Fmt("%#v", updateEval), "error", err)
"eval", hclog.Fmt("%#v", updateEval), "error", err)
continue
}
}
@ -917,7 +915,7 @@ func (s *Server) reapDupBlockedEvaluations(stopCh chan struct{}) {
Evals: cancel,
}
if _, _, err := s.raftApply(structs.EvalUpdateRequestType, &req); err != nil {
s.logger.Error("failed to update duplicate evals", "evals", log.Fmt("%#v", cancel), "error", err)
s.logger.Error("failed to update duplicate evals", "evals", hclog.Fmt("%#v", cancel), "error", err)
continue
}
}
@ -1681,13 +1679,13 @@ func (s *Server) getOrCreateSchedulerConfig() *structs.SchedulerConfiguration {
func (s *Server) generateClusterID() (string, error) {
if !ServersMeetMinimumVersion(s.Members(), minClusterIDVersion, false) {
s.logger.Named("core").Warn("cannot initialize cluster ID until all servers are above minimum version", "min_version", minClusterIDVersion)
return "", errors.Errorf("cluster ID cannot be created until all servers are above minimum version %s", minClusterIDVersion)
return "", fmt.Errorf("cluster ID cannot be created until all servers are above minimum version %s", minClusterIDVersion)
}
newMeta := structs.ClusterMetadata{ClusterID: uuid.Generate(), CreateTime: time.Now().UnixNano()}
if _, _, err := s.raftApply(structs.ClusterMetadataRequestType, newMeta); err != nil {
s.logger.Named("core").Error("failed to create cluster ID", "error", err)
return "", errors.Wrap(err, "failed to create cluster ID")
return "", fmt.Errorf("failed to create cluster ID: %w", err)
}
s.logger.Named("core").Info("established cluster id", "cluster_id", newMeta.ClusterID, "create_time", newMeta.CreateTime)

View File

@ -2,26 +2,24 @@ package nomad
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
metrics "github.com/armon/go-metrics"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
multierror "github.com/hashicorp/go-multierror"
vapi "github.com/hashicorp/vault/api"
"github.com/armon/go-metrics"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/nomad/acl"
"github.com/hashicorp/nomad/helper/uuid"
"github.com/hashicorp/nomad/nomad/state"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/raft"
"github.com/pkg/errors"
vapi "github.com/hashicorp/vault/api"
"golang.org/x/sync/errgroup"
)
const (
@ -53,7 +51,7 @@ const (
// Node endpoint is used for client interactions
type Node struct {
srv *Server
logger log.Logger
logger hclog.Logger
// ctx provides context regarding the underlying connection
ctx *RPCContext
@ -1759,11 +1757,11 @@ func (n *Node) DeriveSIToken(args *structs.DeriveSITokenRequest, reply *structs.
return nil
}
if node == nil {
setError(errors.Errorf("Node %q does not exist", args.NodeID), false)
setError(fmt.Errorf("Node %q does not exist", args.NodeID), false)
return nil
}
if node.SecretID != args.SecretID {
setError(errors.Errorf("SecretID mismatch"), false)
setError(errors.New("SecretID mismatch"), false)
return nil
}
@ -1773,26 +1771,26 @@ func (n *Node) DeriveSIToken(args *structs.DeriveSITokenRequest, reply *structs.
return nil
}
if alloc == nil {
setError(errors.Errorf("Allocation %q does not exist", args.AllocID), false)
setError(fmt.Errorf("Allocation %q does not exist", args.AllocID), false)
return nil
}
if alloc.NodeID != args.NodeID {
setError(errors.Errorf("Allocation %q not running on node %q", args.AllocID, args.NodeID), false)
setError(fmt.Errorf("Allocation %q not running on node %q", args.AllocID, args.NodeID), false)
return nil
}
if alloc.TerminalStatus() {
setError(errors.Errorf("Cannot request SI token for terminal allocation"), false)
setError(errors.New("Cannot request SI token for terminal allocation"), false)
return nil
}
// make sure task group contains at least one connect enabled service
tg := alloc.Job.LookupTaskGroup(alloc.TaskGroup)
if tg == nil {
setError(errors.Errorf("Allocation %q does not contain TaskGroup %q", args.AllocID, alloc.TaskGroup), false)
setError(fmt.Errorf("Allocation %q does not contain TaskGroup %q", args.AllocID, alloc.TaskGroup), false)
return nil
}
if !tg.UsesConnect() {
setError(errors.Errorf("TaskGroup %q does not use Connect", tg.Name), false)
setError(fmt.Errorf("TaskGroup %q does not use Connect", tg.Name), false)
return nil
}

View File

@ -8,11 +8,9 @@ import (
"strings"
"time"
log "github.com/hashicorp/go-hclog"
memdb "github.com/hashicorp/go-memdb"
multierror "github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-memdb"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad/stream"
"github.com/hashicorp/nomad/nomad/structs"
@ -36,12 +34,12 @@ const (
)
const (
// NodeRegisterEventReregistered is the message used when the node becomes
// reregistered.
// NodeRegisterEventRegistered is the message used when the node becomes
// registered.
NodeRegisterEventRegistered = "Node registered"
// NodeRegisterEventReregistered is the message used when the node becomes
// reregistered.
// re-registered.
NodeRegisterEventReregistered = "Node re-registered"
)
@ -63,7 +61,7 @@ type IndexEntry struct {
// StateStoreConfig is used to configure a new state store
type StateStoreConfig struct {
// Logger is used to output the state store's logs
Logger log.Logger
Logger hclog.Logger
// Region is the region of the server embedding the state store.
Region string
@ -83,7 +81,7 @@ type StateStoreConfig struct {
// returned as a result of a read against the state store should be
// considered a constant and NEVER modified in place.
type StateStore struct {
logger log.Logger
logger hclog.Logger
db *changeTrackerDB
// config is the passed in configuration
@ -4101,13 +4099,13 @@ func (s *StateStore) UpsertSITokenAccessors(index uint64, accessors []*structs.S
// insert the accessor
if err := txn.Insert(siTokenAccessorTable, accessor); err != nil {
return errors.Wrap(err, "accessor insert failed")
return fmt.Errorf("accessor insert failed: %w", err)
}
}
// update the index for this table
if err := txn.Insert("index", indexEntry(siTokenAccessorTable, index)); err != nil {
return errors.Wrap(err, "index update failed")
return fmt.Errorf("index update failed: %w", err)
}
return txn.Commit()
@ -4122,13 +4120,13 @@ func (s *StateStore) DeleteSITokenAccessors(index uint64, accessors []*structs.S
for _, accessor := range accessors {
// Delete the accessor
if err := txn.Delete(siTokenAccessorTable, accessor); err != nil {
return errors.Wrap(err, "accessor delete failed")
return fmt.Errorf("accessor delete failed: %w", err)
}
}
// update the index for this table
if err := txn.Insert("index", indexEntry(siTokenAccessorTable, index)); err != nil {
return errors.Wrap(err, "index update failed")
return fmt.Errorf("index update failed: %w", err)
}
return txn.Commit()
@ -4141,7 +4139,7 @@ func (s *StateStore) SITokenAccessor(ws memdb.WatchSet, accessorID string) (*str
watchCh, existing, err := txn.FirstWatch(siTokenAccessorTable, "id", accessorID)
if err != nil {
return nil, errors.Wrap(err, "accessor lookup failed")
return nil, fmt.Errorf("accessor lookup failed: %w", err)
}
ws.Add(watchCh)
@ -5896,7 +5894,7 @@ func (s *StateStore) ClusterMetadata(ws memdb.WatchSet) (*structs.ClusterMetadat
// Get the cluster metadata
watchCh, m, err := txn.FirstWatch("cluster_meta", "id")
if err != nil {
return nil, errors.Wrap(err, "failed cluster metadata lookup")
return nil, fmt.Errorf("failed cluster metadata lookup: %w", err)
}
ws.Add(watchCh)
@ -5912,7 +5910,7 @@ func (s *StateStore) ClusterSetMetadata(index uint64, meta *structs.ClusterMetad
defer txn.Abort()
if err := s.setClusterMetadata(txn, meta); err != nil {
return errors.Wrap(err, "set cluster metadata failed")
return fmt.Errorf("set cluster metadata failed: %w", err)
}
return txn.Commit()

View File

@ -4,7 +4,6 @@ import (
"fmt"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/pkg/errors"
)
// StateRestore is used to optimize the performance when restoring state by
@ -107,7 +106,7 @@ func (r *StateRestore) VaultAccessorRestore(accessor *structs.VaultAccessor) err
// SITokenAccessorRestore is used to restore an SI token accessor
func (r *StateRestore) SITokenAccessorRestore(accessor *structs.SITokenAccessor) error {
if err := r.txn.Insert(siTokenAccessorTable, accessor); err != nil {
return errors.Wrap(err, "si token accessor insert failed")
return fmt.Errorf("si token accessor insert failed: %w", err)
}
return nil
}

View File

@ -16,7 +16,6 @@ import (
"github.com/hashicorp/nomad/nomad/mock"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/hashicorp/nomad/version"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
@ -130,7 +129,7 @@ func TestServerErr(t *testing.T, cb func(*Config)) (*Server, func(), error) {
// Shutdown server
err := server.Shutdown()
if err != nil {
ch <- errors.Wrap(err, "failed to shutdown server")
ch <- fmt.Errorf("failed to shutdown server: %w", err)
}
freeport.Return(ports)