diff --git a/pkg/blockstorage/awsebs/awsebs.go b/pkg/blockstorage/awsebs/awsebs.go index de12211820..b68eb6774f 100644 --- a/pkg/blockstorage/awsebs/awsebs.go +++ b/pkg/blockstorage/awsebs/awsebs.go @@ -18,6 +18,7 @@ package awsebs import ( "context" + "fmt" "net/http" "time" @@ -26,7 +27,7 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/jpillora/backoff" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" awsconfig "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/blockstorage" @@ -71,7 +72,7 @@ func NewProvider(ctx context.Context, config map[string]string) (blockstorage.Pr } ec2Cli, err := newEC2Client(region, awsConfig) if err != nil { - return nil, errors.Wrapf(err, "Could not get EC2 client") + return nil, errkit.Wrap(err, "Could not get EC2 client") } return &EbsStorage{Ec2Cli: ec2Cli, Role: config[awsconfig.ConfigRole], config: awsConfig}, nil } @@ -79,11 +80,11 @@ func NewProvider(ctx context.Context, config map[string]string) (blockstorage.Pr // newEC2Client returns ec2 client struct. func newEC2Client(awsRegion string, config *aws.Config) (*EC2, error) { if config == nil { - return nil, errors.New("Invalid empty AWS config") + return nil, errkit.New("Invalid empty AWS config") } s, err := session.NewSession(config) if err != nil { - return nil, errors.Wrap(err, "Failed to create session for EBS") + return nil, errkit.Wrap(err, "Failed to create session for EBS") } conf := config.WithMaxRetries(maxRetries).WithRegion(awsRegion).WithCredentials(config.Credentials) return &EC2{EC2: ec2.New(s, conf)}, nil @@ -124,17 +125,17 @@ func (s *EbsStorage) CheckVolumeCreate(ctx context.Context) (bool, error) { ec2Cli, err := newEC2Client(*s.config.Region, s.config) if err != nil { - return false, errors.Wrap(err, "Could not get EC2 client") + return false, errkit.Wrap(err, "Could not get EC2 client") } dai := &ec2.DescribeAvailabilityZonesInput{} az, err := ec2Cli.DescribeAvailabilityZones(dai) if err != nil { - return false, errors.New("Fail to get available zone for EC2 client") + return false, errkit.New("Fail to get available zone for EC2 client") } if az != nil { zoneName = az.AvailabilityZones[1].ZoneName } else { - return false, errors.New("No available zone for EC2 client") + return false, errkit.New("No available zone for EC2 client") } cvi := &ec2.CreateVolumeInput{ @@ -144,7 +145,7 @@ func (s *EbsStorage) CheckVolumeCreate(ctx context.Context) (bool, error) { } _, err = s.Ec2Cli.CreateVolume(cvi) if !isDryRunErr(err) { - return false, errors.Wrap(err, "Could not create volume with EC2 client") + return false, errkit.Wrap(err, "Could not create volume with EC2 client") } return true, nil } @@ -159,14 +160,14 @@ func (s *EbsStorage) VolumeGet(ctx context.Context, id string, zone string) (*bl return nil, err } if len(dvo.Volumes) != len(volIDs) { - return nil, errors.New("Object not found") + return nil, errkit.New("Object not found") } vols := dvo.Volumes if len(vols) == 0 { - return nil, errors.New("Volume with volume_id: " + id + " not found") + return nil, errkit.New("Volume with volume_id: " + id + " not found") } if len(vols) > 1 { - return nil, errors.Errorf("Found an unexpected number of volumes: volume_id=%s result_count=%d", id, len(vols)) + return nil, errkit.New(fmt.Sprintf("Found an unexpected number of volumes: volume_id=%s result_count=%d", id, len(vols))) } vol := vols[0] mv := s.volumeParse(ctx, vol) @@ -268,15 +269,15 @@ func (s *EbsStorage) SnapshotsList(ctx context.Context, tags map[string]string) // i.e., copying unencrypted to encrypted snapshot is allowed but not vice versa. func (s *EbsStorage) SnapshotCopy(ctx context.Context, from, to blockstorage.Snapshot) (*blockstorage.Snapshot, error) { if to.Region == "" { - return nil, errors.New("Destination snapshot AvailabilityZone must be specified") + return nil, errkit.New("Destination snapshot AvailabilityZone must be specified") } if to.ID != "" { - return nil, errors.Errorf("Snapshot %v destination ID must be empty", to) + return nil, errkit.New(fmt.Sprintf("Snapshot %v destination ID must be empty", to)) } // Copy operation must be initiated from the destination region. ec2Cli, err := newEC2Client(to.Region, s.Ec2Cli.Config.Copy()) if err != nil { - return nil, errors.Wrapf(err, "Could not get EC2 client") + return nil, errkit.Wrap(err, "Could not get EC2 client") } // Include a presigned URL when the regions are different. Include it // independent of whether or not the snapshot is encrypted. @@ -290,7 +291,7 @@ func (s *EbsStorage) SnapshotCopy(ctx context.Context, from, to blockstorage.Sna rq, _ := ec2Cli.CopySnapshotRequest(&si) su, err2 := rq.Presign(120 * time.Minute) if err2 != nil { - return nil, errors.Wrap(err2, "Could not presign URL for snapshot copy request") + return nil, errkit.Wrap(err2, "Could not presign URL for snapshot copy request") } presignedURL = &su } @@ -316,14 +317,14 @@ func (s *EbsStorage) SnapshotCopy(ctx context.Context, from, to blockstorage.Sna } cso, err := ec2Cli.CopySnapshotWithContext(ctx, &csi) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy snapshot %v", csi) + return nil, errkit.Wrap(err, "Failed to copy snapshot", "snapshot", csi) } snapID := aws.StringValue(cso.SnapshotId) if err = setResourceTags(ctx, ec2Cli, snapID, ktags.GetTags(tags)); err != nil { return nil, err } if err = waitOnSnapshotID(ctx, ec2Cli, snapID); err != nil { - return nil, errors.Wrapf(err, "Snapshot %s did not complete", snapID) + return nil, errkit.Wrap(err, "Snapshot did not complete", "snapshot", snapID) } snaps, err := getSnapshots(ctx, ec2Cli, []*string{aws.String(snapID)}) if err != nil { @@ -341,7 +342,7 @@ func (s *EbsStorage) SnapshotCopy(ctx context.Context, from, to blockstorage.Sna // SnapshotCopyWithArgs is part of blockstorage.Provider func (s *EbsStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage.Snapshot, to blockstorage.Snapshot, args map[string]string) (*blockstorage.Snapshot, error) { - return nil, errors.New("Copy Snapshot with Args not implemented") + return nil, errkit.New("Copy Snapshot with Args not implemented") } // SnapshotCreate is part of blockstorage.Provider @@ -358,7 +359,7 @@ func (s *EbsStorage) SnapshotCreate(ctx context.Context, volume blockstorage.Vol csi.SetDryRun(s.Ec2Cli.DryRun) snap, err := s.Ec2Cli.CreateSnapshotWithContext(ctx, csi) if err != nil && !isDryRunErr(err) { - return nil, errors.Wrapf(err, "Failed to create snapshot, volume_id: %s", *csi.VolumeId) + return nil, errkit.Wrap(err, "Failed to create snapshot", "volume_id", *csi.VolumeId) } region, err := availabilityZoneToRegion(ctx, s.Ec2Cli, volume.Az) @@ -381,7 +382,7 @@ func (s *EbsStorage) SnapshotCreateWaitForCompletion(ctx context.Context, snap * return nil } if err := waitOnSnapshotID(ctx, s.Ec2Cli, snap.ID); err != nil { - return errors.Wrapf(err, "Waiting on snapshot %v", snap) + return errkit.Wrap(err, "Waiting on snapshot", "snapshot", snap) } return nil } @@ -399,7 +400,7 @@ func (s *EbsStorage) SnapshotDelete(ctx context.Context, snapshot *blockstorage. return nil } if err != nil && !isDryRunErr(err) { - return errors.Wrap(err, "Failed to delete snapshot") + return errkit.Wrap(err, "Failed to delete snapshot") } return nil } @@ -431,7 +432,7 @@ func (s *EbsStorage) VolumeDelete(ctx context.Context, volume *blockstorage.Volu return nil } if err != nil && !isDryRunErr(err) { - return errors.Wrapf(err, "Failed to delete volume volID: %s", volume.ID) + return errkit.Wrap(err, "Failed to delete volume", "volID", volume.ID) } return nil } @@ -444,7 +445,7 @@ func (s *EbsStorage) SetTags(ctx context.Context, resource interface{}, tags map case *blockstorage.Snapshot: return setResourceTags(ctx, s.Ec2Cli, res.ID, tags) default: - return errors.Wrapf(nil, "Unknown resource type: %v", res) + return errkit.Wrap(nil, "Unknown resource type", "resourceType", res) } } @@ -452,7 +453,7 @@ func (s *EbsStorage) SetTags(ctx context.Context, resource interface{}, tags map func setResourceTags(ctx context.Context, ec2Cli *EC2, resourceID string, tags map[string]string) error { cti := &ec2.CreateTagsInput{Resources: []*string{&resourceID}, Tags: mapToEC2Tags(tags)} if _, err := ec2Cli.CreateTags(cti); err != nil { - return errors.Wrapf(err, "Failed to set tags, resource_id:%s", resourceID) + return errkit.Wrap(err, "Failed to set tags", "resource_id", resourceID) } return nil } @@ -460,10 +461,10 @@ func setResourceTags(ctx context.Context, ec2Cli *EC2, resourceID string, tags m // VolumeCreateFromSnapshot is part of blockstorage.Provider func (s *EbsStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot blockstorage.Snapshot, tags map[string]string) (*blockstorage.Volume, error) { if snapshot.Volume == nil { - return nil, errors.New("Snapshot volume information not available") + return nil, errkit.New("Snapshot volume information not available") } if snapshot.Volume.VolumeType == "" || snapshot.Volume.Az == "" || snapshot.Volume.Tags == nil { - return nil, errors.Errorf("Required volume fields not available, volumeType: %s, Az: %s, VolumeTags: %v", snapshot.Volume.VolumeType, snapshot.Volume.Az, snapshot.Volume.Tags) + return nil, errkit.New(fmt.Sprintf("Required volume fields not available, volumeType: %s, Az: %s, VolumeTags: %v", snapshot.Volume.VolumeType, snapshot.Volume.Az, snapshot.Volume.Tags)) } kubeCli, err := kube.NewClient() if err != nil { @@ -474,7 +475,7 @@ func (s *EbsStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc return nil, err } if len(zones) != 1 { - return nil, errors.Errorf("Length of zone slice should be 1, got %d", len(zones)) + return nil, errkit.New(fmt.Sprintf("Length of zone slice should be 1, got %d", len(zones))) } cvi := &ec2.CreateVolumeInput{ AvailabilityZone: aws.String(zones[0]), @@ -495,7 +496,7 @@ func (s *EbsStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc volID, err := createVolume(ctx, s.Ec2Cli, cvi, ktags.GetTags(tags)) if err != nil { if isVolNotFoundErr(err) { - return nil, errors.Wrap(err, "This may indicate insufficient permissions for KMS keys.") + return nil, errkit.Wrap(err, "This may indicate insufficient permissions for KMS keys.") } return nil, err } @@ -530,13 +531,13 @@ func getSnapshots(ctx context.Context, ec2Cli *EC2, snapIDs []*string) ([]*ec2.S dsi := &ec2.DescribeSnapshotsInput{SnapshotIds: snapIDs} dso, err := ec2Cli.DescribeSnapshotsWithContext(ctx, dsi) if err != nil { - return nil, errors.Wrapf(err, blockstorage.SnapshotDoesNotExistError+", snapshot_ids: %p", snapIDs) + return nil, errkit.Wrap(err, blockstorage.SnapshotDoesNotExistError+", snapshot_ids: %p", snapIDs) } // TODO: handle paging and continuation if len(dso.Snapshots) != len(snapIDs) { log.Error().Print("Did not find all requested snapshots", field.M{"snapshots_requested": snapIDs, "snapshots_found": dso.Snapshots}) // TODO: Move mapping to HTTP error to the caller - return nil, errors.New(blockstorage.SnapshotDoesNotExistError) + return nil, errkit.New(blockstorage.SnapshotDoesNotExistError) } return dso.Snapshots, nil } @@ -549,11 +550,11 @@ func availabilityZoneToRegion(ctx context.Context, awsCli *EC2, az string) (ar s azo, err := awsCli.DescribeAvailabilityZonesWithContext(ctx, azi) if err != nil { - return "", errors.Wrapf(err, "Could not determine region for availability zone (AZ) %s", az) + return "", errkit.Wrap(err, "Could not determine region for availability zone (AZ)", "az", az) } if len(azo.AvailabilityZones) == 0 { - return "", errors.New("Region unavailable for availability zone" + az) + return "", errkit.New("Region unavailable for availability zone" + az) } return aws.StringValue(azo.AvailabilityZones[0].RegionName), nil @@ -585,11 +586,11 @@ func waitOnVolume(ctx context.Context, ec2Cli *EC2, vol *ec2.Volume) error { return err } if len(dvo.Volumes) != 1 { - return errors.New("Object not found") + return errkit.New("Object not found") } s := dvo.Volumes[0] if *s.State == ec2.VolumeStateError { - return errors.New("Creating EBS volume failed") + return errkit.New("Creating EBS volume failed") } if *s.State == ec2.VolumeStateAvailable { log.Print("Volume creation complete", field.M{"VolumeID": *vol.VolumeId}) @@ -612,14 +613,14 @@ func waitOnSnapshotID(ctx context.Context, ec2Cli *EC2, snapID string) error { return poll.WaitWithBackoff(ctx, snapWaitBackoff, func(ctx context.Context) (bool, error) { dso, err := ec2Cli.DescribeSnapshotsWithContext(ctx, dsi) if err != nil { - return false, errors.Wrapf(err, "Failed to describe snapshot, snapshot_id: %s", snapID) + return false, errkit.Wrap(err, "Failed to describe snapshot", "snapshot_id", snapID) } if len(dso.Snapshots) != 1 { - return false, errors.New(blockstorage.SnapshotDoesNotExistError) + return false, errkit.New(blockstorage.SnapshotDoesNotExistError) } s := dso.Snapshots[0] if *s.State == ec2.SnapshotStateError { - return false, errors.New("Snapshot EBS volume failed") + return false, errkit.New("Snapshot EBS volume failed") } if *s.State == ec2.SnapshotStateCompleted { log.Print("Snapshot completed", field.M{"SnapshotID": snapID}) @@ -644,14 +645,14 @@ func GetRegionFromEC2Metadata() (string, error) { ec2MetaData := ec2metadata.New(session.Must(session.NewSession()), &conf) awsRegion, err := ec2MetaData.Region() - return awsRegion, errors.Wrap(err, "Failed to get AWS Region") + return awsRegion, errkit.Wrap(err, "Failed to get AWS Region") } // FromRegion is part of zone.Mapper func (s *EbsStorage) FromRegion(ctx context.Context, region string) ([]string, error) { ec2Cli, err := newEC2Client(region, s.config) if err != nil { - return nil, errors.Wrapf(err, "Could not get EC2 client while fetching zones FromRegion (%s)", region) + return nil, errkit.Wrap(err, "Could not get EC2 client while fetching zones FromRegion", "region", region) } trueBool := true filterKey := "region-name" @@ -662,7 +663,7 @@ func (s *EbsStorage) FromRegion(ctx context.Context, region string) ([]string, e }, }) if err != nil { - return nil, errors.Wrapf(err, "Failed to get availability zones for region %s", region) + return nil, errkit.Wrap(err, "Failed to get availability zones for region", "region", region) } zoneList := []string{} for _, zone := range zones.AvailabilityZones { @@ -675,7 +676,7 @@ func (s *EbsStorage) GetRegions(ctx context.Context) ([]string, error) { trueBool := true result, err := s.Ec2Cli.DescribeRegions(&ec2.DescribeRegionsInput{AllRegions: &trueBool}) if err != nil { - return nil, errors.Wrap(err, "Failed to describe regions") + return nil, errkit.Wrap(err, "Failed to describe regions") } regions := []string{} @@ -689,10 +690,10 @@ func (s *EbsStorage) GetRegions(ctx context.Context) ([]string, error) { func (s *EbsStorage) SnapshotRestoreTargets(ctx context.Context, snapshot *blockstorage.Snapshot) (global bool, regionsAndZones map[string][]string, err error) { // A few checks from VolumeCreateFromSnapshot if snapshot.Volume == nil { - return false, nil, errors.New("Snapshot volume information not available") + return false, nil, errkit.New("Snapshot volume information not available") } if snapshot.Volume.VolumeType == "" || snapshot.Volume.Az == "" || snapshot.Volume.Tags == nil { - return false, nil, errors.Errorf("Required volume fields not available, volumeType: %s, Az: %s, VolumeTags: %v", snapshot.Volume.VolumeType, snapshot.Volume.Az, snapshot.Volume.Tags) + return false, nil, errkit.New(fmt.Sprintf("Required volume fields not available, volumeType: %s, Az: %s, VolumeTags: %v", snapshot.Volume.VolumeType, snapshot.Volume.Az, snapshot.Volume.Tags)) } // EBS snapshots can only be restored in their region zl, err := s.FromRegion(ctx, snapshot.Region) diff --git a/pkg/blockstorage/azure/auth.go b/pkg/blockstorage/azure/auth.go index 0a6000d99f..b365435e89 100644 --- a/pkg/blockstorage/azure/auth.go +++ b/pkg/blockstorage/azure/auth.go @@ -4,7 +4,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/blockstorage" ) @@ -62,7 +62,7 @@ func NewAzureAuthenticator(config map[string]string) (AzureAuthenticator, error) case isClientCredsAvailable(config): return &ClientSecretAuthenticator{}, nil default: - return nil, errors.New("Fail to get an authenticator for provided creds combination") + return nil, errkit.New("Fail to get an authenticator for provided creds combination") } } @@ -78,13 +78,13 @@ func (m *MsiAuthenticator) Authenticate(config map[string]string) error { // check if MSI endpoint is available clientID, ok := config[blockstorage.AzureClientID] if !ok || clientID == "" { - return errors.New("Failed to fetch azure clientID") + return errkit.New("Failed to fetch azure clientID") } azClientID := azidentity.ClientID(clientID) opts := azidentity.ManagedIdentityCredentialOptions{ID: azClientID} cred, err := azidentity.NewManagedIdentityCredential(&opts) if err != nil { - return errors.Wrap(err, "Failed to create an Azure Managed Identity credential") + return errkit.Wrap(err, "Failed to create an Azure Managed Identity credential") } m.TokenCredential = cred // config passed authentication @@ -102,11 +102,11 @@ func (c *ClientSecretAuthenticator) GetAuthorizer() azcore.TokenCredential { func (c *ClientSecretAuthenticator) Authenticate(creds map[string]string) error { credConfig, err := getCredConfigForAuth(creds) if err != nil { - return errors.Wrap(err, "Failed to get Client Secret config") + return errkit.Wrap(err, "Failed to get Client Secret config") } cred, err := azidentity.NewClientSecretCredential(credConfig.TenantID, credConfig.ClientID, credConfig.ClientSecret, nil) if err != nil { - return errors.Wrap(err, "Failed to create an Azure Client Secret credential") + return errkit.Wrap(err, "Failed to create an Azure Client Secret credential") } c.TokenCredential = cred // creds passed authentication @@ -116,17 +116,17 @@ func (c *ClientSecretAuthenticator) Authenticate(creds map[string]string) error func getCredConfigForAuth(config map[string]string) (ClientCredentialsConfig, error) { tenantID, ok := config[blockstorage.AzureTenantID] if !ok { - return ClientCredentialsConfig{}, errors.New("Cannot get tenantID from config") + return ClientCredentialsConfig{}, errkit.New("Cannot get tenantID from config") } clientID, ok := config[blockstorage.AzureClientID] if !ok { - return ClientCredentialsConfig{}, errors.New("Cannot get clientID from config") + return ClientCredentialsConfig{}, errkit.New("Cannot get clientID from config") } clientSecret, ok := config[blockstorage.AzureClientSecret] if !ok { - return ClientCredentialsConfig{}, errors.New("Cannot get clientSecret from config") + return ClientCredentialsConfig{}, errkit.New("Cannot get clientSecret from config") } credConfig := NewClientCredentialsConfig(clientID, clientSecret, tenantID) diff --git a/pkg/blockstorage/azure/azure_instance_metadata.go b/pkg/blockstorage/azure/azure_instance_metadata.go index 6dafa650f6..eed08e4445 100644 --- a/pkg/blockstorage/azure/azure_instance_metadata.go +++ b/pkg/blockstorage/azure/azure_instance_metadata.go @@ -16,10 +16,11 @@ package azure import ( "encoding/json" + "fmt" "io" "net/http" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" ) const metadataURL = "http://169.254.169.254/metadata/" @@ -109,7 +110,7 @@ func (i *InstanceMetadata) queryMetadataBytes(path, format string) ([]byte, erro return nil, err } if resp.StatusCode != http.StatusOK { - return nil, errors.Errorf("Failed to get instance metadata with statusCode: %d, Path: %s", resp.StatusCode, path) + return nil, errkit.New(fmt.Sprintf("Failed to get instance metadata with statusCode: %d, Path: %s", resp.StatusCode, path)) } defer resp.Body.Close() //nolint:errcheck return io.ReadAll(resp.Body) diff --git a/pkg/blockstorage/azure/azuredisk.go b/pkg/blockstorage/azure/azuredisk.go index 67107d2ba9..24ffe5cb09 100644 --- a/pkg/blockstorage/azure/azuredisk.go +++ b/pkg/blockstorage/azure/azuredisk.go @@ -16,7 +16,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" "github.com/Azure/azure-sdk-for-go/storage" "github.com/gofrs/uuid" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/blockstorage" ktags "github.com/kanisterio/kanister/pkg/blockstorage/tags" @@ -61,12 +61,12 @@ func NewProvider(ctx context.Context, config map[string]string) (blockstorage.Pr func (s *AdStorage) VolumeGet(ctx context.Context, id string, zone string) (*blockstorage.Volume, error) { _, rg, name, err := parseDiskID(id) if err != nil { - return nil, errors.Wrapf(err, "Failed to get info for volume with ID %s", id) + return nil, errkit.Wrap(err, "Failed to get info for volume with ID", "id", id) } diskResponse, err := s.azCli.DisksClient.Get(ctx, rg, name, nil) if err != nil { - return nil, errors.Wrapf(err, "Failed to get volume, volumeID: %s", id) + return nil, errkit.Wrap(err, "Failed to get volume", "volumeID", id) } return s.VolumeParse(ctx, diskResponse.Disk) } @@ -75,7 +75,7 @@ func (s *AdStorage) VolumeCreate(ctx context.Context, volume blockstorage.Volume tags := blockstorage.SanitizeTags(blockstorage.KeyValueToMap(volume.Tags)) diskID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } diskName := fmt.Sprintf(volumeNameFmt, diskID.String()) @@ -87,7 +87,7 @@ func (s *AdStorage) VolumeCreate(ctx context.Context, volume blockstorage.Volume } region, id, err := getLocationInfo(volume.Az) if err != nil { - return nil, errors.Wrapf(err, "Could not get region from zone %s", volume.Az) + return nil, errkit.Wrap(err, "Could not get region from zone", "zone", volume.Az) } // TODO(ilya): figure out how to create SKUed disks createdDisk := armcompute.Disk{ @@ -105,11 +105,11 @@ func (s *AdStorage) VolumeCreate(ctx context.Context, volume blockstorage.Volume pollerResp, err := s.azCli.DisksClient.BeginCreateOrUpdate(ctx, s.azCli.ResourceGroup, diskName, createdDisk, nil) if err != nil { - return nil, errors.Wrapf(err, "Could not create volume %s", diskName) + return nil, errkit.Wrap(err, "Could not create volume", "volume", diskName) } resp, err := pollerResp.PollUntilDone(ctx, nil) if err != nil { - return nil, errors.Wrapf(err, "Volume create %s polling error", diskName) + return nil, errkit.Wrap(err, "Volume create polling error", "volume", diskName) } return s.VolumeParse(ctx, resp.Disk) } @@ -117,18 +117,18 @@ func (s *AdStorage) VolumeCreate(ctx context.Context, volume blockstorage.Volume func (s *AdStorage) VolumeDelete(ctx context.Context, volume *blockstorage.Volume) error { _, rg, name, err := parseDiskID(volume.ID) if err != nil { - return errors.Wrapf(err, "Error in deleting Volume with ID %s", volume.ID) + return errkit.Wrap(err, "Error in deleting Volume with ID", "volumeID", volume.ID) } poller, err := s.azCli.DisksClient.BeginDelete(ctx, rg, name, nil) if err != nil { - return errors.Wrapf(err, "Error in deleting Volume with ID %s", volume.ID) + return errkit.Wrap(err, "Error in deleting Volume with ID", "volumeID", volume.ID) } _, err = poller.PollUntilDone(ctx, nil) - return errors.Wrapf(err, "Error in deleting Volume with ID %s", volume.ID) + return errkit.Wrap(err, "Error in deleting Volume with ID", "volumeID", volume.ID) } func (s *AdStorage) SnapshotCopy(ctx context.Context, from blockstorage.Snapshot, to blockstorage.Snapshot) (*blockstorage.Snapshot, error) { - return nil, errors.New("Copy Snapshot not implemented") + return nil, errkit.New("Copy Snapshot not implemented") } // SnapshotCopyWithArgs func: args map should contain non-empty StorageAccountName(AZURE_MIGRATE_STORAGE_ACCOUNT_NAME) @@ -139,22 +139,22 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. migrateStorageAccount := args[blockstorage.AzureMigrateStorageAccount] migrateStorageKey := args[blockstorage.AzureMigrateStorageKey] if isMigrateStorageAccountorKey(migrateStorageAccount, migrateStorageKey) { - return nil, errors.Errorf("Required args %s and %s for snapshot copy not available", blockstorage.AzureMigrateStorageAccount, blockstorage.AzureMigrateStorageKey) + return nil, errkit.New(fmt.Sprintf("Required args %s and %s for snapshot copy not available", blockstorage.AzureMigrateStorageAccount, blockstorage.AzureMigrateStorageKey)) } storageCli, err := storage.NewBasicClient(migrateStorageAccount, migrateStorageKey) if err != nil { - return nil, errors.Wrap(err, "Cannot get storage service client") + return nil, errkit.Wrap(err, "Cannot get storage service client") } storageAccountID := "/subscriptions/" + s.azCli.SubscriptionID + "/resourceGroups/" + s.azCli.ResourceGroup + "/providers/Microsoft.Storage/storageAccounts/" + migrateStorageAccount _, rg, name, err := parseSnapshotID(from.ID) if err != nil { - return nil, errors.Wrapf(err, "SnapshotsClient.Copy: Failure in parsing snapshot ID %s", from.ID) + return nil, errkit.Wrap(err, "SnapshotsClient.Copy: Failure in parsing snapshot ID", "snapshotID", from.ID) } _, err = s.azCli.SnapshotsClient.Get(ctx, rg, name, nil) if err != nil { - return nil, errors.Wrapf(err, "SnapshotsClient.Copy: Failed to get snapshot with ID %s", from.ID) + return nil, errkit.Wrap(err, "SnapshotsClient.Copy: Failed to get snapshot with ID", "snapshotID", from.ID) } duration := int32(3600) @@ -165,16 +165,16 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. snapshotsGrantAccessPoller, err := s.azCli.SnapshotsClient.BeginGrantAccess(ctx, rg, name, gad, nil) if err != nil { - return nil, errors.Wrapf(err, "Failed to grant read access to snapshot: %s", from.ID) + return nil, errkit.Wrap(err, "Failed to grant read access to", "snapshot", from.ID) } defer s.revokeAccess(ctx, rg, name, from.ID) snapshotGrantRes, err := snapshotsGrantAccessPoller.PollUntilDone(ctx, nil) if err != nil { - return nil, errors.Wrap(err, "SnapshotsClient.Copy failure to grant snapshot access. Snapshot grant access poller failed to pull the result") + return nil, errkit.Wrap(err, "SnapshotsClient.Copy failure to grant snapshot access. Snapshot grant access poller failed to pull the result") } if err != nil { - return nil, errors.Wrap(err, "SnapshotsClient.Copy failure to grant snapshot access") + return nil, errkit.Wrap(err, "SnapshotsClient.Copy failure to grant snapshot access") } blobStorageClient := storageCli.GetBlobService() container := blobStorageClient.GetContainerReference(copyContainerName) @@ -192,11 +192,11 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. } err = blob.Copy(*snapshotGrantRes.AccessSAS, copyOptions) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy disk to blob") + return nil, errkit.Wrap(err, "Failed to copy disk to blob") } snapID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } snapName := fmt.Sprintf(snapshotNameFmt, snapID.String()) createSnap := getSnapshotObject(blob, from, to, snapName, storageAccountID) @@ -207,15 +207,15 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. } createSnapshotPoller, err := s.azCli.SnapshotsClient.BeginCreateOrUpdate(ctx, migrateResourceGroup, snapName, createSnap, nil) if err != nil { - return nil, errors.Wrapf(err, "Failed to copy snapshot from source snapshot %v", from) + return nil, errkit.Wrap(err, "Failed to copy snapshot from source snapshot", "snapshot", from) } createSnapRes, err := createSnapshotPoller.PollUntilDone(ctx, nil) if err != nil { - return nil, errors.Wrap(err, "Poller failed to retrieve snapshot") + return nil, errkit.Wrap(err, "Poller failed to retrieve snapshot") } snap, err := s.SnapshotGet(ctx, blockstorage.StringFromPtr(createSnapRes.ID)) if err != nil { - return nil, errors.Wrapf(err, "Failed to Get Snapshot after create, snaphotName %s", snapName) + return nil, errkit.Wrap(err, "Failed to Get Snapshot after create, snaphotName", "snaphotName", snapName) } *snap.Volume = *from.Volume return snap, nil @@ -226,7 +226,7 @@ func getCopyOptions(ctx context.Context) (*storage.CopyOptions, error) { if t, ok := ctx.Deadline(); ok { time := time.Until(t).Seconds() if time <= 0 { - return nil, errors.New("Context deadline exceeded, cannot copy snapshot") + return nil, errkit.New("Context deadline exceeded, cannot copy snapshot") } copyOptions = &storage.CopyOptions{ Timeout: uint(time), @@ -296,13 +296,13 @@ func deleteBlob(blob *storage.Blob, blobName string) { func (s *AdStorage) SnapshotCreate(ctx context.Context, volume blockstorage.Volume, tags map[string]string) (*blockstorage.Snapshot, error) { snapID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } snapName := fmt.Sprintf(snapshotNameFmt, snapID.String()) tags = blockstorage.SanitizeTags(ktags.GetTags(tags)) region, _, err := getLocationInfo(volume.Az) if err != nil { - return nil, errors.Wrapf(err, "Could not get region from zone %s", volume.Az) + return nil, errkit.Wrap(err, "Could not get region from zone", "zone", volume.Az) } createSnap := armcompute.Snapshot{ Name: blockstorage.StringPtr(snapName), @@ -317,15 +317,15 @@ func (s *AdStorage) SnapshotCreate(ctx context.Context, volume blockstorage.Volu } pollerResp, err := s.azCli.SnapshotsClient.BeginCreateOrUpdate(ctx, s.azCli.ResourceGroup, snapName, createSnap, nil) if err != nil { - return nil, errors.Wrapf(err, "Failed to create snapshot for volume %v", volume) + return nil, errkit.Wrap(err, "Failed to create snapshot for volume", "volume", volume) } resp, err := pollerResp.PollUntilDone(ctx, nil) if err != nil { - return nil, errors.Wrapf(err, "Failed to Get Snapshot after create, snaphotName %s", snapName) + return nil, errkit.Wrap(err, "Failed to Get Snapshot after create, snaphotName", "snaphotName", snapName) } blockSnapshot, err := s.snapshotParse(ctx, resp.Snapshot) if err != nil { - return nil, errors.Wrapf(err, "Failed to Parse Snapshot, snaphotName %s", snapName) + return nil, errkit.Wrap(err, "Failed to Parse Snapshot, snaphotName", "snaphotName", snapName) } blockSnapshot.Volume = &volume @@ -356,7 +356,7 @@ var snapIDRe = regexp.MustCompile(snapshotIDRegEx) func parseDiskID(id string) (subscription string, resourceGroup string, name string, err error) { comps := diskIDRe.FindStringSubmatch(id) if len(comps) != 4 { - return "", "", "", errors.New("Failed to parse Disk ID" + id) + return "", "", "", errkit.New("Failed to parse Disk ID" + id) } return comps[1], comps[2], comps[3], nil } @@ -365,7 +365,7 @@ func parseDiskID(id string) (subscription string, resourceGroup string, name str func parseSnapshotID(id string) (subscription string, resourceGroup string, name string, err error) { comps := snapIDRe.FindStringSubmatch(id) if len(comps) != 4 { - return "", "", "", errors.New("Failed to parse Snapshot ID" + id) + return "", "", "", errkit.New("Failed to parse Snapshot ID" + id) } return comps[1], comps[2], comps[3], nil } @@ -373,27 +373,27 @@ func parseSnapshotID(id string) (subscription string, resourceGroup string, name func (s *AdStorage) SnapshotDelete(ctx context.Context, snapshot *blockstorage.Snapshot) error { _, rg, name, err := parseSnapshotID(snapshot.ID) if err != nil { - return errors.Wrapf(err, "SnapshotClient.Delete: Failure in parsing snapshot ID %s", snapshot.ID) + return errkit.Wrap(err, "SnapshotClient.Delete: Failure in parsing snapshot ID", "snapshotID", snapshot.ID) } poller, err := s.azCli.SnapshotsClient.BeginDelete(ctx, rg, name, nil) if err != nil { - return errors.Wrapf(err, "SnapshotClient.Delete: Failed to delete snapshot with ID %s", snapshot.ID) + return errkit.Wrap(err, "SnapshotClient.Delete: Failed to delete snapshot with ID", "snapshotID", snapshot.ID) } _, err = poller.PollUntilDone(ctx, nil) - return errors.Wrapf(err, "SnapshotClient.Delete: Error while waiting for snapshot with ID %s to get deleted", snapshot.ID) + return errkit.Wrap(err, "SnapshotClient.Delete: Error while waiting for snapshot with ID to get deleted", "snapshotID", snapshot.ID) } func (s *AdStorage) SnapshotGet(ctx context.Context, id string) (*blockstorage.Snapshot, error) { _, rg, name, err := parseSnapshotID(id) if err != nil { - return nil, errors.Wrapf(err, "SnapshotsClient.Get: Failure in parsing snapshot ID %s", id) + return nil, errkit.Wrap(err, "SnapshotsClient.Get: Failure in parsing snapshot ID", "id", id) } snapRes, err := s.azCli.SnapshotsClient.Get(ctx, rg, name, nil) if err != nil { if isNotFoundError(err) { - err = errors.Wrap(err, blockstorage.SnapshotDoesNotExistError) + err = errkit.Wrap(err, blockstorage.SnapshotDoesNotExistError) } - return nil, errors.Wrapf(err, "SnapshotsClient.Get: Failed to get snapshot with ID %s", id) + return nil, errkit.Wrap(err, "SnapshotsClient.Get: Failed to get snapshot with ID", "id", id) } return s.snapshotParse(ctx, snapRes.Snapshot) @@ -402,7 +402,7 @@ func (s *AdStorage) SnapshotGet(ctx context.Context, id string) (*blockstorage.S func (s *AdStorage) VolumeParse(ctx context.Context, volume interface{}) (*blockstorage.Volume, error) { vol, ok := volume.(armcompute.Disk) if !ok { - return nil, errors.New(fmt.Sprintf("Volume is not of type *armcompute.Disk, volume: %v", volume)) + return nil, errkit.New(fmt.Sprintf("Volume is not of type *armcompute.Disk, volume: %v", volume)) // TODO: Fixme } encrypted := false if vol.Properties.EncryptionSettingsCollection != nil && @@ -422,14 +422,14 @@ func (s *AdStorage) VolumeParse(ctx context.Context, volume interface{}) (*block vol.SKU.Name != nil { volumeType = string(*vol.SKU.Name) } else { - return nil, errors.New("Volume type is not available") + return nil, errkit.New("Volume type is not available") } volID := "" if vol.ID != nil { volID = blockstorage.StringFromPtr(vol.ID) } else { - return nil, errors.New("Volume Id is not available") + return nil, errkit.New("Volume Id is not available") } diskSize := int64(0) if vol.Properties != nil && @@ -464,7 +464,7 @@ func (s *AdStorage) SnapshotParse(ctx context.Context, snapshot interface{}) (*b if snap, ok := snapshot.(armcompute.Snapshot); ok { return s.snapshotParse(ctx, snap) } - return nil, errors.New(fmt.Sprintf("Snapshot is not of type *armcompute.Snapshot, snapshot: %v", snapshot)) + return nil, errkit.New(fmt.Sprintf("Snapshot is not of type *armcompute.Snapshot, snapshot: %v", snapshot)) // TODO: Fixme } func (s *AdStorage) snapshotParse(ctx context.Context, snap armcompute.Snapshot) (*blockstorage.Snapshot, error) { @@ -472,7 +472,7 @@ func (s *AdStorage) snapshotParse(ctx context.Context, snap armcompute.Snapshot) if snap.ID != nil { snapID = *snap.ID } else { - return nil, errors.New("Snapshot ID is missing") + return nil, errkit.New("Snapshot ID is missing") } vol := &blockstorage.Volume{ Type: s.Type(), @@ -525,12 +525,12 @@ func (s *AdStorage) VolumesList(ctx context.Context, tags map[string]string, zon for pager.More() { page, err := pager.NextPage(ctx) if err != nil { - return nil, errors.Wrap(err, "DisksClient.List in VolumesList") + return nil, errkit.Wrap(err, "DisksClient.List in VolumesList") } for _, disk := range page.Value { vol, err := s.VolumeParse(ctx, *disk) if err != nil { - return nil, errors.Wrap(err, "DisksClient.List in VolumesList, failure in parsing Volume") + return nil, errkit.Wrap(err, "DisksClient.List in VolumesList, failure in parsing Volume") } vols = append(vols, vol) } @@ -546,7 +546,7 @@ func (s *AdStorage) SnapshotsList(ctx context.Context, tags map[string]string) ( for pager.More() { page, err := pager.NextPage(ctx) if err != nil { - return nil, errors.Wrap(err, "SnapshotsClient.List in SnapshotsList") + return nil, errkit.Wrap(err, "SnapshotsClient.List in SnapshotsList") } for _, snap := range page.Value { k10Snap, err := s.SnapshotParse(ctx, *snap) @@ -577,7 +577,7 @@ func (s *AdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot block diskID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } diskName := fmt.Sprintf(volumeNameFmt, diskID.String()) tags = blockstorage.SanitizeTags(tags) @@ -604,11 +604,11 @@ func (s *AdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot block } poller, err := s.azCli.DisksClient.BeginCreateOrUpdate(ctx, s.azCli.ResourceGroup, diskName, createDisk, nil) if err != nil { - return nil, errors.Wrapf(err, "DiskCLient.CreateOrUpdate in VolumeCreateFromSnapshot, diskName: %s, snapshotID: %s", diskName, snapshot.ID) + return nil, errkit.Wrap(err, "DiskCLient.CreateOrUpdate in VolumeCreateFromSnapshot", "diskName", diskName, "snapshotID", snapshot.ID) } resp, err := poller.PollUntilDone(ctx, nil) if err != nil { - return nil, errors.Wrapf(err, "DiskCLient.CreateOrUpdate in VolumeCreateFromSnapshot, diskName: %s, snapshotID: %s", diskName, snapshot.ID) + return nil, errkit.Wrap(err, "DiskCLient.CreateOrUpdate in VolumeCreateFromSnapshot", "diskName", diskName, "snapshotID", snapshot.ID) } return s.VolumeParse(ctx, resp.Disk) } @@ -632,16 +632,16 @@ func (s *AdStorage) getRegionAndZoneID(ctx context.Context, sourceRegion, volAz return "", "", err } if len(zones) != 1 { - return "", "", errors.Errorf("Length of zone slice should be 1, got %d", len(zones)) + return "", "", errkit.New(fmt.Sprintf("Length of zone slice should be 1, got %d", len(zones))) } region, id, err := getLocationInfo(zones[0]) - return region, id, errors.Wrapf(err, "Could not get region from zone %s", zones[0]) + return region, id, errkit.Wrap(err, "Could not get region from zone", "zone", zones[0]) } func getLocationInfo(az string) (string, string, error) { if az == "" { - return "", "", errors.New("zone value is empty") + return "", "", errkit.New("zone value is empty") } s := strings.Split(az, "-") @@ -665,7 +665,7 @@ func (s *AdStorage) SetTags(ctx context.Context, resource interface{}, tags map[ } snap, err := s.azCli.SnapshotsClient.Get(ctx, rg, name, nil) if err != nil { - return errors.Wrapf(err, "SnapshotsClient.Get in SetTags, snapshotID: %s", res.ID) + return errkit.Wrap(err, "SnapshotsClient.Get in SetTags", "snapshotID", res.ID) } tags = ktags.AddMissingTags(blockstorage.StringMap(snap.Tags), ktags.GetTags(tags)) snapProperties := armcompute.SnapshotUpdate{ @@ -673,10 +673,10 @@ func (s *AdStorage) SetTags(ctx context.Context, resource interface{}, tags map[ } poller, err := s.azCli.SnapshotsClient.BeginUpdate(ctx, rg, name, snapProperties, nil) if err != nil { - return errors.Wrapf(err, "SnapshotsClient.Update in SetTags, snapshotID: %s", name) + return errkit.Wrap(err, "SnapshotsClient.Update in SetTags", "snapshotID", name) } _, err = poller.PollUntilDone(ctx, nil) - return errors.Wrapf(err, "SnapshotsClient.Update in SetTags, snapshotID: %s", name) + return errkit.Wrap(err, "SnapshotsClient.Update in SetTags", "snapshotID", name) } case *blockstorage.Volume: { @@ -686,7 +686,7 @@ func (s *AdStorage) SetTags(ctx context.Context, resource interface{}, tags map[ } vol, err := s.azCli.DisksClient.Get(ctx, rg, volID, nil) if err != nil { - return errors.Wrapf(err, "DiskClient.Get in SetTags, volumeID: %s", volID) + return errkit.Wrap(err, "DiskClient.Get in SetTags", "volumeID", volID) } tags = ktags.AddMissingTags(blockstorage.StringMap(vol.Tags), ktags.GetTags(tags)) @@ -695,24 +695,24 @@ func (s *AdStorage) SetTags(ctx context.Context, resource interface{}, tags map[ } poller, err := s.azCli.DisksClient.BeginUpdate(ctx, rg, volID, diskProperties, nil) if err != nil { - return errors.Wrapf(err, "DiskClient.Update in SetTags, volumeID: %s", volID) + return errkit.Wrap(err, "DiskClient.Update in SetTags", "volumeID", volID) } _, err = poller.PollUntilDone(ctx, nil) - return errors.Wrapf(err, "DiskClient.Update in SetTags, volumeID: %s", volID) + return errkit.Wrap(err, "DiskClient.Update in SetTags", "volumeID", volID) } default: - return errors.New(fmt.Sprintf("Unknown resource type %v", res)) + return errkit.New(fmt.Sprintf("Unknown resource type %v", res)) // TODO: Fixme } } func (s *AdStorage) FromRegion(ctx context.Context, region string) ([]string, error) { regionMap, err := s.dynamicRegionMapAzure(ctx) if err != nil { - return nil, errors.Wrapf(err, "Failed to fetch dynamic region map for region (%s)", region) + return nil, errkit.Wrap(err, "Failed to fetch dynamic region map for region", "region", region) } zones, ok := regionMap[region] if !ok { - return nil, errors.Errorf("Zones for region %s not found", region) + return nil, errkit.New(fmt.Sprintf("Zones for region %s not found", region)) } return zones, nil } @@ -720,7 +720,7 @@ func (s *AdStorage) FromRegion(ctx context.Context, region string) ([]string, er func (s *AdStorage) GetRegions(ctx context.Context) ([]string, error) { regionMap, err := s.dynamicRegionMapAzure(ctx) if err != nil { - return nil, errors.Wrap(err, "Failed to fetch dynamic region map") + return nil, errkit.Wrap(err, "Failed to fetch dynamic region map") } regions := []string{} for region := range regionMap { @@ -732,10 +732,10 @@ func (s *AdStorage) GetRegions(ctx context.Context) ([]string, error) { func (s *AdStorage) SnapshotRestoreTargets(ctx context.Context, snapshot *blockstorage.Snapshot) (global bool, regionsAndZones map[string][]string, err error) { // A few checks from VolumeCreateFromSnapshot if snapshot.Volume == nil { - return false, nil, errors.New("Snapshot volume information not available") + return false, nil, errkit.New("Snapshot volume information not available") } if snapshot.Volume.VolumeType == "" { - return false, nil, errors.Errorf("Required VolumeType not set") + return false, nil, errkit.New("Required VolumeType not set") } zl, err := s.FromRegion(ctx, snapshot.Region) @@ -754,7 +754,7 @@ func (s *AdStorage) dynamicRegionMapAzure(ctx context.Context) (map[string][]str for locationsPager.More() { page, err := locationsPager.NextPage(ctx) if err != nil { - return nil, errors.Wrap(err, "failed to advance page") + return nil, errkit.Wrap(err, "failed to advance page") } for _, location := range page.Value { if location != nil && location.Name != nil { @@ -771,7 +771,7 @@ func (s *AdStorage) dynamicRegionMapAzure(ctx context.Context) (map[string][]str for skusPager.More() { skuResults, err := skusPager.NextPage(ctx) if err != nil { - return nil, errors.Wrap(err, "failed to advance page") + return nil, errkit.Wrap(err, "failed to advance page") } for _, skuResult := range skuResults.Value { if skuResult.Name != nil && skuResult.ResourceType != nil && *skuResult.ResourceType == "disks" { @@ -811,7 +811,7 @@ func (s *AdStorage) mapLocationToZone(skuResult *armcompute.ResourceSKU, regionM func isNotFoundError(err error) bool { var azerr azcore.ResponseError - if errors.As(err, azerr) { + if errkit.As(err, azerr) { return azerr.StatusCode == http.StatusNotFound } return false diff --git a/pkg/blockstorage/azure/client.go b/pkg/blockstorage/azure/client.go index ae8cda499e..4fc69f02b6 100644 --- a/pkg/blockstorage/azure/client.go +++ b/pkg/blockstorage/azure/client.go @@ -23,7 +23,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v4" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/blockstorage" "github.com/kanisterio/kanister/pkg/log" @@ -59,7 +59,7 @@ func NewClient(ctx context.Context, config map[string]string) (*Client, error) { log.Debug().Print("AZURE_RESOURCE_GROUP is not setup") resourceGroup, err = metadata.Text("instance/compute/resourceGroupName") if err != nil { - return nil, errors.Wrap(err, "Cannot get resourceGroup from instance metadata") + return nil, errkit.Wrap(err, "Cannot get resourceGroup from instance metadata") } } @@ -67,7 +67,7 @@ func NewClient(ctx context.Context, config map[string]string) (*Client, error) { log.Debug().Print("AZURE_SUBSCRIPTION_ID is not setup") subscriptionID, err = metadata.Text("instance/compute/subscriptionId") if err != nil { - return nil, errors.Wrap(err, "Cannot get subscriptionID from instance metadata") + return nil, errkit.Wrap(err, "Cannot get subscriptionID from instance metadata") } } diff --git a/pkg/blockstorage/gcepd/gcepd.go b/pkg/blockstorage/gcepd/gcepd.go index bb0beb4722..344c2dc59b 100644 --- a/pkg/blockstorage/gcepd/gcepd.go +++ b/pkg/blockstorage/gcepd/gcepd.go @@ -24,10 +24,10 @@ import ( "strings" "time" - uuid "github.com/gofrs/uuid" + "github.com/gofrs/uuid" "github.com/jpillora/backoff" - "github.com/pkg/errors" - compute "google.golang.org/api/compute/v1" + "github.com/kanisterio/errkit" + "google.golang.org/api/compute/v1" "google.golang.org/api/googleapi" "k8s.io/apimachinery/pkg/util/sets" @@ -114,7 +114,7 @@ func (s *GpdStorage) VolumeCreate(ctx context.Context, volume blockstorage.Volum id, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } createDisk := &compute.Disk{ Name: fmt.Sprintf(volumeNameFmt, id.String()), @@ -177,19 +177,19 @@ func (s *GpdStorage) VolumeDelete(ctx context.Context, volume *blockstorage.Volu // SnapshotCopy is part of blockstorage.Provider func (s *GpdStorage) SnapshotCopy(ctx context.Context, from blockstorage.Snapshot, to blockstorage.Snapshot) (*blockstorage.Snapshot, error) { - return nil, errors.Errorf("Not implemented") + return nil, errkit.New("Not implemented") } // SnapshotCopyWithArgs is part of blockstorage.Provider func (s *GpdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage.Snapshot, to blockstorage.Snapshot, args map[string]string) (*blockstorage.Snapshot, error) { - return nil, errors.New("Copy Snapshot with Args not implemented") + return nil, errkit.New("Copy Snapshot with Args not implemented") } // SnapshotCreate is part of blockstorage.Provider func (s *GpdStorage) SnapshotCreate(ctx context.Context, volume blockstorage.Volume, tags map[string]string) (*blockstorage.Snapshot, error) { rbID, uerr := uuid.NewV1() if uerr != nil { - return nil, errors.Wrap(uerr, "Failed to create UUID") + return nil, errkit.Wrap(uerr, "Failed to create UUID") } rb := &compute.Snapshot{ Name: fmt.Sprintf(snapshotNameFmt, rbID.String()), @@ -237,7 +237,7 @@ func (s *GpdStorage) SnapshotCreate(ctx context.Context, volume blockstorage.Vol // SnapshotCreateWaitForCompletion is part of blockstorage.Provider func (s *GpdStorage) SnapshotCreateWaitForCompletion(ctx context.Context, snap *blockstorage.Snapshot) error { if err := s.waitOnSnapshotID(ctx, snap.ID); err != nil { - return errors.Wrapf(err, "Waiting on snapshot %v", snap) + return errkit.Wrap(err, "Waiting on snapshot", "snapshot", snap) } return nil } @@ -260,7 +260,7 @@ func (s *GpdStorage) SnapshotGet(ctx context.Context, id string) (*blockstorage. snap, err := s.service.Snapshots.Get(s.project, id).Context(ctx).Do() if err != nil { if isNotFoundError(err) { - return nil, errors.Wrap(err, blockstorage.SnapshotDoesNotExistError) + return nil, errkit.Wrap(err, blockstorage.SnapshotDoesNotExistError) } return nil, err } @@ -322,7 +322,7 @@ func (s *GpdStorage) VolumesList(ctx context.Context, tags map[string]string, zo if isMultiZone(zone) { region, err := getRegionFromZones(zone) if err != nil { - return nil, errors.Wrapf(err, "Could not get region from zones %s", zone) + return nil, errkit.Wrap(err, "Could not get region from zones", "zones", zone) } req := s.service.RegionDisks.List(s.project, region).Filter(fltrs) if err := req.Pages(ctx, func(page *compute.DiskList) error { @@ -374,7 +374,7 @@ func (s *GpdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc } if snapshot.Volume.VolumeType == "" || snapshot.Volume.Az == "" { - return nil, errors.Errorf("Required volume fields not available, volumeType: %s, Az: %s", snapshot.Volume.VolumeType, snapshot.Volume.Az) + return nil, errkit.New(fmt.Sprintf("Required volume fields not available, volumeType: %s, Az: %s", snapshot.Volume.VolumeType, snapshot.Volume.Az)) } // Incorporate pre-existing tags if overrides don't already exist @@ -386,7 +386,7 @@ func (s *GpdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc } createDiskID, err := uuid.NewV1() if err != nil { - return nil, errors.Wrap(err, "Failed to create UUID") + return nil, errkit.Wrap(err, "Failed to create UUID") } createDisk := &compute.Disk{ Name: fmt.Sprintf(volumeNameFmt, createDiskID.String()), @@ -401,7 +401,7 @@ func (s *GpdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc var region string // Validate Zones if region, err = getRegionFromZones(snapshot.Volume.Az); err != nil { - return nil, errors.Wrapf(err, "Could not validate zones: %s", snapshot.Volume.Az) + return nil, errkit.Wrap(err, "Could not validate", "zones", snapshot.Volume.Az) } kubeCli, err := kube.NewClient() if err != nil { @@ -432,7 +432,7 @@ func (s *GpdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot bloc resp, err = s.service.RegionDisks.Insert(s.project, region, createDisk).Context(ctx).Do() } if err != nil { - return nil, errors.Wrapf(err, "Failed to create volume from snapshot") + return nil, errkit.Wrap(err, "Failed to create volume from snapshot") } if err = s.waitOnOperation(ctx, resp, volZone); err != nil { @@ -501,7 +501,7 @@ func (s *GpdStorage) SetTags(ctx context.Context, resource interface{}, tags map return s.waitOnOperation(ctx, op, res.Az) } default: - return errors.Errorf("Unknown resource type %v (%T)", res, res) + return errkit.New(fmt.Sprintf("Unknown resource type %v (%T)", res, res)) } } @@ -537,9 +537,9 @@ func (s *GpdStorage) waitOnOperation(ctx context.Context, op *compute.Operation, if op.Error != nil { errJSON, merr := op.Error.MarshalJSON() if merr != nil { - return false, errors.Errorf("Operation %s failed. Failed to marshal error string with error %s", op.OperationType, merr) + return false, errkit.New(fmt.Sprintf("Operation %s failed. Failed to marshal error string with error %s", op.OperationType, merr)) } - return false, errors.Errorf("%s", errJSON) + return false, errkit.New(string(errJSON)) } log.Print("Operation done", field.M{"OperationType": op.OperationType}) return true, nil @@ -547,7 +547,7 @@ func (s *GpdStorage) waitOnOperation(ctx context.Context, op *compute.Operation, log.Debug().Print("Operation status update", field.M{"Operation": op.OperationType, "Status": op.Status, "Status message": op.StatusMessage, "Progress": op.Progress}) return false, nil default: - return false, errors.Errorf("Unknown operation status") + return false, errkit.New("Unknown operation status") } }) } @@ -563,10 +563,10 @@ func (s *GpdStorage) waitOnSnapshotID(ctx context.Context, id string) error { return poll.WaitWithBackoff(ctx, snapWaitBackoff, func(ctx context.Context) (bool, error) { snap, err := s.service.Snapshots.Get(s.project, id).Context(ctx).Do() if err != nil { - return false, errors.Wrapf(err, "Snapshot not found") + return false, errkit.Wrap(err, "Snapshot not found") } if snap.Status == "FAILED" { - return false, errors.New("Snapshot GCP volume failed") + return false, errkit.New("Snapshot GCP volume failed") } if snap.Status == "READY" { log.Print("Snapshot completed", field.M{"SnapshotID": id}) @@ -589,7 +589,7 @@ func isNotFoundError(err error) bool { func (s *GpdStorage) FromRegion(ctx context.Context, region string) ([]string, error) { rtzMap, err := s.dynamicRegionToZoneMap(ctx) if err != nil { - return nil, errors.Wrapf(err, "Failed to get region to zone map for region (%s)", region) + return nil, errkit.Wrap(err, "Failed to get region to zone map for region", "region", region) } zones, ok := rtzMap[region] if !ok { @@ -601,7 +601,7 @@ func (s *GpdStorage) FromRegion(ctx context.Context, region string) ([]string, e func (s *GpdStorage) GetRegions(ctx context.Context) ([]string, error) { regionMap, err := s.dynamicRegionToZoneMap(ctx) if err != nil { - return nil, errors.Wrap(err, "Failed to fetch dynamic region map") + return nil, errkit.Wrap(err, "Failed to fetch dynamic region map") } regions := []string{} for region := range regionMap { @@ -641,18 +641,18 @@ func getRegionFromZones(az string) (string, error) { zones := splitZones(az) regions := sets.Set[string]{} if len(zones) < 1 { - return "", errors.Errorf("no zones specified, zone: %s", az) + return "", errkit.New(fmt.Sprintf("no zones specified, zone: %s", az)) } for _, zone := range zones { // Expected format of zone: {locale}-{region}-{zone} splitZone := strings.Split(zone, "-") if len(splitZone) != 3 { - return "", errors.Errorf("zone in unexpected format, expected: {locale}-{region}-{zone}, got: %v", zone) + return "", errkit.New(fmt.Sprintf("zone in unexpected format, expected: {locale}-{region}-{zone}, got: %v", zone)) } regions.Insert(strings.Join(splitZone[0:2], "-")) } if regions.Len() != 1 { - return "", errors.Errorf("multiple or no regions gotten from zones, got: %v", regions) + return "", errkit.New(fmt.Sprintf("multiple or no regions gotten from zones, got: %v", regions)) } return regions.UnsortedList()[0], nil } @@ -662,7 +662,7 @@ func (s *GpdStorage) getSelfLinks(ctx context.Context, zones []string) ([]string for i, zone := range zones { replicaZone, err := s.service.Zones.Get(s.project, zone).Context(ctx).Do() if err != nil { - return nil, errors.Wrapf(err, "Could not get Zone %s", zone) + return nil, errkit.Wrap(err, "Could not get Zone", "zone", zone) } selfLinks[i] = replicaZone.SelfLink } diff --git a/pkg/blockstorage/getter/getter.go b/pkg/blockstorage/getter/getter.go index 150e4857eb..1ee90a739e 100644 --- a/pkg/blockstorage/getter/getter.go +++ b/pkg/blockstorage/getter/getter.go @@ -16,8 +16,9 @@ package getter import ( "context" + "fmt" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" "github.com/kanisterio/kanister/pkg/blockstorage" "github.com/kanisterio/kanister/pkg/blockstorage/awsebs" @@ -49,7 +50,7 @@ func (*getter) Get(storageType blockstorage.Type, config map[string]string) (blo case blockstorage.TypeAD: return azure.NewProvider(context.Background(), config) default: - return nil, errors.Errorf("Unsupported storage type %v", storageType) + return nil, errkit.New(fmt.Sprintf("Unsupported storage type %v", storageType)) } } diff --git a/pkg/blockstorage/zone/zone.go b/pkg/blockstorage/zone/zone.go index 841ca182e7..e418c12ff5 100644 --- a/pkg/blockstorage/zone/zone.go +++ b/pkg/blockstorage/zone/zone.go @@ -16,11 +16,12 @@ package zone import ( "context" + "fmt" "hash/fnv" "sort" "strings" - "github.com/pkg/errors" + "github.com/kanisterio/errkit" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -48,7 +49,7 @@ func FromSourceRegionZone(ctx context.Context, m Mapper, kubeCli kubernetes.Inte if len(newZones) == 0 { validZoneNames, err := m.FromRegion(ctx, sourceRegion) if err != nil || len(validZoneNames) == 0 { - return nil, errors.Wrapf(err, "No provider zones for region (%s)", sourceRegion) + return nil, errkit.Wrap(err, "No provider zones for region", "region", sourceRegion) } for _, zone := range sourceZones { if isZoneValid(zone, validZoneNames) { @@ -57,7 +58,7 @@ func FromSourceRegionZone(ctx context.Context, m Mapper, kubeCli kubernetes.Inte } } if len(newZones) == 0 { - return nil, errors.Errorf("Unable to find valid availability zones for region (%s)", sourceRegion) + return nil, errkit.New(fmt.Sprintf("Unable to find valid availability zones for region (%s)", sourceRegion)) } var zones []string for z := range newZones { @@ -155,11 +156,11 @@ const ( // NodeZonesAndRegion returns cloud provider failure-domain region and zones as reported by K8s func NodeZonesAndRegion(ctx context.Context, cli kubernetes.Interface) (map[string]struct{}, string, error) { if cli == nil { - return nil, "", errors.New(nodeZonesErr) + return nil, "", errkit.New(nodeZonesErr) } ns, err := GetReadySchedulableNodes(cli) if err != nil { - return nil, "", errors.Wrap(err, nodeZonesErr) + return nil, "", errkit.Wrap(err, nodeZonesErr) } zoneSet := make(map[string]struct{}) regionSet := make(map[string]struct{}) @@ -177,10 +178,10 @@ func NodeZonesAndRegion(ctx context.Context, cli kubernetes.Interface) (map[stri } } if len(regionSet) > 1 { - return nil, "", errors.New("Multiple failure domain regions found") + return nil, "", errkit.New("Multiple failure domain regions found") } if len(regionSet) == 0 { - return nil, "", errors.New("No failure domain regions found") + return nil, "", errkit.New("No failure domain regions found") } var region []string for r := range regionSet { @@ -214,7 +215,7 @@ func GetReadySchedulableNodes(cli kubernetes.Interface) ([]corev1.Node, error) { } log.Info().Print("Available nodes status", field.M{"total": total, "unschedulable": unschedulable, "notReady": notReady}) if len(l) == 0 { - return nil, errors.New("There are currently no ready, schedulable nodes in the cluster") + return nil, errkit.New("There are currently no ready, schedulable nodes in the cluster") } return l, nil }