From 01ec43733baae9ca6f12474d5890391f17e5ecfc Mon Sep 17 00:00:00 2001 From: Eugen Sumin Date: Thu, 14 Nov 2024 11:10:12 +0100 Subject: [PATCH] Replace many minor usages of errors with errkit --- .../v1alpha1/repositoryserver_types_test.go | 4 +- pkg/apis/cr/v1alpha1/types_test.go | 4 +- pkg/aws/aws.go | 20 +++---- pkg/aws/ec2/ec2.go | 4 +- pkg/aws/rds/rds.go | 6 +-- pkg/aws/role/role.go | 4 +- pkg/blueprint/validate/validate.go | 12 ++--- pkg/chronicle/chronicle_pull.go | 4 +- pkg/chronicle/chronicle_push.go | 20 +++---- pkg/client/listers/cr/v1alpha1/actionset.go | 2 +- pkg/client/listers/cr/v1alpha1/blueprint.go | 2 +- pkg/client/listers/cr/v1alpha1/profile.go | 2 +- .../listers/cr/v1alpha1/repositoryserver.go | 2 +- pkg/controller/controller.go | 32 +++++------ pkg/controller/controller_test.go | 16 +++--- pkg/controllers/repositoryserver/handler.go | 22 ++++---- .../repositoryserver_controller.go | 6 +-- .../repositoryserver_controller_test.go | 10 ++-- .../repositoryserver/secrets_manager.go | 6 +-- pkg/controllers/repositoryserver/server.go | 28 +++++----- pkg/controllers/repositoryserver/utils.go | 18 +++---- pkg/customresource/customresource.go | 8 +-- pkg/customresource/watcher.go | 5 +- pkg/datamover/profile.go | 4 +- pkg/datamover/repository_server.go | 8 +-- pkg/datamover/utils.go | 8 +-- pkg/discovery/crd.go | 4 +- pkg/discovery/discovery.go | 11 ++-- pkg/envdir/envdir.go | 8 +-- pkg/errorchecker/errorchecker_test.go | 7 ++- pkg/handler/handler.go | 8 +-- pkg/kando/chronicle_pull.go | 4 +- pkg/kando/kando.go | 4 +- pkg/kando/location.go | 12 ++--- pkg/kando/output.go | 4 +- pkg/kanister.go | 6 +-- pkg/kopia/cli/errors.go | 18 +++---- pkg/kopia/cli/repository/opts.go | 5 +- pkg/kopia/errors/utils_test.go | 6 +-- pkg/kube/log_reader_test.go | 2 +- pkg/kube/pod.go | 1 - pkg/kube/pod_controller_test.go | 8 +-- pkg/kube/pod_runner_test.go | 6 +-- pkg/kube/pod_test.go | 6 +-- pkg/location/location.go | 13 ++--- pkg/log/fluentbit.go | 8 +-- pkg/log/log.go | 14 ++--- pkg/log/log_test.go | 4 +- pkg/metrics/metrics.go | 2 +- pkg/objectstore/bucket.go | 12 ++--- pkg/objectstore/directory.go | 20 +++---- pkg/objectstore/objectstore.go | 19 +++---- pkg/output/output.go | 10 ++-- pkg/param/param.go | 54 +++++++++---------- pkg/param/render.go | 10 ++-- pkg/phase.go | 25 ++++----- pkg/poll/poll.go | 6 +-- pkg/poll/poll_test.go | 2 +- pkg/progress/action.go | 6 +-- pkg/reconcile/reconcile.go | 6 +-- pkg/resource/resource.go | 6 +-- pkg/restic/restic.go | 26 ++++----- pkg/stream/stream.go | 10 ++-- pkg/testing/e2e_test.go | 14 ++--- pkg/testing/integration_test.go | 4 +- pkg/testutil/func.go | 4 +- .../mockblockstorage/mockblockstorage.go | 12 ++--- pkg/utils/utils.go | 10 ++-- pkg/validate/error.go | 12 ++--- pkg/validate/error_test.go | 12 ++--- .../repositoryserver_handler.go | 6 +-- pkg/virtualfs/directory.go | 18 +++---- pkg/virtualfs/file.go | 6 +-- pkg/virtualfs/virtualfs.go | 4 +- 74 files changed, 364 insertions(+), 368 deletions(-) diff --git a/pkg/apis/cr/v1alpha1/repositoryserver_types_test.go b/pkg/apis/cr/v1alpha1/repositoryserver_types_test.go index 0e051742f1..524d8328c5 100644 --- a/pkg/apis/cr/v1alpha1/repositoryserver_types_test.go +++ b/pkg/apis/cr/v1alpha1/repositoryserver_types_test.go @@ -17,7 +17,7 @@ package v1alpha1 import ( "testing" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" @@ -86,7 +86,7 @@ func getRepositoryServerFromSpec(spec []byte) (*RepositoryServer, error) { repositoryServer := &RepositoryServer{} d := serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer() if _, _, err := d.Decode([]byte(spec), nil, repositoryServer); err != nil { - return nil, errors.Wrap(err, "Failed to decode RepositoryServer") + return nil, errkit.Wrap(err, "Failed to decode RepositoryServer") } return repositoryServer, nil } diff --git a/pkg/apis/cr/v1alpha1/types_test.go b/pkg/apis/cr/v1alpha1/types_test.go index 6da1bc3d7d..6518183101 100644 --- a/pkg/apis/cr/v1alpha1/types_test.go +++ b/pkg/apis/cr/v1alpha1/types_test.go @@ -18,7 +18,7 @@ import ( "reflect" "testing" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" @@ -73,7 +73,7 @@ func getBlueprintFromSpec(spec []byte) (*Blueprint, error) { blueprint := &Blueprint{} d := serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer() if _, _, err := d.Decode([]byte(spec), nil, blueprint); err != nil { - return nil, errors.Wrap(err, "Failed to decode spec into object") + return nil, errkit.Wrap(err, "Failed to decode spec into object") } return blueprint, nil } diff --git a/pkg/aws/aws.go b/pkg/aws/aws.go index 65b1a824c5..a16d730d2a 100644 --- a/pkg/aws/aws.go +++ b/pkg/aws/aws.go @@ -24,7 +24,7 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sts" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" awsrole "github.com/kanisterio/kanister/pkg/aws/role" "github.com/kanisterio/kanister/pkg/field" @@ -111,7 +111,7 @@ func authenticateAWSCredentials( return creds, os.Getenv(RoleARNEnvKey), nil } - return nil, "", errors.New("Missing AWS credentials, please check that either AWS access keys or web identity token are provided") + return nil, "", errkit.New("Missing AWS credentials, please check that either AWS access keys or web identity token are provided") } func fetchStaticAWSCredentials(config map[string]string) *credentials.Credentials { @@ -171,14 +171,14 @@ func switchAWSRole(ctx context.Context, creds *credentials.Credentials, targetRo // If the caller wants to use a specific role, use the credentials initialized above to assume that // role and return those credentials instead creds, err := awsrole.Switch(ctx, creds, targetRole, assumeRoleDuration) - return creds, errors.Wrap(err, "Failed to switch roles") + return creds, errkit.Wrap(err, "Failed to switch roles") } // GetCredentials returns credentials to use for AWS operations func GetCredentials(ctx context.Context, config map[string]string) (*credentials.Credentials, error) { assumeRoleDuration, err := durationFromString(config) if err != nil { - return nil, errors.Wrap(err, "Failed to get assume role duration") + return nil, errkit.Wrap(err, "Failed to get assume role duration") } log.Debug().Print("Assume Role Duration setup", field.M{"assumeRoleDuration": assumeRoleDuration}) @@ -202,7 +202,7 @@ func getCredentialsWithDuration( ) (*credentials.Credentials, error) { sess, err := session.NewSessionWithOptions(session.Options{AssumeRoleDuration: duration}) if err != nil { - return nil, errors.Wrap(err, "Failed to create session to initialize Web Identify credentials") + return nil, errkit.Wrap(err, "Failed to create session to initialize Web Identify credentials") } svc := sts.New(sess) @@ -220,11 +220,11 @@ func getCredentialsWithDuration( func GetConfig(ctx context.Context, config map[string]string) (awsConfig *aws.Config, region string, err error) { region, ok := config[ConfigRegion] if !ok { - return nil, "", errors.New("region required for storage type EBS/EFS") + return nil, "", errkit.New("region required for storage type EBS/EFS") } creds, err := GetCredentials(ctx, config) if err != nil { - return nil, "", errors.Wrap(err, "could not initialize AWS credentials for operation") + return nil, "", errkit.Wrap(err, "could not initialize AWS credentials for operation") } return &aws.Config{Credentials: creds}, region, nil } @@ -233,16 +233,16 @@ func IsAwsCredsValid(ctx context.Context, config map[string]string) (bool, error var maxRetries int = 10 awsConfig, region, err := GetConfig(ctx, config) if err != nil { - return false, errors.Wrap(err, "Failed to get config for AWS creds") + return false, errkit.Wrap(err, "Failed to get config for AWS creds") } s, err := session.NewSession(awsConfig) if err != nil { - return false, errors.Wrap(err, "Failed to create session with provided creds") + return false, errkit.Wrap(err, "Failed to create session with provided creds") } stsCli := sts.New(s, aws.NewConfig().WithRegion(region).WithMaxRetries(maxRetries)) _, err = stsCli.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if err != nil { - return false, errors.Wrap(err, "Failed to get user with provided creds") + return false, errkit.Wrap(err, "Failed to get user with provided creds") } return true, nil } diff --git a/pkg/aws/ec2/ec2.go b/pkg/aws/ec2/ec2.go index 056bb09ffc..7b5e4ca7b3 100644 --- a/pkg/aws/ec2/ec2.go +++ b/pkg/aws/ec2/ec2.go @@ -20,7 +20,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) const ( @@ -37,7 +37,7 @@ type EC2 struct { func NewClient(ctx context.Context, awsConfig *aws.Config, region string) (*EC2, error) { s, err := session.NewSession(awsConfig) if err != nil { - return nil, errors.Wrap(err, "Failed to create session") + return nil, errkit.Wrap(err, "Failed to create session") } return &EC2{EC2: ec2.New(s, awsConfig.WithMaxRetries(maxRetries).WithRegion(region).WithCredentials(awsConfig.Credentials))}, nil } diff --git a/pkg/aws/rds/rds.go b/pkg/aws/rds/rds.go index 80b346f2df..a35ad2e4f7 100644 --- a/pkg/aws/rds/rds.go +++ b/pkg/aws/rds/rds.go @@ -23,7 +23,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/rds" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/poll" ) @@ -43,7 +43,7 @@ type RDS struct { func NewClient(ctx context.Context, awsConfig *aws.Config, region string) (*RDS, error) { s, err := session.NewSession(awsConfig) if err != nil { - return nil, errors.Wrap(err, "Failed to create session") + return nil, errkit.Wrap(err, "Failed to create session") } return &RDS{RDS: rds.New(s, awsConfig.WithMaxRetries(maxRetries).WithRegion(region).WithCredentials(awsConfig.Credentials))}, nil } @@ -143,7 +143,7 @@ func (r RDS) WaitOnDBCluster(ctx context.Context, dbClusterID, status string) er if *descCluster.DBClusters[0].Status == status { return nil } - return errors.New(fmt.Sprintf("DBCluster is not in %s state", status)) + return errkit.New(fmt.Sprintf("DBCluster is not in %s state", status)) } func (r RDS) WaitUntilDBClusterDeleted(ctx context.Context, dbClusterID string) error { diff --git a/pkg/aws/role/role.go b/pkg/aws/role/role.go index 20dc85c652..7efb989e6e 100644 --- a/pkg/aws/role/role.go +++ b/pkg/aws/role/role.go @@ -22,14 +22,14 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" "github.com/aws/aws-sdk-go/aws/session" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) // Switch func uses credentials API to automatically generates New Credentials for a given role. func Switch(ctx context.Context, creds *credentials.Credentials, role string, duration time.Duration) (*credentials.Credentials, error) { sess, err := session.NewSession(aws.NewConfig().WithCredentials((creds))) if err != nil { - return nil, errors.Wrap(err, "Failed to create session") + return nil, errkit.Wrap(err, "Failed to create session") } return stscreds.NewCredentials(sess, role, func(p *stscreds.AssumeRoleProvider) { p.Duration = duration diff --git a/pkg/blueprint/validate/validate.go b/pkg/blueprint/validate/validate.go index 1e4a79e469..5165193d3e 100644 --- a/pkg/blueprint/validate/validate.go +++ b/pkg/blueprint/validate/validate.go @@ -17,7 +17,7 @@ package validate import ( "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" kanister "github.com/kanisterio/kanister/pkg" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" @@ -40,20 +40,20 @@ func Do(bp *crv1alpha1.Blueprint, funcVersion string) error { phases, err := kanister.GetPhases(*bp, name, funcVersion, param.TemplateParams{}) if err != nil { utils.PrintStage(fmt.Sprintf("validation of action %s", name), utils.Fail) - return errors.Wrapf(err, "%s action %s", BPValidationErr, name) + return errkit.Wrap(err, fmt.Sprintf("%s action %s", BPValidationErr, name)) } // validate deferPhase's argument deferPhase, err := kanister.GetDeferPhase(*bp, name, funcVersion, param.TemplateParams{}) if err != nil { utils.PrintStage(fmt.Sprintf("validation of action %s", name), utils.Fail) - return errors.Wrapf(err, "%s action %s", BPValidationErr, name) + return errkit.Wrap(err, fmt.Sprintf("%s action %s", BPValidationErr, name)) } if deferPhase != nil { if err := deferPhase.Validate(action.DeferPhase.Args); err != nil { utils.PrintStage(fmt.Sprintf("validation of phase %s in action %s", deferPhase.Name(), name), utils.Fail) - return errors.Wrapf(err, "%s phase %s in action %s", BPValidationErr, deferPhase.Name(), name) + return errkit.Wrap(err, fmt.Sprintf("%s phase %s in action %s", BPValidationErr, deferPhase.Name(), name)) } utils.PrintStage(fmt.Sprintf("validation of phase %s in action %s", deferPhase.Name(), name), utils.Pass) } @@ -63,7 +63,7 @@ func Do(bp *crv1alpha1.Blueprint, funcVersion string) error { // validate function's mandatory arguments if err := phase.Validate(action.Phases[i].Args); err != nil { utils.PrintStage(fmt.Sprintf("validation of phase %s in action %s", phase.Name(), name), utils.Fail) - return errors.Wrapf(err, "%s phase %s in action %s", BPValidationErr, phase.Name(), name) + return errkit.Wrap(err, fmt.Sprintf("%s phase %s in action %s", BPValidationErr, phase.Name(), name)) } utils.PrintStage(fmt.Sprintf("validation of phase %s in action %s", phase.Name(), name), utils.Pass) } @@ -83,7 +83,7 @@ func validatePhaseNames(bp *crv1alpha1.Blueprint) error { for _, phase := range allPhases { if val := phasesCount[phase.Name]; val >= 1 { - return errors.New(fmt.Sprintf("%s: Duplicated phase name is not allowed. Violating phase '%s'", BPValidationErr, phase.Name)) + return errkit.New(fmt.Sprintf("%s: Duplicated phase name is not allowed. Violating phase '%s'", BPValidationErr, phase.Name)) } phasesCount[phase.Name] = 1 } diff --git a/pkg/chronicle/chronicle_pull.go b/pkg/chronicle/chronicle_pull.go index 0552c7efc8..504e970d45 100644 --- a/pkg/chronicle/chronicle_pull.go +++ b/pkg/chronicle/chronicle_pull.go @@ -19,7 +19,7 @@ import ( "context" "io" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/location" "github.com/kanisterio/kanister/pkg/param" @@ -32,7 +32,7 @@ func Pull(ctx context.Context, target io.Writer, p param.Profile, manifest strin // Read Data data, err := io.ReadAll(buf) if err != nil { - return errors.Wrap(err, "Could not read chronicle manifest") + return errkit.Wrap(err, "Could not read chronicle manifest") } return location.Read(ctx, target, p, string(data)) } diff --git a/pkg/chronicle/chronicle_push.go b/pkg/chronicle/chronicle_push.go index be7c4df5fe..7b56f90e32 100644 --- a/pkg/chronicle/chronicle_push.go +++ b/pkg/chronicle/chronicle_push.go @@ -25,7 +25,7 @@ import ( "syscall" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/envdir" "github.com/kanisterio/kanister/pkg/field" @@ -110,25 +110,25 @@ func pushWithEnv(ctx context.Context, c []string, suffix string, ord int, prof p cmd.Env = append(cmd.Env, env...) out, err := cmd.StdoutPipe() if err != nil { - return errors.Wrap(err, "Failed to open command pipe") + return errkit.Wrap(err, "Failed to open command pipe") } cmd.Stderr = os.Stderr cur := fmt.Sprintf("%s-%d", suffix, ord) // Write data to object store if err := cmd.Start(); err != nil { - return errors.Wrap(err, "Failed to start chronicle pipe command") + return errkit.Wrap(err, "Failed to start chronicle pipe command") } if err := location.Write(ctx, out, prof, cur); err != nil { - return errors.Wrap(err, "Failed to write command output to object storage") + return errkit.Wrap(err, "Failed to write command output to object storage") } if err := cmd.Wait(); err != nil { - return errors.Wrap(err, "Chronicle pipe command failed") + return errkit.Wrap(err, "Chronicle pipe command failed") } // Write manifest pointing to new data man := strings.NewReader(cur) if err := location.Write(ctx, man, prof, suffix); err != nil { - return errors.Wrap(err, "Failed to write command output to object storage") + return errkit.Wrap(err, "Failed to write command output to object storage") } // Delete old data prev := fmt.Sprintf("%s-%d", suffix, ord-1) @@ -139,7 +139,7 @@ func pushWithEnv(ctx context.Context, c []string, suffix string, ord int, prof p func readArtifactPathFile(path string) (string, error) { buf, err := os.ReadFile(path) t := strings.TrimSuffix(string(buf), "\n") - return t, errors.Wrap(err, "Could not read artifact path file") + return t, errkit.Wrap(err, "Could not read artifact path file") } func readProfile(path string) (param.Profile, bool, error) { @@ -151,10 +151,10 @@ func readProfile(path string) (param.Profile, bool, error) { err = nil return p, false, err case err != nil: - return p, false, errors.Wrap(err, "Failed to read profile") + return p, false, errkit.Wrap(err, "Failed to read profile") } if err = json.Unmarshal(buf, &p); err != nil { - return p, false, errors.Wrap(err, "Failed to unmarshal profile") + return p, false, errkit.Wrap(err, "Failed to unmarshal profile") } return p, true, nil } @@ -162,7 +162,7 @@ func readProfile(path string) (param.Profile, bool, error) { func writeProfile(path string, p param.Profile) error { buf, err := json.Marshal(p) if err != nil { - return errors.Wrap(err, "Failed to write profile") + return errkit.Wrap(err, "Failed to write profile") } return os.WriteFile(path, buf, os.ModePerm) } diff --git a/pkg/client/listers/cr/v1alpha1/actionset.go b/pkg/client/listers/cr/v1alpha1/actionset.go index 7f0ccf206b..08fb9d6d50 100644 --- a/pkg/client/listers/cr/v1alpha1/actionset.go +++ b/pkg/client/listers/cr/v1alpha1/actionset.go @@ -92,7 +92,7 @@ func (s actionSetNamespaceLister) Get(name string) (*v1alpha1.ActionSet, error) return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("actionset"), name) + return nil, errkit.NewNotFound(v1alpha1.Resource("actionset"), name) } return obj.(*v1alpha1.ActionSet), nil } diff --git a/pkg/client/listers/cr/v1alpha1/blueprint.go b/pkg/client/listers/cr/v1alpha1/blueprint.go index 01c14fe797..5296362d2c 100644 --- a/pkg/client/listers/cr/v1alpha1/blueprint.go +++ b/pkg/client/listers/cr/v1alpha1/blueprint.go @@ -92,7 +92,7 @@ func (s blueprintNamespaceLister) Get(name string) (*v1alpha1.Blueprint, error) return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("blueprint"), name) + return nil, errkit.NewNotFound(v1alpha1.Resource("blueprint"), name) } return obj.(*v1alpha1.Blueprint), nil } diff --git a/pkg/client/listers/cr/v1alpha1/profile.go b/pkg/client/listers/cr/v1alpha1/profile.go index a2efa08cc6..2aaac9f9a2 100644 --- a/pkg/client/listers/cr/v1alpha1/profile.go +++ b/pkg/client/listers/cr/v1alpha1/profile.go @@ -92,7 +92,7 @@ func (s profileNamespaceLister) Get(name string) (*v1alpha1.Profile, error) { return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("profile"), name) + return nil, errkit.NewNotFound(v1alpha1.Resource("profile"), name) } return obj.(*v1alpha1.Profile), nil } diff --git a/pkg/client/listers/cr/v1alpha1/repositoryserver.go b/pkg/client/listers/cr/v1alpha1/repositoryserver.go index 8545b73450..cc1b60bf4e 100644 --- a/pkg/client/listers/cr/v1alpha1/repositoryserver.go +++ b/pkg/client/listers/cr/v1alpha1/repositoryserver.go @@ -92,7 +92,7 @@ func (s repositoryServerNamespaceLister) Get(name string) (*v1alpha1.RepositoryS return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("repositoryserver"), name) + return nil, errkit.NewNotFound(v1alpha1.Resource("repositoryserver"), name) } return obj.(*v1alpha1.RepositoryServer), nil } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 4e3c7f69a0..315240fea5 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -28,7 +28,7 @@ import ( "sync" osversioned "github.com/openshift/client-go/apps/clientset/versioned" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/prometheus/client_golang/prometheus" "gopkg.in/tomb.v2" corev1 "k8s.io/api/core/v1" @@ -86,23 +86,23 @@ func New(c *rest.Config, reg prometheus.Registerer) *Controller { func (c *Controller) StartWatch(ctx context.Context, namespace string) error { crClient, err := versioned.NewForConfig(c.config) if err != nil { - return errors.Wrap(err, "failed to get a CustomResource client") + return errkit.Wrap(err, "failed to get a CustomResource client") } if err := checkCRAccess(ctx, crClient, namespace); err != nil { return err } clientset, err := kubernetes.NewForConfig(c.config) if err != nil { - return errors.Wrap(err, "failed to get a k8s client") + return errkit.Wrap(err, "failed to get a k8s client") } dynClient, err := dynamic.NewForConfig(c.config) if err != nil { - return errors.Wrap(err, "failed to get a k8s dynamic client") + return errkit.Wrap(err, "failed to get a k8s dynamic client") } osClient, err := osversioned.NewForConfig(c.config) if err != nil { - return errors.Wrap(err, "failed to get a openshift client") + return errkit.Wrap(err, "failed to get a openshift client") } c.crClient = crClient @@ -134,13 +134,13 @@ func (c *Controller) StartWatch(ctx context.Context, namespace string) error { func checkCRAccess(ctx context.Context, cli versioned.Interface, ns string) error { if _, err := cli.CrV1alpha1().ActionSets(ns).List(ctx, metav1.ListOptions{}); err != nil { - return errors.Wrap(err, "Could not list ActionSets") + return errkit.Wrap(err, "Could not list ActionSets") } if _, err := cli.CrV1alpha1().Blueprints(ns).List(ctx, metav1.ListOptions{}); err != nil { - return errors.Wrap(err, "Could not list Blueprints") + return errkit.Wrap(err, "Could not list Blueprints") } if _, err := cli.CrV1alpha1().Profiles(ns).List(ctx, metav1.ListOptions{}); err != nil { - return errors.Wrap(err, "Could not list Profiles") + return errkit.Wrap(err, "Could not list Profiles") } return nil } @@ -220,7 +220,7 @@ func (c *Controller) onAddActionSet(ctx context.Context, t *tomb.Tomb, as *crv1a } as, err := c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Get(ctx, as.GetName(), metav1.GetOptions{}) if err != nil { - return errors.WithStack(err) + return errkit.WithStack(err) } if err = validate.ActionSet(as); err != nil { return err @@ -313,13 +313,13 @@ func (c *Controller) initActionSetStatus(ctx context.Context, as *crv1alpha1.Act for _, a := range as.Spec.Actions { if a.Blueprint == "" { // TODO: If no blueprint is specified, we should consider a default. - err = errors.New("Blueprint is not specified for action") + err = errkit.New("Blueprint is not specified for action") c.logAndErrorEvent(ctx, "Could not get blueprint:", "Blueprint not specified", err, as) break } var bp *crv1alpha1.Blueprint if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, metav1.GetOptions{}); err != nil { - err = errors.Wrap(err, "Failed to query blueprint") + err = errkit.Wrap(err, "Failed to query blueprint") c.logAndErrorEvent(ctx, "Could not get blueprint:", "Error", err, as) break } @@ -349,7 +349,7 @@ func (c *Controller) initActionSetStatus(ctx context.Context, as *crv1alpha1.Act func (c *Controller) initialActionStatus(a crv1alpha1.ActionSpec, bp *crv1alpha1.Blueprint) (*crv1alpha1.ActionStatus, error) { bpa, ok := bp.Actions[a.Name] if !ok { - return nil, errors.Errorf("Action %s for object kind %s not found in blueprint %s", a.Name, a.Object.Kind, a.Blueprint) + return nil, errkit.New(fmt.Sprintf("Action %s for object kind %s not found in blueprint %s", a.Name, a.Object.Kind, a.Blueprint)) } phases := make([]crv1alpha1.Phase, 0, len(bpa.Phases)) for _, p := range bpa.Phases { @@ -379,14 +379,14 @@ func (c *Controller) initialActionStatus(a crv1alpha1.ActionSpec, bp *crv1alpha1 func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1alpha1.ActionSet) (err error) { if as.Status == nil { - return errors.New("ActionSet was not initialized") + return errkit.New("ActionSet was not initialized") } if as.Status.State != crv1alpha1.StatePending { return nil } as.Status.State = crv1alpha1.StateRunning if as, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, metav1.UpdateOptions{}); err != nil { - return errors.WithStack(err) + return errkit.WithStack(err) } ctx = field.Context(ctx, consts.ActionsetNameKey, as.GetName()) // adding labels with prefix "kanister.io/" in the context as field for better logging @@ -399,7 +399,7 @@ func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1 for i, a := range as.Status.Actions { var bp *crv1alpha1.Blueprint if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, metav1.GetOptions{}); err != nil { - err = errors.Wrap(err, "Failed to query blueprint") + err = errkit.Wrap(err, "Failed to query blueprint") c.logAndErrorEvent(ctx, "Could not get blueprint:", "Error", err, as) break } @@ -419,7 +419,7 @@ func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1 Message: err.Error(), } _, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, metav1.UpdateOptions{}) - return errors.WithStack(err) + return errkit.WithStack(err) } log.WithContext(ctx).Print("Created actionset and started executing actions", field.M{"NewActionSetName": as.GetName()}) return nil diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index 6f5b8604a0..f5b4210025 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -21,7 +21,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/prometheus/client_golang/prometheus" promgomodel "github.com/prometheus/client_model/go" "gopkg.in/check.v1" @@ -171,12 +171,12 @@ func (s *ControllerSuite) waitOnActionSetState(as *crv1alpha1.ActionSet, state c if as.Status.State == crv1alpha1.StatePending || as.Status.State == crv1alpha1.StateRunning { return false, nil } - return false, errors.New(fmt.Sprintf("Unexpected state: %s", as.Status.State)) + return false, errkit.New(fmt.Sprintf("Unexpected state: %s", as.Status.State)) }) if err == nil { return nil } - return errors.Wrapf(err, "State '%s' never reached", state) + return errkit.Wrap(err, fmt.Sprintf("State '%s' never reached", state)) } func (s *ControllerSuite) waitOnDeferPhaseState(as *crv1alpha1.ActionSet, state crv1alpha1.State) error { @@ -201,7 +201,7 @@ func (s *ControllerSuite) waitOnDeferPhaseState(as *crv1alpha1.ActionSet, state if err == nil { return nil } - return errors.Wrapf(err, "State '%s' never reached", state) + return errkit.Wrap(err, fmt.Sprintf("State '%s' never reached", state)) } func (s *ControllerSuite) waitOnActionSetCompleteWithRunningPhases(as *crv1alpha1.ActionSet, rp *sets.Set[string]) error { @@ -229,12 +229,12 @@ func (s *ControllerSuite) waitOnActionSetCompleteWithRunningPhases(as *crv1alpha } return false, nil } - return false, errors.New(fmt.Sprintf("Unexpected state: %s", as.Status.State)) + return false, errkit.New(fmt.Sprintf("Unexpected state: %s", as.Status.State)) }) if err == nil { return nil } - return errors.Wrapf(err, "ActionSet did not reach '%s' state", crv1alpha1.StateComplete) + return errkit.Wrap(err, fmt.Sprintf("ActionSet did not reach '%s' state", crv1alpha1.StateComplete)) } func newBPWithOutputArtifact() *crv1alpha1.Blueprint { @@ -731,7 +731,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *check.C) { config, err := kube.LoadConfig() c.Assert(err, check.IsNil) ctlr := New(config, nil) - ctlr.logAndErrorEvent(ctx, msg, reason, errors.New("Testing Event Logs"), as, nilAs, bp) + ctlr.logAndErrorEvent(ctx, msg, reason, errkit.New("Testing Event Logs"), as, nilAs, bp) // Test ActionSet error event logging events, err := s.cli.CoreV1().Events(as.Namespace).Search(scheme.Scheme, as) @@ -754,7 +754,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *check.C) { // Testing empty Blueprint testbp := &crv1alpha1.Blueprint{} - ctlr.logAndErrorEvent(ctx, msg, reason, errors.New("Testing Event Logs"), testbp) + ctlr.logAndErrorEvent(ctx, msg, reason, errkit.New("Testing Event Logs"), testbp) events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, testbp) c.Assert(err, check.NotNil) c.Assert(len(events.Items), check.Equals, 0) diff --git a/pkg/controllers/repositoryserver/handler.go b/pkg/controllers/repositoryserver/handler.go index 29677628de..d7325f0c27 100644 --- a/pkg/controllers/repositoryserver/handler.go +++ b/pkg/controllers/repositoryserver/handler.go @@ -22,7 +22,7 @@ import ( "github.com/go-logr/logr" "github.com/jpillora/backoff" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -50,20 +50,20 @@ type RepoServerHandler struct { func (h *RepoServerHandler) CreateOrUpdateOwnedResources(ctx context.Context) error { if err := h.getSecretsFromCR(ctx); err != nil { - return errors.Wrap(err, "Failed to get Kopia API server secrets") + return errkit.Wrap(err, "Failed to get Kopia API server secrets") } svc, err := h.reconcileService(ctx) if err != nil { - return errors.Wrap(err, "Failed to reconcile service") + return errkit.Wrap(err, "Failed to reconcile service") } envVars, pod, err := h.reconcilePod(ctx, svc) if err != nil { - return errors.Wrap(err, "Failed to reconcile Kopia API server pod") + return errkit.Wrap(err, "Failed to reconcile Kopia API server pod") } if err := h.waitForPodReady(ctx, pod); err != nil { - return errors.Wrap(err, "Kopia API server pod not in ready state") + return errkit.Wrap(err, "Kopia API server pod not in ready state") } // envVars are set only when credentials are of type AWS/Azure. @@ -95,7 +95,7 @@ func (h *RepoServerHandler) reconcileService(ctx context.Context) (*corev1.Servi return nil, err } if err := h.updateServerInfoInCRStatus(ctx, h.RepositoryServer.Status.ServerInfo.PodName, svc.Name); err != nil { - return nil, errors.Wrap(err, "Failed to update service name in RepositoryServer /status") + return nil, errkit.Wrap(err, "Failed to update service name in RepositoryServer /status") } return svc, err } @@ -131,7 +131,7 @@ func (h *RepoServerHandler) createService(ctx context.Context, repoServerNamespa } err := h.Reconciler.Create(ctx, &svc) if err != nil { - return nil, errors.Wrap(err, "Failed to create RepositoryServer service") + return nil, errkit.Wrap(err, "Failed to create RepositoryServer service") } err = poll.WaitWithBackoff(ctx, backoff.Backoff{ @@ -184,7 +184,7 @@ func (h *RepoServerHandler) createPodAndUpdateStatus(ctx context.Context, repoSe return nil, nil, err } if err := h.updateServerInfoInCRStatus(ctx, pod.Name, h.RepositoryServer.Status.ServerInfo.ServiceName); err != nil { - return nil, nil, errors.Wrap(err, "Failed to update pod name in RepositoryServer /status") + return nil, nil, errkit.Wrap(err, "Failed to update pod name in RepositoryServer /status") } return envVars, pod, nil } @@ -236,7 +236,7 @@ func (h *RepoServerHandler) createPod(ctx context.Context, repoServerNamespace s return nil, nil, err } if err := h.Reconciler.Create(ctx, pod); err != nil { - return nil, nil, errors.Wrap(err, "Failed to create RepositoryServer pod") + return nil, nil, errkit.Wrap(err, "Failed to create RepositoryServer pod") } return pod, envVars, err } @@ -284,7 +284,7 @@ func (h *RepoServerHandler) preparePodOverride(ctx context.Context, po *kube.Pod h.RepositoryServerSecrets.serverTLS.Name, po, ); err != nil { - return nil, errors.Wrap(err, "Failed to attach TLS Certificate configuration") + return nil, errkit.Wrap(err, "Failed to attach TLS Certificate configuration") } return podOverride, nil } @@ -315,7 +315,7 @@ func (h *RepoServerHandler) updateServerInfoInCRStatus(ctx context.Context, podN func (h *RepoServerHandler) waitForPodReady(ctx context.Context, pod *corev1.Pod) error { if err := kube.WaitForPodReady(ctx, h.KubeCli, pod.Namespace, pod.Name); err != nil { - return errors.Wrap(err, fmt.Sprintf("Failed while waiting for pod %s to be ready", pod.Name)) + return errkit.Wrap(err, fmt.Sprintf("Failed while waiting for pod %s to be ready", pod.Name)) } return nil } diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller.go b/pkg/controllers/repositoryserver/repositoryserver_controller.go index 8616921b95..7e52febac0 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller.go @@ -18,7 +18,7 @@ import ( "context" "github.com/go-logr/logr" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -69,11 +69,11 @@ func (r *RepositoryServerReconciler) Reconcile(ctx context.Context, req ctrl.Req logger = logger.V(1) cnf, err := ctrl.GetConfig() if err != nil { - return ctrl.Result{}, errors.Wrap(err, "Failed to get k8s config") + return ctrl.Result{}, errkit.Wrap(err, "Failed to get k8s config") } kubeCli, err := kubernetes.NewForConfig(cnf) if err != nil { - return ctrl.Result{}, errors.Wrap(err, "Failed to get a k8s client") + return ctrl.Result{}, errkit.Wrap(err, "Failed to get a k8s client") } repositoryServer := &crv1alpha1.RepositoryServer{} diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index 90b6e9f5fa..b84557e468 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -23,7 +23,7 @@ import ( "testing" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" corev1 "k8s.io/api/core/v1" k8sresource "k8s.io/apimachinery/pkg/api/resource" @@ -477,11 +477,11 @@ func (s *RepoServerControllerSuite) waitForRepoServerInfoUpdateInCR(repoServerNa }) if !serverInfoUpdated && err == nil { - err = errors.New("pod name or service name is not set on repository server CR") + err = errkit.New("pod name or service name is not set on repository server CR") } if err != nil { - return errors.Wrapf(err, "failed waiting for RepoServer Info updates in the CR") + return errkit.Wrap(err, "failed waiting for RepoServer Info updates in the CR") } return err } @@ -502,12 +502,12 @@ func (s *RepoServerControllerSuite) waitOnRepositoryServerState(reposerverName s return false, nil } if repoServerCR.Status.Progress == crv1alpha1.Failed { - return false, errors.New(fmt.Sprintf(" There is failure in staring the repository server, server is in %s state, please check logs", repoServerCR.Status.Progress)) + return false, errkit.New(fmt.Sprintf("There is failure in staring the repository server, server is in %s state, please check logs", repoServerCR.Status.Progress)) } if repoServerCR.Status.Progress == crv1alpha1.Ready { return true, nil } - return false, errors.New(fmt.Sprintf("Unexpected Repository server state: %s", repoServerCR.Status.Progress)) + return false, errkit.New(fmt.Sprintf("Unexpected Repository server state: %s", repoServerCR.Status.Progress)) }) return repoServerState, err } diff --git a/pkg/controllers/repositoryserver/secrets_manager.go b/pkg/controllers/repositoryserver/secrets_manager.go index 9272eeafb3..fb66923ea2 100644 --- a/pkg/controllers/repositoryserver/secrets_manager.go +++ b/pkg/controllers/repositoryserver/secrets_manager.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" ) @@ -76,14 +76,14 @@ func (h *RepoServerHandler) getSecretsFromCR(ctx context.Context) error { func (h *RepoServerHandler) fetchSecret(ctx context.Context, ref *corev1.SecretReference) (*corev1.Secret, error) { if ref == nil { - return nil, errors.New("repository server CR does not have a secret reference set") + return nil, errkit.New("repository server CR does not have a secret reference set") } h.Logger.Info(fmt.Sprintf("Fetching secret %s from namespace %s", ref.Name, ref.Namespace)) secret := corev1.Secret{} err := h.Reconciler.Get(ctx, types.NamespacedName{Name: ref.Name, Namespace: ref.Namespace}, &secret) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("Error fetching secret %s from namespace %s", ref.Name, ref.Namespace)) + return nil, errkit.Wrap(err, fmt.Sprintf("Error fetching secret %s from namespace %s", ref.Name, ref.Namespace)) } return &secret, nil } diff --git a/pkg/controllers/repositoryserver/server.go b/pkg/controllers/repositoryserver/server.go index 16ce3d4a08..9d03c0ea33 100644 --- a/pkg/controllers/repositoryserver/server.go +++ b/pkg/controllers/repositoryserver/server.go @@ -21,7 +21,7 @@ import ( "os" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "k8s.io/kube-openapi/pkg/util/sets" "github.com/kanisterio/kanister/pkg/format" @@ -69,12 +69,12 @@ func (h *RepoServerHandler) startRepoProxyServer(ctx context.Context) (err error format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stderr) if err != nil { - return errors.Wrap(err, "Failed to start Kopia API server") + return errkit.Wrap(err, "Failed to start Kopia API server") } err = h.waitForServerReady(ctx, repoServerAddress, serverAdminUserName, serverAdminPassword) if err != nil { - return errors.Wrap(err, "Failed to check Kopia API server status") + return errkit.Wrap(err, "Failed to check Kopia API server status") } return nil } @@ -87,10 +87,10 @@ func (h *RepoServerHandler) getServerDetails(ctx context.Context) (string, strin var serverAdminUsername, serverAdminPassword []byte var ok bool if serverAdminUsername, ok = h.RepositoryServerSecrets.serverAdmin.Data[reposerver.AdminUsernameKey]; !ok { - return "", "", "", errors.New("Server admin username is not specified") + return "", "", "", errkit.New("Server admin username is not specified") } if serverAdminPassword, ok = h.RepositoryServerSecrets.serverAdmin.Data[reposerver.AdminPasswordKey]; !ok { - return "", "", "", errors.New("Server admin password is not specified") + return "", "", "", errkit.New("Server admin password is not specified") } return repoServerAddress, string(serverAdminUsername), string(serverAdminPassword), nil } @@ -98,7 +98,7 @@ func (h *RepoServerHandler) getServerDetails(ctx context.Context) (string, strin func (h *RepoServerHandler) checkServerStatus(ctx context.Context, serverAddress, username, password string) error { cmd, err := h.getServerStatusCommand(ctx, serverAddress, username, password) if err != nil { - return errors.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") + return errkit.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") } stdout, stderr, exErr := kube.Exec(ctx, h.KubeCli, h.RepositoryServer.Namespace, h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, cmd, nil) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) @@ -109,7 +109,7 @@ func (h *RepoServerHandler) checkServerStatus(ctx context.Context, serverAddress func (h *RepoServerHandler) waitForServerReady(ctx context.Context, serverAddress, username, password string) error { cmd, err := h.getServerStatusCommand(ctx, serverAddress, username, password) if err != nil { - return errors.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") + return errkit.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") } serverStartTimeOut := h.getRepositoryServerStartTimeout() ctx, cancel := context.WithTimeout(ctx, serverStartTimeOut) @@ -132,14 +132,14 @@ func (h *RepoServerHandler) createOrUpdateClientUsers(ctx context.Context) error format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stderr) if err != nil { - return errors.Wrap(err, "Failed to list users from the Kopia repository") + return errkit.Wrap(err, "Failed to list users from the Kopia repository") } userProfiles := []maintenance.KopiaUserProfile{} err = json.Unmarshal([]byte(stdout), &userProfiles) if err != nil { - return errors.Wrap(err, "Failed to unmarshal user list") + return errkit.Wrap(err, "Failed to unmarshal user list") } // Get list of usernames from ServerListUserCommand output to update the existing data with updated password @@ -169,7 +169,7 @@ func (h *RepoServerHandler) createOrUpdateClientUsers(ctx context.Context) error format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stderr) if err != nil { - return errors.Wrap(err, "Failed to update existing user passphrase from the Kopia API server") + return errkit.Wrap(err, "Failed to update existing user passphrase from the Kopia API server") } continue } @@ -187,7 +187,7 @@ func (h *RepoServerHandler) createOrUpdateClientUsers(ctx context.Context) error format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stderr) if err != nil { - return errors.Wrap(err, "Failed to add new user to the Kopia API server") + return errkit.Wrap(err, "Failed to add new user to the Kopia API server") } } return nil @@ -201,7 +201,7 @@ func (h *RepoServerHandler) refreshServer(ctx context.Context) error { repoPassword := string(h.RepositoryServerSecrets.repositoryPassword.Data[reposerver.RepoPasswordKey]) fingerprint, err := kopia.ExtractFingerprintFromCertSecret(ctx, h.KubeCli, h.RepositoryServerSecrets.serverTLS.Name, h.RepositoryServer.Namespace) if err != nil { - return errors.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") + return errkit.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") } cmd := command.ServerRefresh( @@ -220,7 +220,7 @@ func (h *RepoServerHandler) refreshServer(ctx context.Context) error { format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stdout) format.Log(h.RepositoryServer.Status.ServerInfo.PodName, repoServerPodContainerName, stderr) if err != nil { - return errors.Wrap(err, "Failed to refresh Kopia API server") + return errkit.Wrap(err, "Failed to refresh Kopia API server") } return nil } @@ -241,7 +241,7 @@ func (h *RepoServerHandler) getRepositoryServerStartTimeout() time.Duration { func (h *RepoServerHandler) getServerStatusCommand(ctx context.Context, serverAddress, username, password string) ([]string, error) { fingerprint, err := kopia.ExtractFingerprintFromCertSecret(ctx, h.KubeCli, h.RepositoryServerSecrets.serverTLS.Name, h.RepositoryServer.Namespace) if err != nil { - return nil, errors.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") + return nil, errkit.Wrap(err, "Failed to extract fingerprint from Kopia API server certificate secret data") } cmd := command.ServerStatus( command.ServerStatusCommandArgs{ diff --git a/pkg/controllers/repositoryserver/utils.go b/pkg/controllers/repositoryserver/utils.go index 928dc984bb..0fdcd5af69 100644 --- a/pkg/controllers/repositoryserver/utils.go +++ b/pkg/controllers/repositoryserver/utils.go @@ -22,7 +22,7 @@ import ( "time" "github.com/jpillora/backoff" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -164,12 +164,12 @@ func volumeSpecForName(podSpec corev1.PodSpec, podOverride map[string]interface{ func addTLSCertConfigurationInPodOverride(podOverride *map[string]interface{}, tlsCertSecretName string, po *kube.PodOptions) error { podSpecBytes, err := json.Marshal(*podOverride) if err != nil { - return errors.Wrap(err, "Failed to marshal Pod Override") + return errkit.Wrap(err, "Failed to marshal Pod Override") } var podOverrideSpec corev1.PodSpec if err := json.Unmarshal(podSpecBytes, &podOverrideSpec); err != nil { - return errors.Wrap(err, "Failed to unmarshal Pod Override Spec") + return errkit.Wrap(err, "Failed to unmarshal Pod Override Spec") } podOverrideSpec.Volumes = append(podOverrideSpec.Volumes, corev1.Volume{ @@ -199,11 +199,11 @@ func addTLSCertConfigurationInPodOverride(podOverride *map[string]interface{}, t podSpecBytes, err = json.Marshal(podOverrideSpec) if err != nil { - return errors.Wrap(err, "Failed to marshal Pod Override Spec") + return errkit.Wrap(err, "Failed to marshal Pod Override Spec") } if err := json.Unmarshal(podSpecBytes, podOverride); err != nil { - return errors.Wrap(err, "Failed to unmarshal Pod Override") + return errkit.Wrap(err, "Failed to unmarshal Pod Override") } return nil @@ -235,7 +235,7 @@ func getPodOptions(namespace string, svc *corev1.Service, vols map[string]kube.V func getPodAddress(ctx context.Context, cli kubernetes.Interface, namespace, podName string) (string, error) { p, err := cli.CoreV1().Pods(namespace).Get(ctx, podName, metav1.GetOptions{}) if err != nil { - return "", errors.Wrap(err, "Failed to get pod") + return "", errkit.Wrap(err, "Failed to get pod") } return fmt.Sprintf(repoServerAddressFormat, p.Status.PodIP, repoServerServicePort), nil } @@ -277,17 +277,17 @@ func getVolumes( vols := make(map[string]kube.VolumeMountOptions, 0) var claimName []byte if len(secret.Data) == 0 { - return nil, errors.Errorf(secerrors.EmptySecretErrorMessage, secret.Namespace, secret.Name) + return nil, errkit.New(fmt.Sprintf(secerrors.EmptySecretErrorMessage, secret.Namespace, secret.Name)) } if locationType, ok := (secret.Data[reposerver.TypeKey]); ok && reposerver.LocType(string(locationType)) == reposerver.LocTypeFilestore { if claimName, ok = secret.Data[reposerver.ClaimNameKey]; !ok { - return nil, errors.New("Claim name not set for file store location secret, failed to retrieve PVC") + return nil, errkit.New("Claim name not set for file store location secret, failed to retrieve PVC") } claimNameString := string(claimName) pvc, err := cli.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, claimNameString, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrapf(err, "Failed to validate if PVC %s:%s exists", namespace, claimName) + return nil, errkit.Wrap(err, "Failed to validate if PVC exists", "namespace", namespace, "claimName", claimName) } vols[claimNameString] = kube.VolumeMountOptions{ diff --git a/pkg/customresource/customresource.go b/pkg/customresource/customresource.go index 71e66731d9..0d80644b3b 100644 --- a/pkg/customresource/customresource.go +++ b/pkg/customresource/customresource.go @@ -21,7 +21,7 @@ import ( "time" "github.com/Masterminds/semver" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -116,18 +116,18 @@ func decodeSpecIntoObject(spec []byte, intoObj runtime.Object) error { func createCRD(context Context, resource CustomResource) error { c, err := rawCRDFromFile(fmt.Sprintf("%s.yaml", resource.Name)) if err != nil { - return errors.Wrap(err, "Getting raw CRD from CRD manifests") + return errkit.Wrap(err, "Getting raw CRD from CRD manifests") } crd, err := getCRDFromSpec(c) if err != nil { - return errors.Wrap(err, "Getting CRD object from CRD bytes") + return errkit.Wrap(err, "Getting CRD object from CRD bytes") } _, err = context.APIExtensionClientset.ApiextensionsV1().CustomResourceDefinitions().Create(context.Context, crd, metav1.CreateOptions{}) if err != nil { if !apierrors.IsAlreadyExists(err) { - return errors.Errorf("Failed to create %s CRD. %+v", resource.Name, err) + return errkit.New(fmt.Sprintf("Failed to create %s CRD. %+v", resource.Name, err)) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { diff --git a/pkg/customresource/watcher.go b/pkg/customresource/watcher.go index 09239aa06a..b057a7ef2e 100644 --- a/pkg/customresource/watcher.go +++ b/pkg/customresource/watcher.go @@ -16,8 +16,7 @@ package customresource import ( - "errors" - + "github.com/kanisterio/errkit" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" @@ -26,7 +25,7 @@ import ( var ( // ErrVersionOutdated indicates that the custom resource is outdated and needs to be refreshed - ErrVersionOutdated = errors.New("requested version is outdated in apiserver") + ErrVersionOutdated = errkit.NewSentinelErr("requested version is outdated in apiserver") ) // ResourceWatcher watches a custom resource for desired state diff --git a/pkg/datamover/profile.go b/pkg/datamover/profile.go index 33f4916ea5..eefd40f7fe 100644 --- a/pkg/datamover/profile.go +++ b/pkg/datamover/profile.go @@ -17,7 +17,7 @@ package datamover import ( "context" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/kopia" @@ -100,7 +100,7 @@ func (p *profile) connectToKopiaRepositoryServer(ctx context.Context, accessMode func (p *profile) unmarshalKopiaSnapshot(ctx context.Context) (*snapshot.SnapshotInfo, error) { if p.snapJSON == "" { - return nil, errors.New("kopia snapshot information is required to manage data using kopia") + return nil, errkit.New("kopia snapshot information is required to manage data using kopia") } kopiaSnap, err := snapshot.UnmarshalKopiaSnapshot(p.snapJSON) if err != nil { diff --git a/pkg/datamover/repository_server.go b/pkg/datamover/repository_server.go index d3e4f1695d..51e23741cc 100644 --- a/pkg/datamover/repository_server.go +++ b/pkg/datamover/repository_server.go @@ -17,7 +17,7 @@ package datamover import ( "context" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/kopia" "github.com/kanisterio/kanister/pkg/kopia/repository" @@ -71,7 +71,7 @@ func (rs *repositoryServer) Delete(ctx context.Context, destinationPath string) func (rs *repositoryServer) connectToKopiaRepositoryServer(ctx context.Context, accessMode repository.AccessMode) (string, error) { hostname, userPassphrase, err := rs.hostnameAndUserPassphrase() if err != nil { - return "", errors.Wrap(err, "Error Retrieving Hostname and User Passphrase from Repository Server") + return "", errkit.Wrap(err, "Error Retrieving Hostname and User Passphrase from Repository Server") } return userPassphrase, repository.ConnectToAPIServer( @@ -89,7 +89,7 @@ func (rs *repositoryServer) connectToKopiaRepositoryServer(ctx context.Context, func (rs *repositoryServer) unmarshalKopiaSnapshot() (*snapshot.SnapshotInfo, error) { if rs.snapJSON == "" { - return nil, errors.New("kopia snapshot information is required to manage data using kopia") + return nil, errkit.New("kopia snapshot information is required to manage data using kopia") } kopiaSnap, err := snapshot.UnmarshalKopiaSnapshot(rs.snapJSON) if err != nil { @@ -127,7 +127,7 @@ func (rs *repositoryServer) hostnameAndUserPassphrase() (string, string, error) func (rs *repositoryServer) checkHostnameExistsInUserAccessMap(userAccessMap map[string]string) error { // check if hostname is provided in the repository server exists in the user access map if _, ok := userAccessMap[rs.hostName]; !ok { - return errors.New("hostname provided in the repository server does not exist in the user access map") + return errkit.New("hostname provided in the repository server does not exist in the user access map") } return nil } diff --git a/pkg/datamover/utils.go b/pkg/datamover/utils.go index 0f19fe4f99..46dd270f6d 100644 --- a/pkg/datamover/utils.go +++ b/pkg/datamover/utils.go @@ -19,7 +19,7 @@ import ( "io" "os" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/kopia/snapshot" "github.com/kanisterio/kanister/pkg/location" @@ -63,7 +63,7 @@ func kopiaLocationPush(ctx context.Context, path, outputName, sourcePath, passwo snapInfo, err = snapshot.WriteFile(ctx, path, sourcePath, password) } if err != nil { - return nil, errors.Wrap(err, "Failed to push data using kopia") + return nil, errkit.Wrap(err, "Failed to push data using kopia") } snapInfoJSON, err := snapshot.MarshalKopiaSnapshot(snapInfo) if err != nil { @@ -79,10 +79,10 @@ func sourceReader(source string) (io.Reader, error) { } fi, err := os.Stdin.Stat() if err != nil { - return nil, errors.Wrap(err, "failed to describe file stdin") + return nil, errkit.Wrap(err, "failed to describe file stdin") } if fi.Mode()&os.ModeNamedPipe == 0 { - return nil, errors.New("Stdin must be piped when the source parameter is \"-\"") + return nil, errkit.New("Stdin must be piped when the source parameter is \"-\"") } return os.Stdin, nil } diff --git a/pkg/discovery/crd.go b/pkg/discovery/crd.go index 592063e969..d25da3e2b3 100644 --- a/pkg/discovery/crd.go +++ b/pkg/discovery/crd.go @@ -17,7 +17,7 @@ package discovery import ( "context" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" crdclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -29,7 +29,7 @@ import ( func CRDMatcher(ctx context.Context, cli crdclient.Interface) (filter.ResourceTypeMatcher, error) { crds, err := cli.ApiextensionsV1().CustomResourceDefinitions().List(ctx, metav1.ListOptions{}) if err != nil { - return nil, errors.Wrap(err, "Failed to query CRDs in cluster") + return nil, errkit.Wrap(err, "Failed to query CRDs in cluster") } return crdsToMatcher(crds.Items), nil } diff --git a/pkg/discovery/discovery.go b/pkg/discovery/discovery.go index a7d4b5bb06..f259dc040c 100644 --- a/pkg/discovery/discovery.go +++ b/pkg/discovery/discovery.go @@ -16,8 +16,9 @@ package discovery import ( "context" + "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/discovery" @@ -28,7 +29,7 @@ import ( func AllGVRs(ctx context.Context, cli discovery.DiscoveryInterface) ([]schema.GroupVersionResource, error) { arls, err := cli.ServerPreferredResources() if err != nil { - return nil, errors.Wrap(err, "Failed to list APIResources") + return nil, errkit.Wrap(err, "Failed to list APIResources") } return apiToGroupVersion(arls) } @@ -36,7 +37,7 @@ func AllGVRs(ctx context.Context, cli discovery.DiscoveryInterface) ([]schema.Gr func NamespacedGVRs(ctx context.Context, cli discovery.DiscoveryInterface) ([]schema.GroupVersionResource, error) { arls, err := cli.ServerPreferredNamespacedResources() if err != nil { - return nil, errors.Wrap(err, "Failed to list APIResources") + return nil, errkit.Wrap(err, "Failed to list APIResources") } return apiToGroupVersion(arls) } @@ -62,7 +63,7 @@ func ignoreGroupErrs(exclude filter.ResourceTypeMatcher, arls []*metav1.APIResou for k := range out.Groups { gvr := schema.GroupVersionResource{Group: k.Group, Version: k.Version, Resource: ""} if !exclude.Any(gvr) { - return nil, errors.Wrap(err, "Failed to list APIResources") + return nil, errkit.Wrap(err, "Failed to list APIResources") } } return apiToGroupVersion(arls) @@ -73,7 +74,7 @@ func apiToGroupVersion(arls []*metav1.APIResourceList) ([]schema.GroupVersionRes for _, arl := range arls { gv, err := schema.ParseGroupVersion(arl.GroupVersion) if err != nil { - return nil, errors.Wrapf(err, "Failed to Parse GroupVersion %s", arl.GroupVersion) + return nil, errkit.Wrap(err, fmt.Sprintf("Failed to Parse GroupVersion %s", arl.GroupVersion)) } for _, ar := range arl.APIResources { // Although APIResources have Group and Version fields they're empty as of client-go v1.13.1 diff --git a/pkg/envdir/envdir.go b/pkg/envdir/envdir.go index 496db8fc1e..b3311a9d0c 100644 --- a/pkg/envdir/envdir.go +++ b/pkg/envdir/envdir.go @@ -20,7 +20,7 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) func EnvDir(dir string) ([]string, error) { @@ -30,7 +30,7 @@ func EnvDir(dir string) ([]string, error) { } entries, err := os.ReadDir(dir) if err != nil { - return nil, errors.Wrap(err, "failed to read env from dir:"+dir) + return nil, errkit.Wrap(err, "failed to read env from dir:"+dir) } e := make([]string, 0, len(entries)) for _, entry := range entries { @@ -40,11 +40,11 @@ func EnvDir(dir string) ([]string, error) { p := filepath.Join(dir, entry.Name()) f, err := os.Open(p) if err != nil { - return nil, errors.Wrap(err, "failed to read env from dir:"+dir) + return nil, errkit.Wrap(err, "failed to read env from dir:"+dir) } c, err := io.ReadAll(f) if err != nil { - return nil, errors.Wrap(err, "failed to read env from dir:"+dir) + return nil, errkit.Wrap(err, "failed to read env from dir:"+dir) } e = append(e, fmt.Sprintf("%s=%s", entry.Name(), c)) } diff --git a/pkg/errorchecker/errorchecker_test.go b/pkg/errorchecker/errorchecker_test.go index 3a12e5a5ef..f8466a3c14 100644 --- a/pkg/errorchecker/errorchecker_test.go +++ b/pkg/errorchecker/errorchecker_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/kanisterio/errkit" - "github.com/pkg/errors" "gopkg.in/check.v1" ) @@ -18,11 +17,11 @@ var _ = check.Suite(&ErrorsTestSuite{}) func (ts *ErrorsTestSuite) TestWrappingAndMatching(c *check.C) { errkitErr := errkit.New("Errkit error") errkitWrappedErr := errkit.Wrap(errkitErr, "errkit wrapped") - errorsWrappedErr := errors.Wrap(errkitWrappedErr, "errors wrapped") - errorsWrappedErr1 := errors.Wrap(errorsWrappedErr, "errors wrapped 1") + errorsWrappedErr := errkit.Wrap(errkitWrappedErr, "errors wrapped") + errorsWrappedErr1 := errkit.Wrap(errorsWrappedErr, "errors wrapped 1") // Ensure that errors from 'errkit' wrapped by the older 'errors' package remain matchable. - c.Assert(errors.Is(errorsWrappedErr, errkitErr), check.Equals, true) + c.Assert(errkit.Is(errorsWrappedErr, errkitErr), check.Equals, true) // Ensure that transformation to string still works c.Assert(errorsWrappedErr1.Error(), check.Equals, "errors wrapped 1: errors wrapped: errkit wrapped: Errkit error") // Ensure that error message matching does work as expected diff --git a/pkg/handler/handler.go b/pkg/handler/handler.go index 97262460f3..f4bfd90fd9 100644 --- a/pkg/handler/handler.go +++ b/pkg/handler/handler.go @@ -20,7 +20,7 @@ import ( "net/http" "github.com/go-logr/logr" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/prometheus/client_golang/prometheus/promhttp" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/log" @@ -68,12 +68,12 @@ func RunWebhookServer(c *rest.Config) error { log.SetLogger(logr.New(log.NullLogSink{})) mgr, err := manager.New(c, manager.Options{}) if err != nil { - return errors.Wrap(err, "Failed to create new webhook manager") + return errkit.Wrap(err, "Failed to create new webhook manager") } bpValidator := &validatingwebhook.BlueprintValidator{} decoder := admission.NewDecoder(mgr.GetScheme()) if err = bpValidator.InjectDecoder(&decoder); err != nil { - return errors.Wrap(err, "Failed to inject decoder") + return errkit.Wrap(err, "Failed to inject decoder") } hookServerOptions := webhook.Options{CertDir: validatingwebhook.WHCertsDir} @@ -83,7 +83,7 @@ func RunWebhookServer(c *rest.Config) error { hookServer.Register(metricsPath, promhttp.Handler()) if err := mgr.Add(hookServer); err != nil { - return errors.Wrap(err, "Failed to add new webhook server") + return errkit.Wrap(err, "Failed to add new webhook server") } if err := mgr.Start(signals.SetupSignalHandler()); err != nil { diff --git a/pkg/kando/chronicle_pull.go b/pkg/kando/chronicle_pull.go index 941ee4b335..a61866f449 100644 --- a/pkg/kando/chronicle_pull.go +++ b/pkg/kando/chronicle_pull.go @@ -20,7 +20,7 @@ import ( "io" "os" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/spf13/cobra" "github.com/kanisterio/kanister/pkg/chronicle" @@ -51,7 +51,7 @@ type locationParams struct { func unmarshalProfile(prof string) (*param.Profile, error) { p := ¶m.Profile{} err := json.Unmarshal([]byte(prof), p) - return p, errors.Wrap(err, "failed to unmarshal profile") + return p, errkit.Wrap(err, "failed to unmarshal profile") } //nolint:unparam diff --git a/pkg/kando/kando.go b/pkg/kando/kando.go index b02ebb8d0e..cc6f2b257c 100644 --- a/pkg/kando/kando.go +++ b/pkg/kando/kando.go @@ -17,7 +17,7 @@ package kando import ( "os" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -60,7 +60,7 @@ func newRootCommand() *cobra.Command { func setLogLevel(v string) error { l, err := logrus.ParseLevel(v) if err != nil { - return errors.Wrap(err, "Invalid log level: "+v) + return errkit.Wrap(err, "Invalid log level: "+v) } logrus.SetLevel(l) return nil diff --git a/pkg/kando/location.go b/pkg/kando/location.go index f6c4e16f75..603c36672a 100644 --- a/pkg/kando/location.go +++ b/pkg/kando/location.go @@ -17,7 +17,7 @@ package kando import ( "encoding/json" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/spf13/cobra" "github.com/kanisterio/kanister/pkg/datamover" @@ -63,10 +63,10 @@ func validateCommandArgs(cmd *cobra.Command) error { profileFlag := cmd.Flags().Lookup(profileFlagName).Value.String() repositoryServerFlag := cmd.Flags().Lookup(repositoryServerFlagName).Value.String() if profileFlag != "" && repositoryServerFlag != "" { - return errors.New("Either --profile or --repository-server should be provided") + return errkit.New("Either --profile or --repository-server should be provided") } if profileFlag == "" && repositoryServerFlag == "" { - return errors.New("Please provide either --profile or --repository-server as per the datamover you want to use") + return errkit.New("Please provide either --profile or --repository-server as per the datamover you want to use") } return nil } @@ -96,7 +96,7 @@ func dataMoverFromCMD(cmd *cobra.Command, kopiaSnapshot, outputName string) (dat } return datamover.NewRepositoryServerDataMover(repositoryServerRef, outputName, kopiaSnapshot, cmd.Flag(repositoryServerUserHostnameFlagName).Value.String()), nil default: - return nil, errors.New("Could not initialize DataMover.") + return nil, errkit.New("Could not initialize DataMover.") } } @@ -104,14 +104,14 @@ func unmarshalProfileFlag(cmd *cobra.Command) (*param.Profile, error) { profileJSON := cmd.Flag(profileFlagName).Value.String() p := ¶m.Profile{} err := json.Unmarshal([]byte(profileJSON), p) - return p, errors.Wrap(err, "failed to unmarshal profile") + return p, errkit.Wrap(err, "failed to unmarshal profile") } func unmarshalRepositoryServerFlag(cmd *cobra.Command) (*param.RepositoryServer, error) { repositoryServerJSON := cmd.Flag(repositoryServerFlagName).Value.String() rs := ¶m.RepositoryServer{} err := json.Unmarshal([]byte(repositoryServerJSON), rs) - return rs, errors.Wrap(err, "failed to unmarshal kopia repository server CR") + return rs, errkit.Wrap(err, "failed to unmarshal kopia repository server CR") } func dataMoverTypeFromCMD(c *cobra.Command) DataMoverType { diff --git a/pkg/kando/output.go b/pkg/kando/output.go index 3c8e092da5..6c12c88abd 100644 --- a/pkg/kando/output.go +++ b/pkg/kando/output.go @@ -15,7 +15,7 @@ package kando import ( - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/spf13/cobra" "github.com/kanisterio/kanister/pkg/output" @@ -34,7 +34,7 @@ func newOutputCommand() *cobra.Command { func validateArguments(c *cobra.Command, args []string) error { if len(args) != 2 { - return errors.Errorf("Command accepts 2 arguments, received %d arguments", len(args)) + return errkit.New(fmt.Sprintf("Command accepts 2 arguments, received %d arguments", len(args))) } return output.ValidateKey(args[0]) } diff --git a/pkg/kanister.go b/pkg/kanister.go index 0778b1f545..6a10a9d12d 100644 --- a/pkg/kanister.go +++ b/pkg/kanister.go @@ -19,7 +19,7 @@ import ( "sync" "github.com/Masterminds/semver" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/param" @@ -50,7 +50,7 @@ func Register(f Func) error { funcMu.Lock() defer funcMu.Unlock() if f == nil { - return errors.Errorf("kanister: Cannot register nil function") + return errkit.New("kanister: Cannot register nil function") } if _, ok := funcs[f.Name()][version]; ok { panic("kanister: Register called twice for function " + f.Name() + " with version " + DefaultVersion) @@ -80,7 +80,7 @@ func RegisterVersion(f Func, v string) error { funcMu.Lock() defer funcMu.Unlock() if f == nil { - return errors.Errorf("kanister: Cannot register nil function") + return errkit.New("kanister: Cannot register nil function") } if _, ok := funcs[f.Name()][version]; ok { panic("kanister: Register called twice for function " + f.Name() + " with version " + v) diff --git a/pkg/kopia/cli/errors.go b/pkg/kopia/cli/errors.go index 68153212d5..4d08eb48cc 100644 --- a/pkg/kopia/cli/errors.go +++ b/pkg/kopia/cli/errors.go @@ -15,29 +15,29 @@ package cli import ( - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) // Common errors var ( // ErrInvalidID is returned when the ID is empty. - ErrInvalidID = errors.New("invalid ID") + ErrInvalidID = errkit.NewSentinelErr("invalid ID") ) // storage errors var ( // ErrUnsupportedStorage is returned when the storage is not supported. - ErrUnsupportedStorage = errors.New("unsupported storage") + ErrUnsupportedStorage = errkit.NewSentinelErr("unsupported storage") // ErrInvalidRepoPath is returned when the repoPath is empty. - ErrInvalidRepoPath = errors.New("repository path cannot be empty") + ErrInvalidRepoPath = errkit.NewSentinelErr("repository path cannot be empty") // ErrInvalidPrefix is returned when the prefix is empty. - ErrInvalidPrefix = errors.New("prefix cannot be empty") + ErrInvalidPrefix = errkit.NewSentinelErr("prefix cannot be empty") // ErrInvalidBucketName is returned when the bucketName is empty. - ErrInvalidBucketName = errors.New("bucket name cannot be empty") + ErrInvalidBucketName = errkit.NewSentinelErr("bucket name cannot be empty") // ErrInvalidCredentialsFile is returned when the credentials file is empty. - ErrInvalidCredentialsFile = errors.New("credentials file cannot be empty") + ErrInvalidCredentialsFile = errkit.NewSentinelErr("credentials file cannot be empty") // ErrInvalidContainerName is returned when the containerName is empty. - ErrInvalidContainerName = errors.New("container name cannot be empty") + ErrInvalidContainerName = errkit.NewSentinelErr("container name cannot be empty") // ErrInvalidServerURL is returned when the serverURL is empty. - ErrInvalidServerURL = errors.New("server URL cannot be empty") + ErrInvalidServerURL = errkit.NewSentinelErr("server URL cannot be empty") ) diff --git a/pkg/kopia/cli/repository/opts.go b/pkg/kopia/cli/repository/opts.go index 31c92ab0e5..fd05a901ca 100644 --- a/pkg/kopia/cli/repository/opts.go +++ b/pkg/kopia/cli/repository/opts.go @@ -15,11 +15,12 @@ package repository import ( + "fmt" "time" "github.com/go-openapi/strfmt" + "github.com/kanisterio/errkit" "github.com/kanisterio/safecli/command" - "github.com/pkg/errors" "github.com/kanisterio/kanister/pkg/kopia/cli" "github.com/kanisterio/kanister/pkg/kopia/cli/internal" @@ -91,7 +92,7 @@ func optStorage(l internal.Location, repoPathPrefix string, logger log.Logger) c } func errUnsupportedStorageType(t rs.LocType) command.Applier { - err := errors.Wrapf(cli.ErrUnsupportedStorage, "storage location: %v", t) + err := errkit.Wrap(cli.ErrUnsupportedStorage, fmt.Sprintf("storage location: %v", t)) return command.NewErrorArgument(err) } diff --git a/pkg/kopia/errors/utils_test.go b/pkg/kopia/errors/utils_test.go index e4370f0406..7ef1debfd9 100644 --- a/pkg/kopia/errors/utils_test.go +++ b/pkg/kopia/errors/utils_test.go @@ -18,7 +18,6 @@ import ( "testing" "github.com/kanisterio/errkit" - "github.com/pkg/errors" "gopkg.in/check.v1" ) @@ -31,17 +30,14 @@ var _ = check.Suite(&KopiaErrorsTestSuite{}) // TestErrCheck verifies that error types are properly detected after wrapping them func (s *KopiaErrorsTestSuite) TestErrCheck(c *check.C) { - origErr := errors.New("Some error") + origErr := errkit.New("Some error") - errWithMessage := errors.WithMessage(origErr, ErrInvalidPasswordStr) errWrapped := errkit.Wrap(origErr, ErrInvalidPasswordStr) - c.Assert(IsInvalidPasswordError(errWithMessage), check.Equals, true) c.Assert(IsInvalidPasswordError(errWrapped), check.Equals, true) c.Assert(IsRepoNotFoundError(errWrapped), check.Equals, false) permittedErrors := []ErrorType{ErrorInvalidPassword, ErrorRepoNotFound} - c.Assert(CheckKopiaErrors(errWithMessage, permittedErrors), check.Equals, true) c.Assert(CheckKopiaErrors(errWrapped, permittedErrors), check.Equals, true) wrongErrors := []ErrorType{ErrorRepoNotFound} diff --git a/pkg/kube/log_reader_test.go b/pkg/kube/log_reader_test.go index b83a89ea29..708914d0c6 100644 --- a/pkg/kube/log_reader_test.go +++ b/pkg/kube/log_reader_test.go @@ -39,7 +39,7 @@ func (frw *fakeResponseWrapper) Stream(context.Context) (io.ReadCloser, error) { } func (s *LogReaderSuite) TestLogReader(c *check.C) { - err := errors.New("TEST") + err := errkit.New("TEST") for _, tc := range []struct { rw *fakeResponseWrapper err error diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index 8baf644565..5fcb0bd162 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -27,7 +27,6 @@ import ( "github.com/gofrs/uuid" json "github.com/json-iterator/go" "github.com/kanisterio/errkit" - "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/pkg/kube/pod_controller_test.go b/pkg/kube/pod_controller_test.go index b2172ca21c..2b01d5122f 100644 --- a/pkg/kube/pod_controller_test.go +++ b/pkg/kube/pod_controller_test.go @@ -46,7 +46,7 @@ func (s *PodControllerTestSuite) TestPodControllerStartPod(c *check.C) { ctx := context.Background() cli := fake.NewSimpleClientset() - simulatedError := errors.New("SimulatedError") + simulatedError := errkit.New("SimulatedError") cases := map[string]func(prp *FakePodControllerProcessor, pr PodController){ "Pod creation failure": func(pcp *FakePodControllerProcessor, pc PodController) { @@ -81,7 +81,7 @@ func (s *PodControllerTestSuite) TestPodControllerStartPod(c *check.C) { prp.InCreatePodOptions = nil prp.CreatePodRet = nil - prp.CreatePodErr = errors.New("CreatePod should not be invoked") + prp.CreatePodErr = errkit.New("CreatePod should not be invoked") err = pr.StartPod(ctx) c.Assert(err, check.Not(check.IsNil)) @@ -108,7 +108,7 @@ func (s *PodControllerTestSuite) TestPodControllerWaitPod(c *check.C) { ctx := context.Background() cli := fake.NewSimpleClientset() - simulatedError := errkit.Wrap(errors.New("SimulatedError"), "Wrapped") + simulatedError := errkit.Wrap(errkit.New("SimulatedError"), "Wrapped") cases := map[string]func(pcp *FakePodControllerProcessor, pc PodController){ "Waiting failed because pod not started yet": func(pcp *FakePodControllerProcessor, pc PodController) { @@ -169,7 +169,7 @@ func (s *PodControllerTestSuite) TestPodControllerStopPod(c *check.C) { cli := fake.NewSimpleClientset() untouchedStr := "DEADBEEF" - simulatedError := errors.New("SimulatedError") + simulatedError := errkit.New("SimulatedError") cases := map[string]func(pcp *FakePodControllerProcessor, pc PodController){ "Pod not started yet": func(pcp *FakePodControllerProcessor, pc PodController) { diff --git a/pkg/kube/pod_runner_test.go b/pkg/kube/pod_runner_test.go index a3b8c21d61..20a312b1c8 100644 --- a/pkg/kube/pod_runner_test.go +++ b/pkg/kube/pod_runner_test.go @@ -19,7 +19,7 @@ import ( "os" "path" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" @@ -191,10 +191,10 @@ func afterPodRunTestKeyPresentFunc(labelKey, expectedLabelValue string, isLabelE <-ch labelValue, found := pc.Pod().Labels[labelKey] if found != isLabelExpected { - return nil, errors.New("Got different label than expected") + return nil, errkit.New("Got different label than expected") } if isLabelExpected && labelValue != expectedLabelValue { - return nil, errors.New("Found label doesn't match with expected label") + return nil, errkit.New("Found label doesn't match with expected label") } return nil, nil } diff --git a/pkg/kube/pod_test.go b/pkg/kube/pod_test.go index 852dd29f10..191e074b3a 100644 --- a/pkg/kube/pod_test.go +++ b/pkg/kube/pod_test.go @@ -315,7 +315,7 @@ func (s *PodSuite) TestPodWithFilesystemModeVolumes(c *check.C) { ca := action.(testing.CreateAction) p = ca.GetObject().(*corev1.Pod) if len(p.Spec.Volumes[0].Name) > 63 { - return true, nil, errors.New("spec.volumes[0].name must be no more than 63 characters") + return true, nil, errkit.New("spec.volumes[0].name must be no more than 63 characters") } return false, nil, nil }) @@ -364,7 +364,7 @@ func (s *PodSuite) TestPodWithFilesystemModeReadOnlyVolumes(c *check.C) { ca := action.(testing.CreateAction) p = ca.GetObject().(*corev1.Pod) if len(p.Spec.Volumes[0].Name) > 63 { - return true, nil, errors.New("spec.volumes[0].name must be no more than 63 characters") + return true, nil, errkit.New("spec.volumes[0].name must be no more than 63 characters") } return false, nil, nil }) @@ -415,7 +415,7 @@ func (s *PodSuite) TestPodWithBlockModeVolumes(c *check.C) { ca := action.(testing.CreateAction) p = ca.GetObject().(*corev1.Pod) if len(p.Spec.Volumes[0].Name) > 63 { - return true, nil, errors.New("spec.volumes[0].name must be no more than 63 characters") + return true, nil, errkit.New("spec.volumes[0].name must be no more than 63 characters") } return false, nil, nil }) diff --git a/pkg/location/location.go b/pkg/location/location.go index 127e4fe797..9a9534df26 100644 --- a/pkg/location/location.go +++ b/pkg/location/location.go @@ -17,10 +17,11 @@ package location import ( "bytes" "context" + "fmt" "io" "path/filepath" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/aws" @@ -124,7 +125,7 @@ func writeData(ctx context.Context, pType objectstore.ProviderType, profile para } if err := bucket.Put(ctx, path, input, size, nil); err != nil { - return errors.Wrapf(err, "failed to write contents to bucket '%s'", profile.Location.Bucket) + return errkit.Wrap(err, fmt.Sprintf("failed to write contents to bucket '%s'", profile.Location.Bucket)) } return nil @@ -173,7 +174,7 @@ func getProviderType(lType crv1alpha1.LocationType) (objectstore.ProviderType, e case crv1alpha1.LocationTypeAzure: return objectstore.ProviderTypeAzure, nil default: - return "", errors.Errorf("Unsupported Location type: %s", lType) + return "", errkit.New(fmt.Sprintf("Unsupported Location type: %s", lType)) } } @@ -209,7 +210,7 @@ func getOSSecret(ctx context.Context, pType objectstore.ProviderType, cred param case objectstore.ProviderTypeAzure: return getAzureSecret(cred) default: - return nil, errors.Errorf("unknown or unsupported provider type '%s'", pType) + return nil, errkit.New(fmt.Sprintf("unknown or unsupported provider type '%s'", pType)) } return secret, nil } @@ -228,7 +229,7 @@ func getAzureSecret(cred param.Credential) (*objectstore.Secret, error) { case param.CredentialTypeSecret: azSecret, err := secrets.ExtractAzureCredentials(cred.Secret) if err != nil { - return nil, errors.Wrap(err, "Failed to extract azure credentials") + return nil, errkit.Wrap(err, "Failed to extract azure credentials") } os.Azure = azSecret } @@ -258,6 +259,6 @@ func getAWSSecret(ctx context.Context, cred param.Credential) (*objectstore.Secr } return os, nil default: - return nil, errors.Errorf("Unsupported type '%s' for credential", cred.Type) + return nil, errkit.New(fmt.Sprintf("Unsupported type '%s' for credential", cred.Type)) } } diff --git a/pkg/log/fluentbit.go b/pkg/log/fluentbit.go index 36a03397a3..2c2d11cf22 100644 --- a/pkg/log/fluentbit.go +++ b/pkg/log/fluentbit.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/sirupsen/logrus" ) @@ -64,7 +64,7 @@ func NewFluentbitHook(endpoint string) *FluentbitHook { func dial(endpoint string) (net.Conn, error) { conn, err := net.DialTimeout("tcp", endpoint, defaultConnTimeout) if err != nil { - return nil, errors.Wrap(err, "Fluentbit connection problem") + return nil, errkit.Wrap(err, "Fluentbit connection problem") } return conn, nil } @@ -73,12 +73,12 @@ func dial(endpoint string) (net.Conn, error) { func handle(msgs []byte, endpoint string) error { conn, err := dial(endpoint) if err != nil { - return errors.Wrap(err, "Fluentbit connection error") + return errkit.Wrap(err, "Fluentbit connection error") } defer conn.Close() //nolint:errcheck _, err = conn.Write(msgs) if err != nil { - return errors.Wrap(err, "Fluentbit write error") + return errkit.Wrap(err, "Fluentbit write error") } return nil } diff --git a/pkg/log/log.go b/pkg/log/log.go index fcd1932cb0..a5363fbc16 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/sirupsen/logrus" "github.com/kanisterio/kanister/pkg/caller" @@ -34,9 +34,9 @@ const ( ) var ( - ErrEndpointNotSet = errors.New("fluentbit endpoint not set") - ErrNonTCPEndpoint = errors.New("fluentbit endpoint scheme must be tcp") - ErrPathSet = errors.New("fluentbit endpoint path is set") + ErrEndpointNotSet = errkit.NewSentinelErr("fluentbit endpoint not set") + ErrNonTCPEndpoint = errkit.NewSentinelErr("fluentbit endpoint scheme must be tcp") + ErrPathSet = errkit.NewSentinelErr("fluentbit endpoint path is set") ) // OutputSink describes the current output sink. @@ -72,17 +72,17 @@ func SetOutput(sink OutputSink) error { case FluentbitSink: fbitAddr, ok := os.LookupEnv(LoggingServiceHostEnv) if !ok { - return errors.New("Unable to find Fluentbit host address") + return errkit.New("Unable to find Fluentbit host address") } fbitPort, ok := os.LookupEnv(LoggingServicePortEnv) if !ok { - return errors.New("Unable to find Fluentbit logging port") + return errkit.New("Unable to find Fluentbit logging port") } hook := NewFluentbitHook(fbitAddr + ":" + fbitPort) log.AddHook(hook) return nil default: - return errors.New("not implemented") + return errkit.New("not implemented") } } diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 838942d7eb..96e59a03b6 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -59,7 +59,7 @@ func (s *LogSuite) TestLogWithFields(c *check.C) { func (s *LogSuite) TestLogWithError(c *check.C) { const text = "My error message" - err := errors.New("test error") + err := errkit.New("test error") entry := testLogMessage(c, text, WithError(err).Print) c.Assert(entry["error"], check.Equals, err.Error()) c.Assert(entry["level"], check.Equals, infoLevelStr) @@ -88,7 +88,7 @@ func (s *LogSuite) TestLogWithContextFields(c *check.C) { func (s *LogSuite) TestLogWithContextFieldsAndError(c *check.C) { const text = "My error message" ctx := field.Context(context.Background(), "key", "value") - err := errors.New("test error") + err := errkit.New("test error") entry := testLogMessage(c, text, WithError(err).WithContext(ctx).Print) c.Assert(entry["level"], check.Equals, infoLevelStr) // Error should be included in the log entry diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 7831683a47..ba884f2f5b 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -73,7 +73,7 @@ func getLabelCombinations(bl []BoundedLabel) ([]prometheus.Labels, error) { {"operation_type": "restore", "action_set_resolution": "failure"}] */ if !verifyBoundedLabels(bl) { - return nil, errors.New("invalid BoundedLabel list") + return nil, errkit.New("invalid BoundedLabel list") } labelLens := make([]int, len(bl)) for idx, l := range bl { diff --git a/pkg/objectstore/bucket.go b/pkg/objectstore/bucket.go index 33b58db9d0..b4071105cc 100644 --- a/pkg/objectstore/bucket.go +++ b/pkg/objectstore/bucket.go @@ -27,7 +27,7 @@ import ( "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/graymeta/stow" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/field" "github.com/kanisterio/kanister/pkg/log" @@ -81,7 +81,7 @@ func (p *provider) CreateBucket(ctx context.Context, bucketName string) (Bucket, } c, err := l.CreateContainer(bucketName) if err != nil { - return nil, errors.Wrapf(err, "failed to create bucket %s", bucketName) + return nil, errkit.Wrap(err, fmt.Sprintf("failed to create bucket %s", bucketName)) } return newBucket(cfg, c, l), nil } @@ -99,7 +99,7 @@ func (p *provider) GetBucket(ctx context.Context, bucketName string) (Bucket, er } c, err := l.Container(bucketName) if err != nil { - return nil, errors.Wrapf(err, "failed to get bucket %s", bucketName) + return nil, errkit.Wrap(err, fmt.Sprintf("failed to get bucket %s", bucketName)) } return newBucket(cfg, c, l), nil } @@ -155,7 +155,7 @@ func (p *provider) bucketConfig(ctx context.Context, bucketName string) (Provide func s3BucketConfig(ctx context.Context, c ProviderConfig, s *Secret, bucketName string) (ProviderConfig, error) { if s == nil || s.Aws == nil { - return c, errors.New("AWS Secret required to get region") + return c, errkit.New("AWS Secret required to get region") } r, err := s3BucketRegion(ctx, c, *s, bucketName) if err != nil { @@ -179,7 +179,7 @@ type s3Provider struct { // then the return value will be "". func (p *s3Provider) GetRegionForBucket(ctx context.Context, bucketName string) (string, error) { if p.secret == nil || p.secret.Aws == nil { - return "", errors.New("AWS Secret required to get region") + return "", errkit.New("AWS Secret required to get region") } return s3BucketRegion(ctx, p.config, *p.secret, bucketName) } @@ -191,7 +191,7 @@ func s3BucketRegion(ctx context.Context, cfg ProviderConfig, sec Secret, bucketN } s, err := session.NewSession(c) if err != nil { - return "", errors.Wrapf(err, "failed to create session, region = %s", r) + return "", errkit.Wrap(err, fmt.Sprintf("failed to create session, region = %s", r)) } svc := s3.New(s) diff --git a/pkg/objectstore/directory.go b/pkg/objectstore/directory.go index f184c29449..0cf97c9c14 100644 --- a/pkg/objectstore/directory.go +++ b/pkg/objectstore/directory.go @@ -25,7 +25,7 @@ import ( "strings" "github.com/graymeta/stow" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) var _ Directory = (*directory)(nil) @@ -73,9 +73,9 @@ func (d *directory) GetDirectory(ctx context.Context, dir string) (Directory, er items, _, err := d.bucket.container.Items(cloudName(dir), stow.CursorStart, 1) switch { case err != nil: - return nil, errors.Wrapf(err, "could not get directory marker %s", dir) + return nil, errkit.Wrap(err, fmt.Sprintf("could not get directory marker %s", dir)) case len(items) == 0: - return nil, errors.Errorf("no items found. could not get directory marker %s", dir) + return nil, errkit.New(fmt.Sprintf("no items found. could not get directory marker %s", dir)) } return &directory{ bucket: d.bucket, @@ -87,7 +87,7 @@ func (d *directory) GetDirectory(ctx context.Context, dir string) (Directory, er // the returned map is indexed by the relative directory name (without trailing '/') func (d *directory) ListDirectories(ctx context.Context) (map[string]Directory, error) { if d.path == "" { - return nil, errors.New("invalid entry") + return nil, errkit.New("invalid entry") } directories := make(map[string]Directory) @@ -130,7 +130,7 @@ func (d *directory) ListDirectories(ctx context.Context) (map[string]Directory, // ListObjects lists all the files that have d.dirname as the prefix. func (d *directory) ListObjects(ctx context.Context) ([]string, error) { if d.path == "" { - return nil, errors.New("invalid entry") + return nil, errkit.New("invalid entry") } objects := make([]string, 0, 1) @@ -155,7 +155,7 @@ func (d *directory) ListObjects(ctx context.Context) ([]string, error) { // // including /// func (d *directory) DeleteDirectory(ctx context.Context) error { if d.path == "" { - return errors.New("invalid entry") + return errkit.New("invalid entry") } return deleteWithPrefix(ctx, d.bucket.container, cloudName(d.path)) } @@ -176,14 +176,14 @@ func deleteWithPrefix(ctx context.Context, c stow.Container, prefix string) erro return c.RemoveItem(item.Name()) }) if err != nil { - return errors.Wrapf(err, "Failed to delete item %s", prefix) + return errkit.Wrap(err, fmt.Sprintf("Failed to delete item %s", prefix)) } return nil } func (d *directory) Get(ctx context.Context, name string) (io.ReadCloser, map[string]string, error) { if d.path == "" { - return nil, nil, errors.New("invalid entry") + return nil, nil, errkit.New("invalid entry") } objName := d.absPathName(name) @@ -232,7 +232,7 @@ func (d *directory) GetBytes(ctx context.Context, name string) ([]byte, map[stri func (d *directory) Put(ctx context.Context, name string, r io.Reader, size int64, tags map[string]string) error { if d.path == "" { - return errors.New("invalid entry") + return errkit.New("invalid entry") } // K10 tags include '/'. Remove them, at least for S3 sTags := sanitizeTags(tags) @@ -253,7 +253,7 @@ func (d *directory) PutBytes(ctx context.Context, name string, data []byte, tags // Delete removes an object func (d *directory) Delete(ctx context.Context, name string) error { if d.path == "" { - return errors.New("invalid entry") + return errkit.New("invalid entry") } objName := d.absPathName(name) diff --git a/pkg/objectstore/objectstore.go b/pkg/objectstore/objectstore.go index fb0ac26c69..102cf25412 100644 --- a/pkg/objectstore/objectstore.go +++ b/pkg/objectstore/objectstore.go @@ -16,6 +16,7 @@ package objectstore import ( "context" + "fmt" "io" "os" @@ -23,7 +24,7 @@ import ( stowaz "github.com/graymeta/stow/azure" stowgcs "github.com/graymeta/stow/google" stows3 "github.com/graymeta/stow/s3" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "golang.org/x/oauth2/google" "google.golang.org/api/compute/v1" ) @@ -119,10 +120,10 @@ func Supported(t ProviderType) bool { func s3Config(ctx context.Context, config ProviderConfig, secret *Secret) (stowKind string, stowConfig stow.Config, err error) { if secret == nil { - return "", nil, errors.New("Invalid Secret value: nil") + return "", nil, errkit.New("Invalid Secret value: nil") } if secret.Type != SecretTypeAwsAccessKey { - return "", nil, errors.Errorf("invalid secret type %s", secret.Type) + return "", nil, errkit.New(fmt.Sprintf("invalid secret type %s", secret.Type)) } awsAccessKeyID := secret.Aws.AccessKeyID awsSecretAccessKey := secret.Aws.SecretAccessKey @@ -151,7 +152,7 @@ func gcsConfig(ctx context.Context, config ProviderConfig, secret *Secret) (stow cm := stow.ConfigMap{} if secret != nil { if secret.Type != SecretTypeGcpServiceAccountKey { - return "", nil, errors.Errorf("invalid secret type %s", secret.Type) + return "", nil, errkit.New(fmt.Sprintf("invalid secret type %s", secret.Type)) } configJSON = secret.Gcp.ServiceKey projectID = secret.Gcp.ProjectID @@ -177,7 +178,7 @@ func azureConfig(ctx context.Context, secret *Secret) (stowKind string, stowConf var azAccount, azStorageKey, azEnvName string if secret != nil { if secret.Type != SecretTypeAzStorageAccount { - return "", nil, errors.Errorf("invalid secret type %s", secret.Type) + return "", nil, errkit.New(fmt.Sprintf("invalid secret type %s", secret.Type)) } azAccount = secret.Azure.StorageAccount azStorageKey = secret.Azure.StorageKey @@ -186,12 +187,12 @@ func azureConfig(ctx context.Context, secret *Secret) (stowKind string, stowConf var ok bool azAccount, ok = os.LookupEnv("AZURE_STORAGE_ACCOUNT") if !ok { - return "", nil, errors.New("AZURE_STORAGE_ACCOUNT environment not set") + return "", nil, errkit.New("AZURE_STORAGE_ACCOUNT environment not set") } azStorageKey, ok = os.LookupEnv("AZURE_STORAGE_KEY") if !ok { - return "", nil, errors.New("AZURE_STORAGE_KEY environment not set") + return "", nil, errkit.New("AZURE_STORAGE_KEY environment not set") } azEnvName, _ = os.LookupEnv("AZURE_ENV_NAME") // not required to be set. } @@ -211,7 +212,7 @@ func getConfig(ctx context.Context, config ProviderConfig, secret *Secret) (stow case ProviderTypeAzure: return azureConfig(ctx, secret) default: - return "", nil, errors.Errorf("unknown or unimplemented object store type %s", config.Type) + return "", nil, errkit.New(fmt.Sprintf("unknown or unimplemented object store type %s", config.Type)) } } @@ -222,7 +223,7 @@ func getStowLocation(ctx context.Context, config ProviderConfig, secret *Secret) } location, err := stow.Dial(kind, stowConfig) if err != nil { - return nil, errors.Wrapf(err, "could not create store provider %+v", config) + return nil, errkit.Wrap(err, fmt.Sprintf("could not create store provider %+v", config)) } return location, nil } diff --git a/pkg/output/output.go b/pkg/output/output.go index d133a9d46a..a77f71004d 100644 --- a/pkg/output/output.go +++ b/pkg/output/output.go @@ -21,7 +21,7 @@ import ( "os" "regexp" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) const ( @@ -40,7 +40,7 @@ func marshalOutput(key, value string) (string, error) { } outString, err := json.Marshal(out) if err != nil { - return "", errors.Wrap(err, "Failed to marshal key-value pair") + return "", errkit.Wrap(err, "Failed to marshal key-value pair") } return string(outString), nil } @@ -49,19 +49,19 @@ func marshalOutput(key, value string) (string, error) { func UnmarshalOutput(opString []byte) (*Output, error) { p := &Output{} err := json.Unmarshal([]byte(opString), p) - return p, errors.Wrap(err, "Failed to unmarshal key-value pair") + return p, errkit.Wrap(err, "Failed to unmarshal key-value pair") } // ValidateKey validates the key argument func ValidateKey(key string) error { // key should be non-empty if key == "" { - return errors.New("Key should not be empty") + return errkit.New("Key should not be empty") } // key can contain only alpha numeric characters and underscore valid := regexp.MustCompile("^[a-zA-Z0-9_]*$").MatchString if !valid(key) { - return errors.New("Key should contain only alphanumeric characters and underscore") + return errkit.New("Key should contain only alphanumeric characters and underscore") } return nil } diff --git a/pkg/param/param.go b/pkg/param/param.go index dcb461011c..f1fdae70af 100644 --- a/pkg/param/param.go +++ b/pkg/param/param.go @@ -21,8 +21,8 @@ import ( "strings" "time" + "github.com/kanisterio/errkit" osversioned "github.com/openshift/client-go/apps/clientset/versioned" - "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -250,7 +250,7 @@ func New(ctx context.Context, cli kubernetes.Interface, dynCli dynamic.Interface } u, err := kube.FetchUnstructuredObjectWithCli(ctx, dynCli, gvr, namespace, as.Object.Name) if err != nil { - return nil, errors.Wrapf(err, "could not fetch object name: %s, namespace: %s, group: %s, version: %s, resource: %s", as.Object.Name, namespace, gvr.Group, gvr.Version, gvr.Resource) + return nil, errkit.Wrap(err, fmt.Sprintf("could not fetch object name: %s, namespace: %s, group: %s, version: %s, resource: %s", as.Object.Name, namespace, gvr.Group, gvr.Version, gvr.Resource)) } tp.Object = u.UnstructuredContent() @@ -264,11 +264,11 @@ func fetchProfile(ctx context.Context, cli kubernetes.Interface, crCli versioned } p, err := crCli.CrV1alpha1().Profiles(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } cred, err := fetchCredential(ctx, cli, p.Credential) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } return &Profile{ Location: p.Location, @@ -284,7 +284,7 @@ func fetchRepositoryServer(ctx context.Context, cli kubernetes.Interface, crCli } r, err := crCli.CrV1alpha1().RepositoryServers(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } serverTLS, err := secretFromSecretRef(ctx, cli, r.Spec.Server.TLSSecretRef) if err != nil { @@ -300,7 +300,7 @@ func fetchRepositoryServer(ctx context.Context, cli kubernetes.Interface, crCli } repositoryServerService, err := cli.CoreV1().Services(r.Namespace).Get(ctx, r.Status.ServerInfo.ServiceName, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrap(err, "Error Fetching Repository Server Service") + return nil, errkit.Wrap(err, "Error Fetching Repository Server Service") } repositoryServerAddress := fmt.Sprintf("https://%s.%s.%s:%d", repositoryServerService.Name, repositoryServerService.Namespace, clusterLocalDomain, repositoryServerService.Spec.Ports[0].Port) cacheSizeSettings := getKopiaRepositoryCacheSize(r) @@ -341,23 +341,23 @@ func fetchCredential(ctx context.Context, cli kubernetes.Interface, c crv1alpha1 case crv1alpha1.CredentialTypeKopia: return fetchKopiaCredential(ctx, cli, c.KopiaServerSecret) default: - return nil, errors.Errorf("CredentialType '%s' not supported", c.Type) + return nil, errkit.New(fmt.Sprintf("CredentialType '%s' not supported", c.Type)) } } func fetchKeyPairCredential(ctx context.Context, cli kubernetes.Interface, c *crv1alpha1.KeyPair) (*Credential, error) { if c == nil { - return nil, errors.New("KVSecret cannot be nil") + return nil, errkit.New("KVSecret cannot be nil") } s, err := cli.CoreV1().Secrets(c.Secret.Namespace).Get(ctx, c.Secret.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } if _, ok := s.Data[c.IDField]; !ok { - return nil, errors.Errorf("Key '%s' not found in secret '%s:%s'", c.IDField, s.GetNamespace(), s.GetName()) + return nil, errkit.New(fmt.Sprintf("Key '%s' not found in secret '%s:%s'", c.IDField, s.GetNamespace(), s.GetName())) } if _, ok := s.Data[c.SecretField]; !ok { - return nil, errors.Errorf("Value '%s' not found in secret '%s:%s'", c.SecretField, s.GetNamespace(), s.GetName()) + return nil, errkit.New(fmt.Sprintf("Value '%s' not found in secret '%s:%s'", c.SecretField, s.GetNamespace(), s.GetName())) } return &Credential{ Type: CredentialTypeKeyPair, @@ -370,11 +370,11 @@ func fetchKeyPairCredential(ctx context.Context, cli kubernetes.Interface, c *cr func fetchSecretCredential(ctx context.Context, cli kubernetes.Interface, sr *crv1alpha1.ObjectReference) (*Credential, error) { if sr == nil { - return nil, errors.New("Secret reference cannot be nil") + return nil, errkit.New("Secret reference cannot be nil") } s, err := cli.CoreV1().Secrets(sr.Namespace).Get(ctx, sr.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrap(err, "Failed to fetch the secret") + return nil, errkit.Wrap(err, "Failed to fetch the secret") } if err = secrets.ValidateCredentials(s); err != nil { return nil, err @@ -388,7 +388,7 @@ func fetchSecretCredential(ctx context.Context, cli kubernetes.Interface, sr *cr func secretFromSecretRef(ctx context.Context, cli kubernetes.Interface, ref corev1.SecretReference) (*corev1.Secret, error) { secret, err := cli.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("Error fetching secret %s from namespace %s", ref.Name, ref.Namespace)) + return nil, errkit.Wrap(err, fmt.Sprintf("Error fetching secret %s from namespace %s", ref.Name, ref.Namespace)) } return secret, nil } @@ -409,7 +409,7 @@ func fetchSecrets(ctx context.Context, cli kubernetes.Interface, refs map[string for name, ref := range refs { s, err := cli.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } secrets[name] = *s } @@ -421,7 +421,7 @@ func fetchConfigMaps(ctx context.Context, cli kubernetes.Interface, refs map[str for name, ref := range refs { c, err := cli.CoreV1().ConfigMaps(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } configs[name] = *c } @@ -431,7 +431,7 @@ func fetchConfigMaps(ctx context.Context, cli kubernetes.Interface, refs map[str func fetchStatefulSetParams(ctx context.Context, cli kubernetes.Interface, namespace, name string) (*StatefulSetParams, error) { ss, err := cli.AppsV1().StatefulSets(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } ssp := &StatefulSetParams{ Name: name, @@ -459,7 +459,7 @@ func fetchDeploymentConfigParams(ctx context.Context, cli kubernetes.Interface, // because deploymentconfig is not standard kubernetes resource. dc, err := osCli.AppsV1().DeploymentConfigs(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } dcp := &DeploymentConfigParams{ @@ -496,7 +496,7 @@ func fetchDeploymentConfigParams(ctx context.Context, cli kubernetes.Interface, func fetchDeploymentParams(ctx context.Context, cli kubernetes.Interface, namespace, name string) (*DeploymentParams, error) { d, err := cli.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } dp := &DeploymentParams{ Name: name, @@ -551,7 +551,7 @@ func volumes(pod corev1.Pod, volToPvc map[string]string) map[string]string { func fetchPVCParams(ctx context.Context, cli kubernetes.Interface, namespace, name string) (*PVCParams, error) { _, err := cli.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return nil, errors.WithStack(err) + return nil, errkit.WithStack(err) } return &PVCParams{ Name: name, @@ -561,32 +561,32 @@ func fetchPVCParams(ctx context.Context, cli kubernetes.Interface, namespace, na func fetchKopiaCredential(ctx context.Context, cli kubernetes.Interface, ks *crv1alpha1.KopiaServerSecret) (*Credential, error) { if ks == nil { - return nil, errors.New("Kopia Secret reference cannot be nil") + return nil, errkit.New("Kopia Secret reference cannot be nil") } if ks.UserPassphrase.Secret == nil { - return nil, errors.New("Kopia UserPassphrase Secret reference cannot be nil") + return nil, errkit.New("Kopia UserPassphrase Secret reference cannot be nil") } passSecret, err := cli.CoreV1().Secrets(ks.UserPassphrase.Secret.Namespace).Get(ctx, ks.UserPassphrase.Secret.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrapf(err, "Failed to fetch the secret %s/%s", ks.UserPassphrase.Secret.Namespace, ks.UserPassphrase.Secret.Name) + return nil, errkit.Wrap(err, "Failed to fetch the secret", "namespace", ks.UserPassphrase.Secret.Namespace, "name", ks.UserPassphrase.Secret.Name) } password, ok := passSecret.Data[ks.UserPassphrase.Key] if !ok { - return nil, errors.New("Failed to fetch user passphrase from secret") + return nil, errkit.New("Failed to fetch user passphrase from secret") } if ks.TLSCert == nil || ks.TLSCert.Secret == nil { - return nil, errors.New("Kopia TLS cert Secret reference cannot be nil") + return nil, errkit.New("Kopia TLS cert Secret reference cannot be nil") } tlsSecret, err := cli.CoreV1().Secrets(ks.TLSCert.Secret.Namespace).Get(ctx, ks.TLSCert.Secret.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrapf(err, "Failed to fetch the secret %s/%s", ks.TLSCert.Secret.Namespace, ks.TLSCert.Secret.Name) + return nil, errkit.Wrap(err, "Failed to fetch the secret", "namespace", ks.TLSCert.Secret.Namespace, "name", ks.TLSCert.Secret.Name) } tlsCert, ok := tlsSecret.Data[ks.TLSCert.Key] if !ok { - return nil, errors.New("Failed to fetch TLS cert from secret") + return nil, errkit.New("Failed to fetch TLS cert from secret") } return &Credential{ Type: CredentialTypeKopia, diff --git a/pkg/param/render.go b/pkg/param/render.go index 1fde104cc7..dbc86203d1 100644 --- a/pkg/param/render.go +++ b/pkg/param/render.go @@ -21,7 +21,7 @@ import ( "strings" "text/template" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/ksprig" @@ -121,7 +121,7 @@ func RenderArtifacts(arts map[string]crv1alpha1.Artifact, tp TemplateParams) (ma func renderStringArg(arg string, tp TemplateParams) (string, error) { t, err := template.New("config").Option("missingkey=error").Funcs(ksprig.TxtFuncMap()).Parse(arg) if err != nil { - return "", errors.WithStack(err) + return "", errkit.WithStack(err) } buf := bytes.NewBuffer(nil) if err = t.Execute(buf, tp); err != nil { @@ -131,7 +131,7 @@ func renderStringArg(arg string, tp TemplateParams) (string, error) { if strings.Contains(err.Error(), undefinedKeyErrorMsg) { return "", newUndefinedKeyError(err.Error()) } - return "", errors.WithStack(err) + return "", errkit.WithStack(err) } return buf.String(), nil } @@ -140,7 +140,7 @@ func newUndefinedKeyError(err string) error { pos := strings.LastIndex(err, undefinedKeyErrorMsg) adjustedPos := pos + len(undefinedKeyErrorMsg) key := strings.Trim(err[adjustedPos:], "\"") - return errors.WithStack(errors.New(fmt.Sprintf("Failed to render template: \"%s\" not found", key))) + return errkit.WithStack(errkit.New(fmt.Sprintf("Failed to render template: \"%s\" not found", key))) } // RenderObjectRefs function renders object refs from TemplateParams @@ -153,7 +153,7 @@ func RenderObjectRefs(in map[string]crv1alpha1.ObjectReference, tp TemplateParam for k, v := range in { rv, err := render(v, tp) if err != nil { - return nil, errors.Wrapf(err, "could not render object reference {%s}", k) + return nil, errkit.Wrap(err, fmt.Sprintf("could not render object reference {%s}", k)) } out[k] = rv.(crv1alpha1.ObjectReference) } diff --git a/pkg/phase.go b/pkg/phase.go index 549906e910..c7ae3db273 100644 --- a/pkg/phase.go +++ b/pkg/phase.go @@ -16,10 +16,11 @@ package kanister import ( "context" + "fmt" "strings" "github.com/Masterminds/semver" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/field" @@ -63,7 +64,7 @@ func (p *Phase) Exec(ctx context.Context, bp crv1alpha1.Blueprint, action string // Get the action from Blueprint a, ok := bp.Actions[action] if !ok { - return nil, errors.Errorf("Action {%s} not found in action map", action) + return nil, errkit.New(fmt.Sprintf("Action {%s} not found in action map", action)) } // Render the argument templates for the Phase's function phases := []crv1alpha1.BlueprintPhase{} @@ -93,11 +94,11 @@ func (p *Phase) setPhaseArgs(phases []crv1alpha1.BlueprintPhase, tp param.Templa } if err = utils.CheckRequiredArgs(p.f.RequiredArgs(), args); err != nil { - return errors.Wrapf(err, "Required args missing for function %s", p.f.Name()) + return errkit.Wrap(err, fmt.Sprintf("Required args missing for function %s", p.f.Name())) } if err = utils.CheckSupportedArgs(p.f.Arguments(), args); err != nil { - return errors.Wrapf(err, "Checking supported args for function %s.", p.f.Name()) + return errkit.Wrap(err, fmt.Sprintf("Checking supported args for function %s.", p.f.Name())) } p.args = args @@ -120,7 +121,7 @@ func renderFuncArgs( func GetDeferPhase(bp crv1alpha1.Blueprint, action, version string, tp param.TemplateParams) (*Phase, error) { a, ok := bp.Actions[action] if !ok { - return nil, errors.Errorf("Action {%s} not found in blueprint actions", action) + return nil, errkit.New(fmt.Sprintf("Action {%s} not found in blueprint actions", action)) } if a.DeferPhase == nil { @@ -150,19 +151,19 @@ func regFuncVersion(f, version string) (semver.Version, error) { defaultVersion, funcVersion, err := getFunctionVersion(version) if err != nil { - return semver.Version{}, errors.Wrapf(err, "Failed to get function version") + return semver.Version{}, errkit.Wrap(err, "Failed to get function version") } regVersion := *funcVersion if _, ok := funcs[f]; !ok { - return semver.Version{}, errors.Errorf("Requested function {%s} has not been registered", f) + return semver.Version{}, errkit.New(fmt.Sprintf("Requested function {%s} has not been registered", f)) } if _, ok := funcs[f][regVersion]; !ok { if funcVersion.Equal(defaultVersion) { - return semver.Version{}, errors.Errorf("Requested function {%s} has not been registered with version {%s}", f, version) + return semver.Version{}, errkit.New(fmt.Sprintf("Requested function {%s} has not been registered with version {%s}", f, version)) } if _, ok := funcs[f][*defaultVersion]; !ok { - return semver.Version{}, errors.Errorf("Requested function {%s} has not been registered with versions {%s} or {%s}", f, version, DefaultVersion) + return semver.Version{}, errkit.New(fmt.Sprintf("Requested function {%s} has not been registered with versions {%s} or {%s}", f, version, DefaultVersion)) } log.Info().Print("Falling back to default version of the function", field.M{"Function": f, "PreferredVersion": version, "FallbackVersion": DefaultVersion}) return *defaultVersion, nil @@ -175,7 +176,7 @@ func regFuncVersion(f, version string) (semver.Version, error) { func GetPhases(bp crv1alpha1.Blueprint, action, version string, tp param.TemplateParams) ([]*Phase, error) { a, ok := bp.Actions[action] if !ok { - return nil, errors.Errorf("Action {%s} not found in action map", action) + return nil, errkit.New(fmt.Sprintf("Action {%s} not found in action map", action)) } phases := make([]*Phase, 0, len(a.Phases)) @@ -207,7 +208,7 @@ func (p *Phase) Validate(args map[string]any) error { func getFunctionVersion(version string) (*semver.Version, *semver.Version, error) { dv, err := semver.NewVersion(DefaultVersion) if err != nil { - return nil, nil, errors.Wrap(err, "Failed to parse default function version") + return nil, nil, errkit.Wrap(err, "Failed to parse default function version") } switch version { case DefaultVersion, "": @@ -215,7 +216,7 @@ func getFunctionVersion(version string) (*semver.Version, *semver.Version, error default: fv, err := semver.NewVersion(version) if err != nil { - return nil, nil, errors.Wrapf(err, "Failed to parse function version {%s}", version) + return nil, nil, errkit.Wrap(err, fmt.Sprintf("Failed to parse function version {%s}", version)) } return dv, fv, nil } diff --git a/pkg/poll/poll.go b/pkg/poll/poll.go index a807e421cd..6f7b8f7a19 100644 --- a/pkg/poll/poll.go +++ b/pkg/poll/poll.go @@ -19,7 +19,7 @@ import ( "time" "github.com/jpillora/backoff" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) // Func returns true if the condition is satisfied, or an error if the loop @@ -71,7 +71,7 @@ func WaitWithRetries(ctx context.Context, numRetries int, r IsRetryableFunc, f F // parameters `b`. func WaitWithBackoffWithRetries(ctx context.Context, b backoff.Backoff, numRetries int, r IsRetryableFunc, f Func) error { if numRetries < 0 { - return errors.New("numRetries must be non-negative") + return errkit.New("numRetries must be non-negative") } t := time.NewTimer(0) @@ -99,7 +99,7 @@ func WaitWithBackoffWithRetries(ctx context.Context, b backoff.Backoff, numRetri t.Reset(sleep) select { case <-ctx.Done(): - return errors.Wrap(ctx.Err(), "Context done while polling") + return errkit.Wrap(ctx.Err(), "Context done while polling") case <-t.C: } } diff --git a/pkg/poll/poll_test.go b/pkg/poll/poll_test.go index 60dd382f29..90b297058e 100644 --- a/pkg/poll/poll_test.go +++ b/pkg/poll/poll_test.go @@ -139,7 +139,7 @@ func (s *PollSuite) TestWaitWithRetriesTimeout(c *check.C) { defer runtime.GOMAXPROCS(maxprocs) f := func(context.Context) (bool, error) { - return false, errors.New("retryable") + return false, errkit.New("retryable") } errf := func(err error) bool { return err.Error() == "retryable" diff --git a/pkg/progress/action.go b/pkg/progress/action.go index 8e4d917112..11eeaee64f 100644 --- a/pkg/progress/action.go +++ b/pkg/progress/action.go @@ -5,7 +5,7 @@ import ( "strconv" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kanister "github.com/kanisterio/kanister/pkg" @@ -75,7 +75,7 @@ func updateActionProgress( ) (bool, error) { actionSet, err := client.CrV1alpha1().ActionSets(namespace).Get(ctx, actionSetName, metav1.GetOptions{}) if err != nil { - return false, errors.Wrap(err, "Failed to get actionset") + return false, errkit.Wrap(err, "Failed to get actionset") } if actionSet.Status == nil { @@ -206,7 +206,7 @@ func SetActionSetPercentCompleted(actionSet *crv1alpha1.ActionSet) error { pp, err := strconv.Atoi(phase.Progress.ProgressPercent) if err != nil { - return errors.Wrap(err, "Invalid phase progress percent") + return errkit.Wrap(err, "Invalid phase progress percent") } actionProgress += pp } diff --git a/pkg/reconcile/reconcile.go b/pkg/reconcile/reconcile.go index 543ec7d14f..9e59f30779 100644 --- a/pkg/reconcile/reconcile.go +++ b/pkg/reconcile/reconcile.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -34,7 +34,7 @@ func ActionSet(ctx context.Context, cli crclientv1alpha1.CrV1alpha1Interface, ns return poll.Wait(ctx, func(ctx context.Context) (bool, error) { as, err := cli.ActionSets(ns).Get(ctx, name, metav1.GetOptions{}) if err != nil { - return false, errors.WithStack(err) + return false, errkit.WithStack(err) } if err = validate.ActionSet(as); err != nil { return false, err @@ -52,7 +52,7 @@ func ActionSet(ctx context.Context, cli crclientv1alpha1.CrV1alpha1Interface, ns } if err != nil { msg := fmt.Sprintf("Failed to update ActionSet %s", name) - return false, errors.Wrap(err, msg) + return false, errkit.Wrap(err, msg) } return true, nil }) diff --git a/pkg/resource/resource.go b/pkg/resource/resource.go index f4ecc6e74b..f09b1fb228 100644 --- a/pkg/resource/resource.go +++ b/pkg/resource/resource.go @@ -21,7 +21,7 @@ import ( "strconv" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" @@ -52,11 +52,11 @@ func CreateCustomResources(ctx context.Context, config *rest.Config) error { func newOpKitContext(ctx context.Context, config *rest.Config) (*customresource.Context, error) { clientset, err := kubernetes.NewForConfig(config) if err != nil { - return nil, errors.Wrap(err, "failed to get k8s client.") + return nil, errkit.Wrap(err, "failed to get k8s client.") } apiExtClientset, err := apiextensionsclient.NewForConfig(config) if err != nil { - return nil, errors.Wrap(err, "failed to create k8s API extension clientset") + return nil, errkit.Wrap(err, "failed to create k8s API extension clientset") } return &customresource.Context{ Clientset: clientset, diff --git a/pkg/restic/restic.go b/pkg/restic/restic.go index fe0951f4e3..d81d1b63ec 100644 --- a/pkg/restic/restic.go +++ b/pkg/restic/restic.go @@ -22,7 +22,7 @@ import ( "strconv" "strings" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" @@ -198,10 +198,10 @@ func resticArgs(profile *param.Profile, repository, encryptionKey string) ([]str case crv1alpha1.LocationTypeAzure: cmd, err = resticAzureArgs(profile, repository) default: - return nil, errors.New("Unsupported type '%s' for the location") + return nil, errkit.New(fmt.Sprintf("Unsupported type '%s' for the location", profile.Location.Type)) } if err != nil { - return nil, errors.Wrap(err, "Failed to get arguments") + return nil, errkit.Wrap(err, "Failed to get arguments") } return append(cmd, fmt.Sprintf("export %s=%s\n", ResticPassword, encryptionKey), ResticCommand), nil } @@ -217,7 +217,7 @@ func resticS3Args(profile *param.Profile, repository string) ([]string, error) { } args, err := resticS3CredentialArgs(profile.Credential) if err != nil { - return nil, errors.Wrap(err, "Failed to create args from credential") + return nil, errkit.Wrap(err, "Failed to create args from credential") } args = append(args, fmt.Sprintf("export %s=s3:%s/%s\n", ResticRepository, s3Endpoint, repository)) return args, nil @@ -233,7 +233,7 @@ func resticS3CredentialArgs(creds param.Credential) ([]string, error) { case param.CredentialTypeSecret: return resticS3CredentialSecretArgs(creds.Secret) default: - return nil, errors.Errorf("Unsupported type '%s' for credentials", creds.Type) + return nil, errkit.New(fmt.Sprintf("Unsupported type '%s' for credentials", creds.Type)) } } @@ -301,12 +301,12 @@ func GetOrCreateRepository( // Create a repository cmd, err := InitCommand(profile, artifactPrefix, encryptionKey, insecureTLS) if err != nil { - return errors.Wrap(err, "Failed to create init command") + return errkit.Wrap(err, "Failed to create init command") } stdout, stderr, err := kube.Exec(ctx, cli, namespace, pod, container, cmd, nil) format.Log(pod, container, stdout) format.Log(pod, container, stderr) - return errors.Wrapf(err, "Failed to create object store backup location") + return errkit.Wrap(err, "Failed to create object store backup location") } // CheckIfRepoIsReachable checks if repo can be reached by trying to list snapshots @@ -323,13 +323,13 @@ func CheckIfRepoIsReachable( ) error { _, stderr, err := getLatestSnapshots(ctx, profile, artifactPrefix, encryptionKey, insecureTLS, cli, namespace, pod, container) if IsPasswordIncorrect(stderr) { // If password didn't work - return errors.New(PasswordIncorrect) + return errkit.New(PasswordIncorrect) } if DoesRepoExist(stderr) { - return errors.New(RepoDoesNotExist) + return errkit.New(RepoDoesNotExist) } if err != nil { - return errors.Wrap(err, "Failed to list snapshots") + return errkit.Wrap(err, "Failed to list snapshots") } return nil } @@ -349,7 +349,7 @@ func getLatestSnapshots( // Use the latest snapshots command to check if the repository exists cmd, err := LatestSnapshotsCommand(profile, artifactPrefix, encryptionKey, insecureTLS) if err != nil { - return "", "", errors.Wrap(err, "Failed to create snapshot command") + return "", "", errkit.Wrap(err, "Failed to create snapshot command") } stdout, stderr, err := kube.Exec(ctx, cli, namespace, pod, container, cmd, nil) format.Log(pod, container, stdout) @@ -362,10 +362,10 @@ func SnapshotIDFromSnapshotLog(output string) (string, error) { var result []map[string]interface{} err := json.Unmarshal([]byte(output), &result) if err != nil { - return "", errors.WithMessage(err, "Failed to unmarshall output from snapshotCommand") + return "", errkit.Wrap(err, "Failed to unmarshall output from snapshotCommand") } if len(result) == 0 { - return "", errors.New("Snapshot not found") + return "", errkit.New("Snapshot not found") } snapID := result[0]["short_id"] return snapID.(string), nil diff --git a/pkg/stream/stream.go b/pkg/stream/stream.go index d471a0d609..6e2e1aa692 100644 --- a/pkg/stream/stream.go +++ b/pkg/stream/stream.go @@ -21,7 +21,7 @@ import ( "github.com/kopia/kopia/snapshot" "github.com/kopia/kopia/snapshot/snapshotfs" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/kopia/repository" kansnapshot "github.com/kanisterio/kanister/pkg/kopia/snapshot" @@ -37,7 +37,7 @@ const ( func Push(ctx context.Context, configFile, dirPath, filePath, password, sourceEndpoint string) error { rep, err := repository.Open(ctx, configFile, password, "kanister stream push") if err != nil { - return errors.Wrap(err, "Failed to open kopia repository") + return errkit.Wrap(err, "Failed to open kopia repository") } // Initialize a directory tree with given file // The following will create / objects @@ -46,10 +46,10 @@ func Push(ctx context.Context, configFile, dirPath, filePath, password, sourceEn // `dir/file` objects will be created under it root, err := virtualfs.NewDirectory(filepath.Base(dirPath)) if err != nil { - return errors.Wrap(err, "Failed to create root directory") + return errkit.Wrap(err, "Failed to create root directory") } if _, err = virtualfs.AddFileWithStreamSource(root, filePath, sourceEndpoint, defaultPermissions, defaultPermissions); err != nil { - return errors.Wrap(err, "Failed to add file with the given stream source to the root directory") + return errkit.Wrap(err, "Failed to add file with the given stream source to the root directory") } // Setup kopia uploader @@ -66,5 +66,5 @@ func Push(ctx context.Context, configFile, dirPath, filePath, password, sourceEn // Create a kopia snapshot _, _, err = kansnapshot.SnapshotSource(ctx, rep, u, sourceInfo, root, snapshotDescription) - return errors.Wrap(err, "Failed to create kopia snapshot") + return errkit.Wrap(err, "Failed to create kopia snapshot") } diff --git a/pkg/testing/e2e_test.go b/pkg/testing/e2e_test.go index 17ef519cd3..3e3ffd41e0 100644 --- a/pkg/testing/e2e_test.go +++ b/pkg/testing/e2e_test.go @@ -23,7 +23,7 @@ import ( "log" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -166,7 +166,7 @@ func (s *E2ESuite) TestKubeExec(c *check.C) { case err != nil, as.Status == nil: return false, err case as.Status.State == crv1alpha1.StateFailed: - return true, errors.Errorf("Actionset failed: %#v", as.Status) + return true, errkit.New(fmt.Sprintf("Actionset failed: %#v", as.Status)) case as.Status.State == crv1alpha1.StateComplete: return true, nil } @@ -290,7 +290,7 @@ func (s *E2ESuite) TestKubeTask(c *check.C) { case err != nil, as.Status == nil: return false, err case as.Status.State == crv1alpha1.StateFailed: - return true, errors.Errorf("Actionset failed: %#v", as.Status) + return true, errkit.New(fmt.Sprintf("Actionset failed: %#v", as.Status)) case as.Status.State == crv1alpha1.StateComplete: return true, nil } @@ -524,7 +524,7 @@ func (s *E2ESuite) waitForActionSetComplete(asName string) error { case err != nil, as.Status == nil: return false, err case as.Status.State == crv1alpha1.StateFailed: - return true, errors.Errorf("Actionset failed: %#v", as.Status) + return true, errkit.New(fmt.Sprintf("Actionset failed: %#v", as.Status)) case as.Status.State == crv1alpha1.StateComplete: return true, nil } @@ -553,7 +553,7 @@ func (s *E2ESuite) waitForFunctionPodReady() error { } if len(pods.Items) > 1 { - return false, errors.New("more than one kanister-job pod found") + return false, errkit.New("more than one kanister-job pod found") } return true, nil @@ -564,7 +564,7 @@ func verifyAnnotationsInFunctionPod(funcPodAnnotations, expectedAnnotations map[ for k, v := range expectedAnnotations { val, ok := funcPodAnnotations[k] if !ok || v != val { - return errors.New(fmt.Sprintf("Either key %s, is not found in pod annotations or, its values (%s and %s) don't match", k, v, val)) + return errkit.New(fmt.Sprintf("Either key %s, is not found in pod annotations or, its values (%s and %s) don't match", k, v, val)) } } return nil @@ -574,7 +574,7 @@ func verifyLabelsInFunctionPod(funcPodLabels, expectedLabels map[string]string) for k, v := range expectedLabels { val, ok := funcPodLabels[k] if !ok || v != val { - return errors.New(fmt.Sprintf("Either key %s, is not found in pod labels or, its values (%s and %s) don't match", k, v, val)) + return errkit.New(fmt.Sprintf("Either key %s, is not found in pod labels or, its values (%s and %s) don't match", k, v, val)) } } return nil diff --git a/pkg/testing/integration_test.go b/pkg/testing/integration_test.go index 80bce4d248..514a07c4d0 100644 --- a/pkg/testing/integration_test.go +++ b/pkg/testing/integration_test.go @@ -23,7 +23,7 @@ import ( test "testing" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" @@ -425,7 +425,7 @@ func (s *IntegrationSuite) createActionset(ctx context.Context, c *check.C, as * case err != nil, as.Status == nil: return false, err case as.Status.State == crv1alpha1.StateFailed: - return true, errors.Errorf("Actionset failed: %#v", as.Status) + return true, errkit.New(fmt.Sprintf("Actionset failed: %#v", as.Status)) case as.Status.State == crv1alpha1.StateComplete: return true, nil } diff --git a/pkg/testutil/func.go b/pkg/testutil/func.go index 8e5beabdf6..bb45370478 100644 --- a/pkg/testutil/func.go +++ b/pkg/testutil/func.go @@ -18,7 +18,7 @@ import ( "context" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kanister "github.com/kanisterio/kanister/pkg" @@ -48,7 +48,7 @@ var ( ) func failFunc(context.Context, param.TemplateParams, map[string]interface{}) (map[string]interface{}, error) { - err := errors.New("Kanister function failed") + err := errkit.New("Kanister function failed") failFuncCh <- err return nil, err } diff --git a/pkg/testutil/mockblockstorage/mockblockstorage.go b/pkg/testutil/mockblockstorage/mockblockstorage.go index d36e38e565..9275cf4a60 100644 --- a/pkg/testutil/mockblockstorage/mockblockstorage.go +++ b/pkg/testutil/mockblockstorage/mockblockstorage.go @@ -20,7 +20,7 @@ import ( "time" uuid "github.com/gofrs/uuid" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/blockstorage" "github.com/kanisterio/kanister/pkg/blockstorage/getter" @@ -57,7 +57,7 @@ func (*mockGetter) Get(storageType blockstorage.Type, config map[string]string) case blockstorage.TypeGPD: return Get(storageType) default: - return nil, errors.New("Get failed") + return nil, errkit.New("Get failed") } } @@ -65,7 +65,7 @@ func (*mockGetter) Get(storageType blockstorage.Type, config map[string]string) func Get(storageType blockstorage.Type) (*Provider, error) { volumeUUID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } volume := blockstorage.Volume{ Type: storageType, @@ -84,7 +84,7 @@ func Get(storageType blockstorage.Type) (*Provider, error) { snapVol := volume snapUUID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } snapshot := blockstorage.Snapshot{ Type: storageType, @@ -122,7 +122,7 @@ func (p *Provider) VolumeCreate(context.Context, blockstorage.Volume) (*blocksto func (p *Provider) VolumeCreateFromSnapshot(ctx context.Context, snapshot blockstorage.Snapshot, tags map[string]string) (*blockstorage.Volume, error) { volUUID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } vol := blockstorage.Volume{ Type: snapshot.Type, @@ -197,7 +197,7 @@ func (p *Provider) SetTags(ctx context.Context, resource interface{}, tags map[s case *blockstorage.Snapshot: return nil default: - return errors.Errorf("Unsupported resource type %v(%T)", res, res) + return errkit.New(fmt.Sprintf("Unsupported resource type %v(%T)", res, res)) } } diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 55aff0c8dc..396472f324 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -23,7 +23,7 @@ import ( "strings" "time" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -56,7 +56,7 @@ func PrintStage(description string, i indicator) { func GetNamespaceUID(ctx context.Context, cli kubernetes.Interface, namespace string) (string, error) { ns, err := cli.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{}) if err != nil { - return "", errors.Wrapf(err, "Failed to get namespace %s", namespace) + return "", errkit.Wrap(err, "Failed to get namespace", "namespace", namespace) } return string(ns.GetUID()), nil } @@ -85,7 +85,7 @@ func GetIntOrDefault(value string, defaultValue int) (int, error) { v, err := strconv.Atoi(value) if err != nil { v = defaultValue - return v, errors.New("conversion to integer failed, using default value for the field") + return v, errkit.New("conversion to integer failed, using default value for the field") } return v, nil } @@ -121,7 +121,7 @@ func RoundUpDuration(t time.Duration) time.Duration { func CheckRequiredArgs(reqArgs []string, args map[string]interface{}) error { for _, a := range reqArgs { if _, ok := args[a]; !ok { - return errors.Errorf("Required arg missing: %s", a) + return errkit.New(fmt.Sprintf("Required arg missing: %s", a)) } } return nil @@ -132,7 +132,7 @@ func CheckRequiredArgs(reqArgs []string, args map[string]interface{}) error { func CheckSupportedArgs(supportedArgs []string, args map[string]interface{}) error { for a := range args { if !slices.Contains(supportedArgs, a) { - return errors.Errorf("argument %s is not supported", a) + return errkit.New(fmt.Sprintf("argument %s is not supported", a)) } } return nil diff --git a/pkg/validate/error.go b/pkg/validate/error.go index 5011e94a25..50c4c591a4 100644 --- a/pkg/validate/error.go +++ b/pkg/validate/error.go @@ -15,18 +15,16 @@ package validate import ( - "fmt" - - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) -var errValidate = fmt.Errorf("Validation Failed") +var errValidate = errkit.NewSentinelErr("Validation Failed") func errorf(err error, format string, args ...interface{}) error { - return errors.Wrapf(err, format, args...) + return errkit.Wrap(err, format, args...) } -// IsError returns true iff the underlying cause was a validation error. +// IsError returns true if the underlying cause was a validation error. func IsError(err error) bool { - return errors.Cause(err) == errValidate + return errkit.Is(err, errValidate) } diff --git a/pkg/validate/error_test.go b/pkg/validate/error_test.go index 05b9cba995..cf86806870 100644 --- a/pkg/validate/error_test.go +++ b/pkg/validate/error_test.go @@ -17,7 +17,7 @@ package validate import ( "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "gopkg.in/check.v1" ) @@ -43,23 +43,23 @@ func (s *ErrorSuite) TestIsError(c *check.C) { is: true, }, { - err: errors.Wrap(nil, "test"), + err: errkit.Wrap(nil, "test"), is: false, }, { - err: errors.WithStack(nil), + err: errkit.WithStack(nil), is: false, }, { - err: errors.Wrap(errValidate, "test"), + err: errkit.Wrap(errValidate, "test"), is: true, }, { - err: errors.WithStack(errValidate), + err: errkit.WithStack(errValidate), is: true, }, { - err: errors.New("test"), + err: errkit.New("test"), is: false, }, } { diff --git a/pkg/validatingwebhook/repositoryserver_handler.go b/pkg/validatingwebhook/repositoryserver_handler.go index b3b9c3509e..b401050c99 100644 --- a/pkg/validatingwebhook/repositoryserver_handler.go +++ b/pkg/validatingwebhook/repositoryserver_handler.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -43,11 +43,11 @@ func (r *RepositoryServerValidator) ValidateUpdate(ctx context.Context, old runt oldrs, ook := old.(*crv1alpha1.RepositoryServer) newrs, nok := new.(*crv1alpha1.RepositoryServer) if !ook || !nok { - return nil, errors.New("Either updated object or the old object is not of type RepositoryServer.cr.kanister.io") + return nil, errkit.New("Either updated object or the old object is not of type RepositoryServer.cr.kanister.io") } errMsg := fmt.Sprintf("RepositoryServer.cr.kanister.io \"%s\" is invalid: spec.repository.rootPath: Invalid value, Value is immutable", newrs.Name) if oldrs.Spec.Repository.RootPath != newrs.Spec.Repository.RootPath { - return nil, errors.New(errMsg) + return nil, errkit.New(errMsg) } return nil, nil } diff --git a/pkg/virtualfs/directory.go b/pkg/virtualfs/directory.go index 3365acb687..334741f819 100644 --- a/pkg/virtualfs/directory.go +++ b/pkg/virtualfs/directory.go @@ -21,8 +21,8 @@ import ( "path" "strings" + "github.com/kanisterio/errkit" "github.com/kopia/kopia/fs" - "github.com/pkg/errors" ) // Directory is a mock in-memory implementation of kopia's fs.Directory @@ -58,7 +58,7 @@ func (d *Directory) AddAllDirs(pathname string, permissions os.FileMode) (subdir for _, n := range missing { if p, err = p.AddDir(n, permissions); err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("Failed to add sub directory '%s'", n)) + return nil, errkit.Wrap(err, fmt.Sprintf("Failed to add sub directory '%s'", n)) } } @@ -94,10 +94,10 @@ func (d *Directory) Subdir(name string) (*Directory, error) { subdir := fs.FindByName(curr.children, name) if subdir == nil { - return nil, errors.New(fmt.Sprintf("'%s' not found in '%s'", name, curr.Name())) + return nil, errkit.New(fmt.Sprintf("'%s' not found in '%s'", name, curr.Name())) } if !subdir.IsDir() { - return nil, errors.New(fmt.Sprintf("'%s' is not a directory in '%s'", name, curr.Name())) + return nil, errkit.New(fmt.Sprintf("'%s' is not a directory in '%s'", name, curr.Name())) } return subdir.(*Directory), nil @@ -111,12 +111,12 @@ func (d *Directory) Summary() *fs.DirectorySummary { // addChild adds the given entry under d, errors out if the entry is already present func (d *Directory) addChild(e fs.Entry) error { if strings.Contains(e.Name(), "/") { - return errors.New("Failed to add child entry: name cannot contain '/'") + return errkit.New("Failed to add child entry: name cannot contain '/'") } child := fs.FindByName(d.children, e.Name()) if child != nil { - return errors.New("Failed to add child entry: already exists") + return errkit.New("Failed to add child entry: already exists") } d.children = append(d.children, e) @@ -138,7 +138,7 @@ func (d *Directory) resolveDirs(pathname string) (parent *Directory, missing []s return p, parts[i:], nil } if !i2.IsDir() { - return nil, nil, errors.New(fmt.Sprintf("'%s' is not a directory in '%s'", n, p.Name())) + return nil, nil, errkit.New(fmt.Sprintf("'%s' is not a directory in '%s'", n, p.Name())) } p = i2.(*Directory) } @@ -162,7 +162,7 @@ func AddFileWithStreamSource(d *Directory, filePath, sourceEndpoint string, dirP f := FileFromEndpoint(name, sourceEndpoint, filePermissions) if err := p.addChild(f); err != nil { - return nil, errors.Wrap(err, "Failed to add file") + return nil, errkit.Wrap(err, "Failed to add file") } return f, nil } @@ -177,7 +177,7 @@ func AddFileWithContent(d *Directory, filePath string, content []byte, dirPermis f := FileWithContent(name, filePermissions, content) if err := p.addChild(f); err != nil { - return nil, errors.Wrap(err, "Failed to add file") + return nil, errkit.Wrap(err, "Failed to add file") } return f, nil } diff --git a/pkg/virtualfs/file.go b/pkg/virtualfs/file.go index 06093e17e2..fa324f7538 100644 --- a/pkg/virtualfs/file.go +++ b/pkg/virtualfs/file.go @@ -21,7 +21,7 @@ import ( "os" "github.com/kopia/kopia/fs" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) // file is an in-memory implementation of kopia's fs.File @@ -80,13 +80,13 @@ func FileFromEndpoint(name, sourceEndpoint string, permissions os.FileMode) *fil func httpStreamReader(sourceEndpoint string) (ReaderSeekerCloser, error) { req, err := http.NewRequest("GET", sourceEndpoint, nil) if err != nil { - return readCloserWrapper{nil}, errors.Wrap(err, "Failed to generate HTTP request") + return readCloserWrapper{nil}, errkit.Wrap(err, "Failed to generate HTTP request") } client := http.Client{} resp, err := client.Do(req) if err != nil { - return readCloserWrapper{nil}, errors.Wrap(err, "Failed to make HTTP request") + return readCloserWrapper{nil}, errkit.Wrap(err, "Failed to make HTTP request") } return readCloserWrapper{resp.Body}, nil diff --git a/pkg/virtualfs/virtualfs.go b/pkg/virtualfs/virtualfs.go index 2a37a50a41..07a6e81032 100644 --- a/pkg/virtualfs/virtualfs.go +++ b/pkg/virtualfs/virtualfs.go @@ -18,13 +18,13 @@ import ( "os" "strings" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) // NewDirectory returns a virtual FS root directory func NewDirectory(rootName string) (*Directory, error) { if strings.Contains(rootName, "/") { - return nil, errors.New("Root name cannot contain '/'") + return nil, errkit.New("Root name cannot contain '/'") } return &Directory{ dirEntry: dirEntry{