Skip to content

Commit

Permalink
Replace many minor usages of errors with errkit (#3228)
Browse files Browse the repository at this point in the history
Signed-off-by: Eugen Sumin <[email protected]>
  • Loading branch information
e-sumin authored Jan 21, 2025
1 parent 6a67752 commit 6ec4426
Show file tree
Hide file tree
Showing 37 changed files with 204 additions and 200 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ require (
//pinned openshift to release-4.5 branch
github.com/openshift/api v0.0.0-20231222123017-053aee22b4b4
github.com/openshift/client-go v0.0.0-20231221125933-2aa81c72f992
github.com/pkg/errors v0.9.1
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.20.5
github.com/prometheus/client_model v0.6.1
github.com/sirupsen/logrus v1.9.3
Expand Down
20 changes: 10 additions & 10 deletions pkg/aws/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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})

Expand All @@ -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)
Expand All @@ -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
}
Expand All @@ -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
}
4 changes: 2 additions & 2 deletions pkg/aws/ec2/ec2.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/aws/rds/rds.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions pkg/aws/role/role.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions pkg/blueprint/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}
Expand All @@ -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)
}
Expand All @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/chronicle/chronicle_pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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))
}
20 changes: 10 additions & 10 deletions pkg/chronicle/chronicle_push.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand All @@ -151,18 +151,18 @@ 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
}

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)
}
8 changes: 4 additions & 4 deletions pkg/customresource/customresource.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
5 changes: 2 additions & 3 deletions pkg/customresource/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pkg/datamover/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/datamover/repository_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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(
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
Loading

0 comments on commit 6ec4426

Please sign in to comment.