From 458e352a2b3570480e5425dfb1bc68fd52720191 Mon Sep 17 00:00:00 2001 From: Eddie Torres Date: Mon, 31 Oct 2022 20:45:29 +0000 Subject: [PATCH] Upgrade golangci-lint; Fix linter errors Signed-off-by: Eddie Torres --- Makefile | 2 +- go.mod | 4 +- pkg/cloud/cloud.go | 60 ++++++++-------- pkg/cloud/cloud_test.go | 5 +- pkg/cloud/metadata_ec2.go | 12 ++-- pkg/cloud/metadata_k8s.go | 2 +- pkg/driver/controller.go | 70 ++++++++----------- pkg/driver/controller_test.go | 2 +- pkg/driver/driver.go | 2 +- pkg/driver/mount.go | 2 - pkg/driver/mount_linux.go | 21 ++---- pkg/driver/mount_test.go | 12 ++-- pkg/driver/node.go | 23 +++--- pkg/driver/node_linux.go | 18 ++--- pkg/driver/sanity_test.go | 3 +- pkg/driver/validation.go | 6 +- pkg/driver/validation_test.go | 4 +- pkg/util/util.go | 4 +- ...ically_provisioned_resize_volume_tester.go | 2 +- .../pre_provisioned_snapshot_volume_tester.go | 6 -- tests/e2e/testsuites/testsuites.go | 13 ++-- tests/integration/integration_test.go | 9 +-- tests/integration/setup_test.go | 3 +- 23 files changed, 123 insertions(+), 162 deletions(-) diff --git a/Makefile b/Makefile index 6571fb74d5..d5bec4a9e6 100644 --- a/Makefile +++ b/Makefile @@ -127,7 +127,7 @@ bin/mockgen: | bin bin/golangci-lint: | bin echo "Installing golangci-lint..." - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.21.0 + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.50.1 .PHONY: kubeval kubeval: bin/kubeval diff --git a/go.mod b/go.mod index d9a9cb9587..995dd6fc84 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,6 @@ require ( github.com/aws/aws-sdk-go v1.44.122 github.com/container-storage-interface/spec v1.6.0 github.com/golang/mock v1.6.0 - github.com/golang/protobuf v1.5.2 github.com/google/go-cmp v0.5.9 github.com/kubernetes-csi/csi-proxy/client v1.1.2 github.com/kubernetes-csi/csi-test v2.2.0+incompatible @@ -14,6 +13,7 @@ require ( github.com/stretchr/testify v1.8.1 golang.org/x/sys v0.1.0 google.golang.org/grpc v1.50.1 + google.golang.org/protobuf v1.28.1 k8s.io/api v0.25.3 k8s.io/apimachinery v0.25.3 k8s.io/client-go v1.22.11 @@ -43,6 +43,7 @@ require ( github.com/go-openapi/swag v0.22.3 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.2 // indirect github.com/google/gnostic v0.6.9 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.3.0 // indirect @@ -91,7 +92,6 @@ require ( golang.org/x/tools v0.2.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71 // indirect - google.golang.org/protobuf v1.28.1 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/pkg/cloud/cloud.go b/pkg/cloud/cloud.go index b3e0b0b5ec..e9c4e128d9 100644 --- a/pkg/cloud/cloud.go +++ b/pkg/cloud/cloud.go @@ -359,11 +359,10 @@ func (c *cloud) CreateDisk(ctx context.Context, volumeName string, diskOptions * zone := diskOptions.AvailabilityZone if zone == "" { - var err error zone, err = c.randomAvailabilityZone(ctx) klog.V(5).Infof("[Debug] AZ is not provided. Using node AZ [%s]", zone) if err != nil { - return nil, fmt.Errorf("failed to get availability zone %s", err) + return nil, fmt.Errorf("failed to get availability zone %w", err) } } @@ -410,7 +409,7 @@ func (c *cloud) CreateDisk(ctx context.Context, volumeName string, diskOptions * if isAWSErrorIdempotentParameterMismatch(err) { return nil, ErrIdempotentParameterMismatch } - return nil, fmt.Errorf("could not create volume in EC2: %v", err) + return nil, fmt.Errorf("could not create volume in EC2: %w", err) } volumeID := aws.StringValue(response.VolumeId) @@ -431,7 +430,7 @@ func (c *cloud) CreateDisk(ctx context.Context, volumeName string, diskOptions * } else { klog.V(5).Infof("[Debug] %v is deleted because it is not in desired state within retry limit", volumeID) } - return nil, fmt.Errorf("failed to get an available volume in EC2: %v", err) + return nil, fmt.Errorf("failed to get an available volume in EC2: %w", err) } outpostArn := aws.StringValue(response.OutpostArn) @@ -450,7 +449,7 @@ func (c *cloud) CreateDisk(ctx context.Context, volumeName string, diskOptions * } else { klog.V(5).Infof("[Debug] %v is deleted because there was an error while attaching the tags", volumeID) } - return nil, fmt.Errorf("could not attach tags to volume: %v. %v", volumeID, err) + return nil, fmt.Errorf("could not attach tags to volume: %v. %w", volumeID, err) } } return &Disk{CapacityGiB: size, VolumeID: volumeID, AvailabilityZone: zone, SnapshotID: snapshotID, OutpostArn: outpostArn}, nil @@ -462,7 +461,7 @@ func (c *cloud) DeleteDisk(ctx context.Context, volumeID string) (bool, error) { if isAWSErrorVolumeNotFound(err) { return false, ErrNotFound } - return false, fmt.Errorf("DeleteDisk could not delete volume: %v", err) + return false, fmt.Errorf("DeleteDisk could not delete volume: %w", err) } return true, nil } @@ -486,17 +485,17 @@ func (c *cloud) AttachDisk(ctx context.Context, volumeID, nodeID string) (string VolumeId: aws.String(volumeID), } - resp, err := c.ec2.AttachVolumeWithContext(ctx, request) - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { + resp, attachErr := c.ec2.AttachVolumeWithContext(ctx, request) + if attachErr != nil { + var awsErr awserr.Error + if errors.As(attachErr, &awsErr) { if awsErr.Code() == "VolumeInUse" { return "", ErrVolumeInUse } } - return "", fmt.Errorf("could not attach volume %q to node %q: %v", volumeID, nodeID, err) + return "", fmt.Errorf("could not attach volume %q to node %q: %w", volumeID, nodeID, attachErr) } klog.V(5).Infof("[Debug] AttachVolume volume=%q instance=%q request returned %v", volumeID, nodeID, resp) - } attachment, err := c.WaitForAttachmentState(ctx, volumeID, volumeAttachedState, *instance.InstanceId, device.Path, device.IsAlreadyAssigned) @@ -557,7 +556,7 @@ func (c *cloud) DetachDisk(ctx context.Context, volumeID, nodeID string) error { isAWSErrorVolumeNotFound(err) { return ErrNotFound } - return fmt.Errorf("could not detach volume %q from node %q: %v", volumeID, nodeID, err) + return fmt.Errorf("could not detach volume %q from node %q: %w", volumeID, nodeID, err) } attachment, err := c.WaitForAttachmentState(ctx, volumeID, volumeDetachedState, *instance.InstanceId, "", false) @@ -756,7 +755,7 @@ func (c *cloud) CreateSnapshot(ctx context.Context, volumeID string, snapshotOpt res, err := c.ec2.CreateSnapshotWithContext(ctx, request) if err != nil { - return nil, fmt.Errorf("error creating snapshot of volume %s: %v", volumeID, err) + return nil, fmt.Errorf("error creating snapshot of volume %s: %w", volumeID, err) } if res == nil { return nil, fmt.Errorf("nil CreateSnapshotResponse") @@ -773,7 +772,7 @@ func (c *cloud) DeleteSnapshot(ctx context.Context, snapshotID string) (success if isAWSErrorSnapshotNotFound(err) { return false, ErrNotFound } - return false, fmt.Errorf("DeleteSnapshot could not delete volume: %v", err) + return false, fmt.Errorf("DeleteSnapshot could not delete volume: %w", err) } return true, nil } @@ -913,7 +912,7 @@ func (c *cloud) getInstance(ctx context.Context, nodeID string) (*ec2.Instance, if isAWSErrorInstanceNotFound(err) { return nil, ErrNotFound } - return nil, fmt.Errorf("error listing AWS instances: %q", err) + return nil, fmt.Errorf("error listing AWS instances: %w", err) } for _, reservation := range response.Reservations { @@ -1017,8 +1016,9 @@ func (c *cloud) waitForVolume(ctx context.Context, volumeID string) error { // and has the given code. More information on AWS error codes at: // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html func isAWSError(err error, code string) bool { - if awsError, ok := err.(awserr.Error); ok { - if awsError.Code() == code { + var awsErr awserr.Error + if errors.As(err, &awsErr) { + if awsErr.Code() == code { return true } } @@ -1095,7 +1095,7 @@ func (c *cloud) ResizeDisk(ctx context.Context, volumeID string, newSizeBytes in if latestMod != nil && modFetchError == nil { state := aws.StringValue(latestMod.ModificationState) if state == ec2.VolumeModificationStateModifying { - _, err = c.waitForVolumeSize(ctx, volumeID) + err = c.waitForVolumeSize(ctx, volumeID) if err != nil { return oldSizeGiB, err } @@ -1105,16 +1105,16 @@ func (c *cloud) ResizeDisk(ctx context.Context, volumeID string, newSizeBytes in // if there was an error fetching volume modifications and it was anything other than VolumeNotBeingModified error // that means we have an API problem. - if modFetchError != nil && modFetchError != VolumeNotBeingModified { - return oldSizeGiB, fmt.Errorf("error fetching volume modifications for %q: %v", volumeID, modFetchError) + if modFetchError != nil && !errors.Is(modFetchError, VolumeNotBeingModified) { + return oldSizeGiB, fmt.Errorf("error fetching volume modifications for %q: %w", volumeID, modFetchError) } // Even if existing volume size is greater than user requested size, we should ensure that there are no pending // volume modifications objects or volume has completed previously issued modification request. if oldSizeGiB >= newSizeGiB { klog.V(5).Infof("[Debug] Volume %q current size (%d GiB) is greater or equal to the new size (%d GiB)", volumeID, oldSizeGiB, newSizeGiB) - _, err = c.waitForVolumeSize(ctx, volumeID) - if err != nil && err != VolumeNotBeingModified { + err = c.waitForVolumeSize(ctx, volumeID) + if err != nil && !errors.Is(err, VolumeNotBeingModified) { return oldSizeGiB, err } return oldSizeGiB, nil @@ -1128,7 +1128,7 @@ func (c *cloud) ResizeDisk(ctx context.Context, volumeID string, newSizeBytes in klog.V(4).Infof("expanding volume %q to size %d", volumeID, newSizeGiB) response, err := c.ec2.ModifyVolumeWithContext(ctx, req) if err != nil { - return 0, fmt.Errorf("could not modify AWS volume %q: %v", volumeID, err) + return 0, fmt.Errorf("could not modify AWS volume %q: %w", volumeID, err) } mod := response.VolumeModification @@ -1138,7 +1138,7 @@ func (c *cloud) ResizeDisk(ctx context.Context, volumeID string, newSizeBytes in return c.checkDesiredSize(ctx, volumeID, newSizeGiB) } - _, err = c.waitForVolumeSize(ctx, volumeID) + err = c.waitForVolumeSize(ctx, volumeID) if err != nil { return oldSizeGiB, err } @@ -1167,15 +1167,14 @@ func (c *cloud) checkDesiredSize(ctx context.Context, volumeID string, newSizeGi return oldSizeGiB, fmt.Errorf("volume %q is still being expanded to %d size", volumeID, newSizeGiB) } -// waitForVolumeSize waits for a volume modification to finish and return its size. -func (c *cloud) waitForVolumeSize(ctx context.Context, volumeID string) (int64, error) { +// waitForVolumeSize waits for a volume modification to finish. +func (c *cloud) waitForVolumeSize(ctx context.Context, volumeID string) error { backoff := wait.Backoff{ Duration: volumeModificationDuration, Factor: volumeModificationWaitFactor, Steps: volumeModificationWaitSteps, } - var modVolSizeGiB int64 waitErr := wait.ExponentialBackoff(backoff, func() (bool, error) { m, err := c.getLatestVolumeModification(ctx, volumeID) if err != nil { @@ -1184,7 +1183,6 @@ func (c *cloud) waitForVolumeSize(ctx context.Context, volumeID string) (int64, state := aws.StringValue(m.ModificationState) if volumeModificationDone(state) { - modVolSizeGiB = aws.Int64Value(m.TargetSize) return true, nil } @@ -1192,10 +1190,10 @@ func (c *cloud) waitForVolumeSize(ctx context.Context, volumeID string) (int64, }) if waitErr != nil { - return 0, waitErr + return waitErr } - return modVolSizeGiB, nil + return nil } // getLatestVolumeModification returns the last modification of the volume. @@ -1210,7 +1208,7 @@ func (c *cloud) getLatestVolumeModification(ctx context.Context, volumeID string if isAWSErrorModificationNotFound(err) { return nil, VolumeNotBeingModified } - return nil, fmt.Errorf("error describing modifications in volume %q: %v", volumeID, err) + return nil, fmt.Errorf("error describing modifications in volume %q: %w", volumeID, err) } volumeMods := mod.VolumesModifications diff --git a/pkg/cloud/cloud_test.go b/pkg/cloud/cloud_test.go index 15f6a7ae87..5b21b7ca22 100644 --- a/pkg/cloud/cloud_test.go +++ b/pkg/cloud/cloud_test.go @@ -1582,8 +1582,9 @@ func TestListSnapshots(t *testing.T) { mockEC2.EXPECT().DescribeSnapshotsWithContext(gomock.Eq(ctx), gomock.Any()).Return(&ec2.DescribeSnapshotsOutput{}, nil) - if _, err := c.ListSnapshots(ctx, "", 0, ""); err != nil { - if err != ErrNotFound { + _, err := c.ListSnapshots(ctx, "", 0, "") + if err != nil { + if !errors.Is(err, ErrNotFound) { t.Fatalf("Expected error %v, got %v", ErrNotFound, err) } } else { diff --git a/pkg/cloud/metadata_ec2.go b/pkg/cloud/metadata_ec2.go index f2c6c7bdaf..5765778a33 100644 --- a/pkg/cloud/metadata_ec2.go +++ b/pkg/cloud/metadata_ec2.go @@ -24,7 +24,7 @@ func EC2MetadataInstanceInfo(svc EC2Metadata, regionFromSession string) (*Metada doc, err := svc.GetInstanceIdentityDocument() klog.Infof("regionFromSession %v", regionFromSession) if err != nil { - return nil, fmt.Errorf("could not get EC2 instance identity metadata: %v", err) + return nil, fmt.Errorf("could not get EC2 instance identity metadata: %w", err) } if len(doc.InstanceID) == 0 { @@ -53,7 +53,7 @@ func EC2MetadataInstanceInfo(svc EC2Metadata, regionFromSession string) (*Metada enis, err := svc.GetMetadata(enisEndpoint) if err != nil { - return nil, fmt.Errorf("could not get number of attached ENIs: %v", err) + return nil, fmt.Errorf("could not get number of attached ENIs: %w", err) } // the ENIs should not be empty; if (somehow) it is empty, return an error if enis == "" { @@ -66,11 +66,11 @@ func EC2MetadataInstanceInfo(svc EC2Metadata, regionFromSession string) (*Metada blockDevMappings := 1 if !util.IsSBE(doc.Region) { - mappings, err := svc.GetMetadata(blockDevicesEndpoint) + mappings, mapErr := svc.GetMetadata(blockDevicesEndpoint) // The output contains 1 volume for the AMI. Any other block device contributes to the attachment limit blockDevMappings = strings.Count(mappings, "\n") - if err != nil { - return nil, fmt.Errorf("could not get number of block device mappings: %v", err) + if mapErr != nil { + return nil, fmt.Errorf("could not get number of block device mappings: %w", err) } } @@ -88,7 +88,7 @@ func EC2MetadataInstanceInfo(svc EC2Metadata, regionFromSession string) (*Metada // it's guaranteed to be in the form `arn::outposts:::outpost/` // There's a case to be made here to ignore the error so a failure here wouldn't affect non-outpost calls. if err != nil && !strings.Contains(err.Error(), "404") { - return nil, fmt.Errorf("something went wrong while getting EC2 outpost arn: %s", err.Error()) + return nil, fmt.Errorf("something went wrong while getting EC2 outpost arn: %w", err) } else if err == nil { klog.Infof("Running in an outpost environment with arn: %s", outpostArn) outpostArn = strings.ReplaceAll(outpostArn, "outpost/", "") diff --git a/pkg/cloud/metadata_k8s.go b/pkg/cloud/metadata_k8s.go index 9b307a7fec..1ba84a0990 100644 --- a/pkg/cloud/metadata_k8s.go +++ b/pkg/cloud/metadata_k8s.go @@ -37,7 +37,7 @@ func KubernetesAPIInstanceInfo(clientset kubernetes.Interface) (*Metadata, error // get node with k8s API node, err := clientset.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{}) if err != nil { - return nil, fmt.Errorf("error getting Node %v: %v", nodeName, err) + return nil, fmt.Errorf("error getting Node %v: %w", nodeName, err) } providerID := node.Spec.ProviderID diff --git a/pkg/driver/controller.go b/pkg/driver/controller.go index d2c0c786f1..1019cccde0 100644 --- a/pkg/driver/controller.go +++ b/pkg/driver/controller.go @@ -18,6 +18,7 @@ package driver import ( "context" + "errors" "fmt" "os" "strconv" @@ -25,13 +26,13 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" csi "github.com/container-storage-interface/spec/lib/go/csi" - "github.com/golang/protobuf/ptypes" "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/cloud" "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/driver/internal" "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/util" "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/util/template" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" "k8s.io/klog/v2" ) @@ -229,7 +230,7 @@ func (d *controllerService) CreateVolume(ctx context.Context, req *csi.CreateVol return nil, status.Errorf(codes.InvalidArgument, "Error interpolating the tag value: %v", err) } - if err := validateExtraTags(addTags, d.driverOptions.warnOnInvalidTag); err != nil { + if err = validateExtraTags(addTags, d.driverOptions.warnOnInvalidTag); err != nil { return nil, status.Errorf(codes.InvalidArgument, "Invalid tag value: %v", err) } @@ -256,10 +257,10 @@ func (d *controllerService) CreateVolume(ctx context.Context, req *csi.CreateVol disk, err := d.cloud.CreateDisk(ctx, volName, opts) if err != nil { errCode := codes.Internal - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { errCode = codes.NotFound } - if err == cloud.ErrIdempotentParameterMismatch { + if errors.Is(err, cloud.ErrIdempotentParameterMismatch) { errCode = codes.AlreadyExists } return nil, status.Errorf(errCode, "Could not create volume %q: %v", volName, err) @@ -303,7 +304,7 @@ func (d *controllerService) DeleteVolume(ctx context.Context, req *csi.DeleteVol defer d.inFlight.Delete(volumeID) if _, err := d.cloud.DeleteDisk(ctx, volumeID); err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { klog.V(4).Info("DeleteVolume: volume not found, returning with success") return &csi.DeleteVolumeResponse{}, nil } @@ -334,7 +335,7 @@ func (d *controllerService) ControllerPublishVolume(ctx context.Context, req *cs } disk, err := d.cloud.GetDiskByID(ctx, volumeID) if err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { return nil, status.Error(codes.NotFound, "Volume not found") } return nil, status.Errorf(codes.Internal, "Could not get volume with ID %q: %v", volumeID, err) @@ -343,7 +344,7 @@ func (d *controllerService) ControllerPublishVolume(ctx context.Context, req *cs // If given volumeId already assigned to given node, will directly return current device path devicePath, err := d.cloud.AttachDisk(ctx, volumeID, nodeID) if err != nil { - if err == cloud.ErrVolumeInUse { + if errors.Is(err, cloud.ErrVolumeInUse) { return nil, status.Error(codes.FailedPrecondition, strings.Join(disk.Attachments, ",")) } // TODO: Check volume capability matches for ALREADY_EXISTS @@ -389,7 +390,7 @@ func (d *controllerService) ControllerUnpublishVolume(ctx context.Context, req * nodeID := req.GetNodeId() if err := d.cloud.DetachDisk(ctx, volumeID, nodeID); err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { return &csi.ControllerUnpublishVolumeResponse{}, nil } return nil, status.Errorf(codes.Internal, "Could not detach volume %q from node %q: %v", volumeID, nodeID, err) @@ -450,7 +451,7 @@ func (d *controllerService) ValidateVolumeCapabilities(ctx context.Context, req } if _, err := d.cloud.GetDiskByID(ctx, volumeID); err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { return nil, status.Error(codes.NotFound, "Volume not found") } return nil, status.Errorf(codes.Internal, "Could not get volume with ID %q: %v", volumeID, err) @@ -559,7 +560,7 @@ func (d *controllerService) CreateSnapshot(ctx context.Context, req *csi.CreateS defer d.inFlight.Delete(snapshotName) snapshot, err := d.cloud.GetSnapshotByName(ctx, snapshotName) - if err != nil && err != cloud.ErrNotFound { + if err != nil && !errors.Is(err, cloud.ErrNotFound) { klog.Errorf("Error looking for the snapshot %s: %v", snapshotName, err) return nil, err } @@ -590,7 +591,7 @@ func (d *controllerService) CreateSnapshot(ctx context.Context, req *csi.CreateS return nil, status.Errorf(codes.InvalidArgument, "Error interpolating the tag value: %v", err) } - if err := validateExtraTags(addTags, d.driverOptions.warnOnInvalidTag); err != nil { + if err = validateExtraTags(addTags, d.driverOptions.warnOnInvalidTag); err != nil { return nil, status.Errorf(codes.InvalidArgument, "Invalid tag value: %v", err) } @@ -645,7 +646,7 @@ func (d *controllerService) DeleteSnapshot(ctx context.Context, req *csi.DeleteS defer d.inFlight.Delete(snapshotID) if _, err := d.cloud.DeleteSnapshot(ctx, snapshotID); err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { klog.V(4).Info("DeleteSnapshot: snapshot not found, returning with success") return &csi.DeleteSnapshotResponse{}, nil } @@ -670,20 +671,17 @@ func (d *controllerService) ListSnapshots(ctx context.Context, req *csi.ListSnap if len(snapshotID) != 0 { snapshot, err := d.cloud.GetSnapshotByID(ctx, snapshotID) if err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { klog.V(4).Info("ListSnapshots: snapshot not found, returning with success") return &csi.ListSnapshotsResponse{}, nil } return nil, status.Errorf(codes.Internal, "Could not get snapshot ID %q: %v", snapshotID, err) } snapshots = append(snapshots, snapshot) - if response, err := newListSnapshotsResponse(&cloud.ListSnapshotsResponse{ + response := newListSnapshotsResponse(&cloud.ListSnapshotsResponse{ Snapshots: snapshots, - }); err != nil { - return nil, status.Errorf(codes.Internal, "Could not build ListSnapshotsResponse: %v", err) - } else { - return response, nil - } + }) + return response, nil } volumeID := req.GetSourceVolumeId() @@ -692,20 +690,17 @@ func (d *controllerService) ListSnapshots(ctx context.Context, req *csi.ListSnap cloudSnapshots, err := d.cloud.ListSnapshots(ctx, volumeID, maxEntries, nextToken) if err != nil { - if err == cloud.ErrNotFound { + if errors.Is(err, cloud.ErrNotFound) { klog.V(4).Info("ListSnapshots: snapshot not found, returning with success") return &csi.ListSnapshotsResponse{}, nil } - if err == cloud.ErrInvalidMaxResults { + if errors.Is(err, cloud.ErrInvalidMaxResults) { return nil, status.Errorf(codes.InvalidArgument, "Error mapping MaxEntries to AWS MaxResults: %v", err) } return nil, status.Errorf(codes.Internal, "Could not list snapshots: %v", err) } - response, err := newListSnapshotsResponse(cloudSnapshots) - if err != nil { - return nil, status.Errorf(codes.Internal, "Could not build ListSnapshotsResponse: %v", err) - } + response := newListSnapshotsResponse(cloudSnapshots) return response, nil } @@ -798,10 +793,8 @@ func newCreateVolumeResponse(disk *cloud.Disk) *csi.CreateVolumeResponse { } func newCreateSnapshotResponse(snapshot *cloud.Snapshot) (*csi.CreateSnapshotResponse, error) { - ts, err := ptypes.TimestampProto(snapshot.CreationTime) - if err != nil { - return nil, err - } + ts := timestamppb.New(snapshot.CreationTime) + return &csi.CreateSnapshotResponse{ Snapshot: &csi.Snapshot{ SnapshotId: snapshot.SnapshotID, @@ -813,27 +806,22 @@ func newCreateSnapshotResponse(snapshot *cloud.Snapshot) (*csi.CreateSnapshotRes }, nil } -func newListSnapshotsResponse(cloudResponse *cloud.ListSnapshotsResponse) (*csi.ListSnapshotsResponse, error) { +func newListSnapshotsResponse(cloudResponse *cloud.ListSnapshotsResponse) *csi.ListSnapshotsResponse { var entries []*csi.ListSnapshotsResponse_Entry for _, snapshot := range cloudResponse.Snapshots { - snapshotResponseEntry, err := newListSnapshotsResponseEntry(snapshot) - if err != nil { - return nil, err - } + snapshotResponseEntry := newListSnapshotsResponseEntry(snapshot) entries = append(entries, snapshotResponseEntry) } return &csi.ListSnapshotsResponse{ Entries: entries, NextToken: cloudResponse.NextToken, - }, nil + } } -func newListSnapshotsResponseEntry(snapshot *cloud.Snapshot) (*csi.ListSnapshotsResponse_Entry, error) { - ts, err := ptypes.TimestampProto(snapshot.CreationTime) - if err != nil { - return nil, err - } +func newListSnapshotsResponseEntry(snapshot *cloud.Snapshot) *csi.ListSnapshotsResponse_Entry { + ts := timestamppb.New(snapshot.CreationTime) + return &csi.ListSnapshotsResponse_Entry{ Snapshot: &csi.Snapshot{ SnapshotId: snapshot.SnapshotID, @@ -842,7 +830,7 @@ func newListSnapshotsResponseEntry(snapshot *cloud.Snapshot) (*csi.ListSnapshots CreationTime: ts, ReadyToUse: snapshot.ReadyToUse, }, - }, nil + } } func getVolSizeBytes(req *csi.CreateVolumeRequest) (int64, error) { diff --git a/pkg/driver/controller_test.go b/pkg/driver/controller_test.go index 030450355f..1e704fd3ee 100644 --- a/pkg/driver/controller_test.go +++ b/pkg/driver/controller_test.go @@ -49,7 +49,7 @@ func TestNewControllerService(t *testing.T) { testErr = errors.New("test error") testRegion = "test-region" - getNewCloudFunc = func(expectedRegion string, awsSdkDebugLog bool) func(region string, awsSdkDebugLog bool) (cloud.Cloud, error) { + getNewCloudFunc = func(expectedRegion string, _ bool) func(region string, awsSdkDebugLog bool) (cloud.Cloud, error) { return func(region string, awsSdkDebugLog bool) (cloud.Cloud, error) { if region != expectedRegion { t.Fatalf("expected region %q but got %q", expectedRegion, region) diff --git a/pkg/driver/driver.go b/pkg/driver/driver.go index 1cf0fbb941..f1cfe92c20 100644 --- a/pkg/driver/driver.go +++ b/pkg/driver/driver.go @@ -81,7 +81,7 @@ func NewDriver(options ...func(*DriverOptions)) (*Driver, error) { } if err := ValidateDriverOptions(&driverOptions); err != nil { - return nil, fmt.Errorf("Invalid driver options: %v", err) + return nil, fmt.Errorf("Invalid driver options: %w", err) } driver := Driver{ diff --git a/pkg/driver/mount.go b/pkg/driver/mount.go index 9ff53817c1..d1322ba1eb 100644 --- a/pkg/driver/mount.go +++ b/pkg/driver/mount.go @@ -24,8 +24,6 @@ import ( mountutils "k8s.io/mount-utils" ) -type mountInterface = mountutils.Interface - // Mounter is the interface implemented by NodeMounter. // A mix & match of functions defined in upstream libraries. (FormatAndMount // from struct SafeFormatAndMount, PathExists from an old edition of diff --git a/pkg/driver/mount_linux.go b/pkg/driver/mount_linux.go index 19a8419c9d..a07d26852e 100644 --- a/pkg/driver/mount_linux.go +++ b/pkg/driver/mount_linux.go @@ -75,23 +75,10 @@ func (m *NodeMounter) NeedResize(devicePath string, deviceMountPath string) (boo return mountutils.NewResizeFs(m.Exec).NeedResize(devicePath, deviceMountPath) } -func (m *NodeMounter) getDeviceSize(devicePath string) (uint64, error) { - output, err := m.SafeFormatAndMount.Exec.Command("blockdev", "--getsize64", devicePath).CombinedOutput() - outStr := strings.TrimSpace(string(output)) - if err != nil { - return 0, fmt.Errorf("failed to read size of device %s: %s: %s", devicePath, err, outStr) - } - size, err := strconv.ParseUint(outStr, 10, 64) - if err != nil { - return 0, fmt.Errorf("failed to parse size of device %s %s: %s", devicePath, outStr, err) - } - return size, nil -} - func (m *NodeMounter) getExtSize(devicePath string) (uint64, uint64, error) { output, err := m.SafeFormatAndMount.Exec.Command("dumpe2fs", "-h", devicePath).CombinedOutput() if err != nil { - return 0, 0, fmt.Errorf("failed to read size of filesystem on %s: %s: %s", devicePath, err, string(output)) + return 0, 0, fmt.Errorf("failed to read size of filesystem on %s: %w: %s", devicePath, err, string(output)) } blockSize, blockCount, _ := m.parseFsInfoOutput(string(output), ":", "block size", "block count") @@ -108,7 +95,7 @@ func (m *NodeMounter) getExtSize(devicePath string) (uint64, uint64, error) { func (m *NodeMounter) getXFSSize(devicePath string) (uint64, uint64, error) { output, err := m.SafeFormatAndMount.Exec.Command("xfs_io", "-c", "statfs", devicePath).CombinedOutput() if err != nil { - return 0, 0, fmt.Errorf("failed to read size of filesystem on %s: %s: %s", devicePath, err, string(output)) + return 0, 0, fmt.Errorf("failed to read size of filesystem on %s: %w: %s", devicePath, err, string(output)) } blockSize, blockCount, _ := m.parseFsInfoOutput(string(output), "=", "geom.bsize", "geom.datablocks") @@ -136,13 +123,13 @@ func (m *NodeMounter) parseFsInfoOutput(cmdOutput string, spliter string, blockS if key == blockSizeKey { blockSize, err = strconv.ParseUint(value, 10, 64) if err != nil { - return 0, 0, fmt.Errorf("failed to parse block size %s: %s", value, err) + return 0, 0, fmt.Errorf("failed to parse block size %s: %w", value, err) } } if key == blockCountKey { blockCount, err = strconv.ParseUint(value, 10, 64) if err != nil { - return 0, 0, fmt.Errorf("failed to parse block count %s: %s", value, err) + return 0, 0, fmt.Errorf("failed to parse block count %s: %w", value, err) } } } diff --git a/pkg/driver/mount_test.go b/pkg/driver/mount_test.go index d5aad56e6c..1dc5de8cd4 100644 --- a/pkg/driver/mount_test.go +++ b/pkg/driver/mount_test.go @@ -20,12 +20,12 @@ limitations under the License. package driver import ( - "io/ioutil" - "k8s.io/mount-utils" "os" "path/filepath" "testing" + "k8s.io/mount-utils" + utilexec "k8s.io/utils/exec" fakeexec "k8s.io/utils/exec/testing" ) @@ -316,7 +316,7 @@ func TestNeedResize(t *testing.T) { func TestMakeDir(t *testing.T) { // Setup the full driver and its environment - dir, err := ioutil.TempDir("", "mount-ebs-csi") + dir, err := os.MkdirTemp("", "mount-ebs-csi") if err != nil { t.Fatalf("error creating directory %v", err) } @@ -344,7 +344,7 @@ func TestMakeDir(t *testing.T) { func TestMakeFile(t *testing.T) { // Setup the full driver and its environment - dir, err := ioutil.TempDir("", "mount-ebs-csi") + dir, err := os.MkdirTemp("", "mount-ebs-csi") if err != nil { t.Fatalf("error creating directory %v", err) } @@ -373,7 +373,7 @@ func TestMakeFile(t *testing.T) { func TestPathExists(t *testing.T) { // Setup the full driver and its environment - dir, err := ioutil.TempDir("", "mount-ebs-csi") + dir, err := os.MkdirTemp("", "mount-ebs-csi") if err != nil { t.Fatalf("error creating directory %v", err) } @@ -400,7 +400,7 @@ func TestPathExists(t *testing.T) { func TestGetDeviceName(t *testing.T) { // Setup the full driver and its environment - dir, err := ioutil.TempDir("", "mount-ebs-csi") + dir, err := os.MkdirTemp("", "mount-ebs-csi") if err != nil { t.Fatalf("error creating directory %v", err) } diff --git a/pkg/driver/node.go b/pkg/driver/node.go index 7be7da08aa..9b33f41c15 100644 --- a/pkg/driver/node.go +++ b/pkg/driver/node.go @@ -48,13 +48,6 @@ const ( // default file system type to be used when it is not provided defaultFsType = FSTypeExt4 - // defaultMaxEBSVolumes is the maximum number of volumes that an AWS instance can have attached. - // More info at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/volume_limits.html - defaultMaxEBSVolumes = 39 - - // defaultMaxEBSNitroVolumes is the limit of volumes for some smaller instances, like c5 and m5. - defaultMaxEBSNitroVolumes = 25 - // VolumeOperationAlreadyExists is message fmt returned to CO when there is another in-flight call on the given volumeID VolumeOperationAlreadyExists = "An operation with the given volume=%q is already in progress" @@ -164,7 +157,7 @@ func (d *nodeService) NodeStageVolume(ctx context.Context, req *csi.NodeStageVol mountOptions := collectMountOptions(fsType, mountVolume.MountFlags) - if ok := d.inFlight.Insert(volumeID); !ok { + if ok = d.inFlight.Insert(volumeID); !ok { return nil, status.Errorf(codes.Aborted, VolumeOperationAlreadyExists, volumeID) } defer func() { @@ -203,7 +196,7 @@ func (d *nodeService) NodeStageVolume(ctx context.Context, req *csi.NodeStageVol if !exists { // If target path does not exist we need to create the directory where volume will be staged klog.V(4).Infof("NodeStageVolume: creating target dir %q", target) - if err := d.mounter.MakeDir(target); err != nil { + if err = d.mounter.MakeDir(target); err != nil { msg := fmt.Sprintf("could not create target dir %q: %v", target, err) return nil, status.Error(codes.Internal, msg) } @@ -358,7 +351,7 @@ func (d *nodeService) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandV } // TODO: lock per volume ID to have some idempotency - if _, err := r.Resize(devicePath, volumePath); err != nil { + if _, err = r.Resize(devicePath, volumePath); err != nil { return nil, status.Errorf(codes.Internal, "Could not resize volume %q (%q): %v", volumeID, devicePath, err) } @@ -473,8 +466,8 @@ func (d *nodeService) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVo return nil, status.Errorf(codes.Internal, "failed to determine whether %s is block device: %v", req.VolumePath, err) } if isBlock { - bcap, err := d.getBlockSizeBytes(req.VolumePath) - if err != nil { + bcap, blockErr := d.getBlockSizeBytes(req.VolumePath) + if blockErr != nil { return nil, status.Errorf(codes.Internal, "failed to get block capacity on path %s: %v", req.VolumePath, err) } return &csi.NodeGetVolumeStatsResponse{ @@ -596,14 +589,14 @@ func (d *nodeService) nodePublishVolumeForBlock(req *csi.NodePublishVolumeReques } if !exists { - if err := d.mounter.MakeDir(globalMountPath); err != nil { + if err = d.mounter.MakeDir(globalMountPath); err != nil { return status.Errorf(codes.Internal, "Could not create dir %q: %v", globalMountPath, err) } } // Create the mount point as a file since bind mount device node requires it to be a file klog.V(4).Infof("NodePublishVolume [block]: making target file %s", target) - if err := d.mounter.MakeFile(target); err != nil { + if err = d.mounter.MakeFile(target); err != nil { if removeErr := os.Remove(target); removeErr != nil { return status.Errorf(codes.Internal, "Could not remove mount target %q: %v", target, removeErr) } @@ -633,7 +626,7 @@ func (d *nodeService) nodePublishVolumeForBlock(req *csi.NodePublishVolumeReques // isMounted checks if target is mounted. It does NOT return an error if target // doesn't exist. -func (d *nodeService) isMounted(source string, target string) (bool, error) { +func (d *nodeService) isMounted(_ string, target string) (bool, error) { /* Checking if it's a mount point using IsLikelyNotMountPoint. There are three different return values, 1. true, err when the directory does not exist or corrupted. diff --git a/pkg/driver/node_linux.go b/pkg/driver/node_linux.go index a9b5f056ce..9f8b819091 100644 --- a/pkg/driver/node_linux.go +++ b/pkg/driver/node_linux.go @@ -57,19 +57,19 @@ func (d *nodeService) findDevicePath(devicePath, volumeID, partition string) (st // path below must happen and must rely on volume ID exists, err := d.mounter.PathExists(devicePath) if err != nil { - return "", fmt.Errorf("failed to check if path %q exists: %v", devicePath, err) + return "", fmt.Errorf("failed to check if path %q exists: %w", devicePath, err) } if exists { - stat, err := d.deviceIdentifier.Lstat(devicePath) - if err != nil { - return "", fmt.Errorf("failed to lstat %q: %v", devicePath, err) + stat, lstatErr := d.deviceIdentifier.Lstat(devicePath) + if lstatErr != nil { + return "", fmt.Errorf("failed to lstat %q: %w", devicePath, err) } if stat.Mode()&os.ModeSymlink == os.ModeSymlink { canonicalDevicePath, err = d.deviceIdentifier.EvalSymlinks(devicePath) if err != nil { - return "", fmt.Errorf("failed to evaluate symlink %q: %v", devicePath, err) + return "", fmt.Errorf("failed to evaluate symlink %q: %w", devicePath, err) } } else { canonicalDevicePath = devicePath @@ -126,7 +126,7 @@ func findNvmeVolume(deviceIdentifier DeviceIdentifier, findName string) (device klog.V(5).Infof("[Debug] nvme path %q not found", p) return "", fmt.Errorf("nvme path %q not found", p) } - return "", fmt.Errorf("error getting stat of %q: %v", p, err) + return "", fmt.Errorf("error getting stat of %q: %w", p, err) } if stat.Mode()&os.ModeSymlink != os.ModeSymlink { @@ -137,7 +137,7 @@ func findNvmeVolume(deviceIdentifier DeviceIdentifier, findName string) (device // For example, /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0fab1d5e3f72a5e23 -> ../../nvme2n1 resolved, err := deviceIdentifier.EvalSymlinks(p) if err != nil { - return "", fmt.Errorf("error reading target of symlink %q: %v", p, err) + return "", fmt.Errorf("error reading target of symlink %q: %w", p, err) } if !strings.HasPrefix(resolved, "/dev") { @@ -150,7 +150,7 @@ func findNvmeVolume(deviceIdentifier DeviceIdentifier, findName string) (device func (d *nodeService) preparePublishTarget(target string) error { klog.V(4).Infof("NodePublishVolume: creating dir %s", target) if err := d.mounter.MakeDir(target); err != nil { - return fmt.Errorf("Could not create dir %q: %v", target, err) + return fmt.Errorf("Could not create dir %q: %w", target, err) } return nil } @@ -170,7 +170,7 @@ func (d *nodeService) getBlockSizeBytes(devicePath string) (int64, error) { cmd := d.mounter.(*NodeMounter).Exec.Command("blockdev", "--getsize64", devicePath) output, err := cmd.Output() if err != nil { - return -1, fmt.Errorf("error when getting size of block volume at path %s: output: %s, err: %v", devicePath, string(output), err) + return -1, fmt.Errorf("error when getting size of block volume at path %s: output: %s, err: %w", devicePath, string(output), err) } strOut := strings.TrimSpace(string(output)) gotSizeBytes, err := strconv.ParseInt(strOut, 10, 64) diff --git a/pkg/driver/sanity_test.go b/pkg/driver/sanity_test.go index 46a3ad6d47..58ad7fd929 100644 --- a/pkg/driver/sanity_test.go +++ b/pkg/driver/sanity_test.go @@ -6,7 +6,6 @@ package driver import ( "context" "fmt" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -24,7 +23,7 @@ import ( func TestSanity(t *testing.T) { // Setup the full driver and its environment - dir, err := ioutil.TempDir("", "sanity-ebs-csi") + dir, err := os.MkdirTemp("", "sanity-ebs-csi") if err != nil { t.Fatalf("error creating directory %v", err) } diff --git a/pkg/driver/validation.go b/pkg/driver/validation.go index 8b1db260ce..ca84c784ca 100644 --- a/pkg/driver/validation.go +++ b/pkg/driver/validation.go @@ -27,11 +27,11 @@ import ( func ValidateDriverOptions(options *DriverOptions) error { if err := validateExtraTags(options.extraTags, false); err != nil { - return fmt.Errorf("Invalid extra tags: %v", err) + return fmt.Errorf("Invalid extra tags: %w", err) } if err := validateMode(options.mode); err != nil { - return fmt.Errorf("Invalid mode: %v", err) + return fmt.Errorf("Invalid mode: %w", err) } return nil @@ -84,7 +84,7 @@ func validateExtraTags(tags map[string]string, warnOnly bool) error { err := validate(k, v) if err != nil { if warnOnly { - klog.Warningf("Skipping tag: the following key-value pair is not valid: (%s, %s): (%v)", k, v, err) + klog.Warningf("Skipping tag: the following key-value pair is not valid: (%s, %s): (%w)", k, v, err) } else { return err } diff --git a/pkg/driver/validation_test.go b/pkg/driver/validation_test.go index 2cc8892369..42f85bceac 100644 --- a/pkg/driver/validation_test.go +++ b/pkg/driver/validation_test.go @@ -169,7 +169,7 @@ func TestValidateDriverOptions(t *testing.T) { { name: "fail because validateMode fails", mode: Mode("unknown"), - expErr: fmt.Errorf("Invalid mode: Mode is not supported (actual: unknown, supported: %v)", []Mode{AllMode, ControllerMode, NodeMode}), + expErr: fmt.Errorf("Invalid mode: %w", fmt.Errorf("Mode is not supported (actual: unknown, supported: %v)", []Mode{AllMode, ControllerMode, NodeMode})), }, { name: "fail because validateExtraVolumeTags fails", @@ -177,7 +177,7 @@ func TestValidateDriverOptions(t *testing.T) { extraVolumeTags: map[string]string{ randomString(cloud.MaxTagKeyLength + 1): "extra-tag-value", }, - expErr: fmt.Errorf("Invalid extra tags: Tag key too long (actual: %d, limit: %d)", cloud.MaxTagKeyLength+1, cloud.MaxTagKeyLength), + expErr: fmt.Errorf("Invalid extra tags: %w", fmt.Errorf("Tag key too long (actual: %d, limit: %d)", cloud.MaxTagKeyLength+1, cloud.MaxTagKeyLength)), }, } diff --git a/pkg/util/util.go b/pkg/util/util.go index 4f68a5cc3f..2dc6b25a3c 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -55,7 +55,7 @@ func GiBToBytes(volumeSizeGiB int64) int64 { func ParseEndpoint(endpoint string) (string, string, error) { u, err := url.Parse(endpoint) if err != nil { - return "", "", fmt.Errorf("could not parse endpoint: %v", err) + return "", "", fmt.Errorf("could not parse endpoint: %w", err) } addr := filepath.Join(u.Host, filepath.FromSlash(u.Path)) @@ -66,7 +66,7 @@ func ParseEndpoint(endpoint string) (string, string, error) { case "unix": addr = filepath.Join("/", addr) if err := os.Remove(addr); err != nil && !os.IsNotExist(err) { - return "", "", fmt.Errorf("could not remove unix domain socket %q: %v", addr, err) + return "", "", fmt.Errorf("could not remove unix domain socket %q: %w", addr, err) } default: return "", "", fmt.Errorf("unsupported protocol: %s", scheme) diff --git a/tests/e2e/testsuites/dynamically_provisioned_resize_volume_tester.go b/tests/e2e/testsuites/dynamically_provisioned_resize_volume_tester.go index a2b83d3853..c264467104 100644 --- a/tests/e2e/testsuites/dynamically_provisioned_resize_volume_tester.go +++ b/tests/e2e/testsuites/dynamically_provisioned_resize_volume_tester.go @@ -46,7 +46,7 @@ func (t *DynamicallyProvisionedResizeVolumeTest) Run(client clientset.Interface, defer tpvc.Cleanup() pvcName := tpvc.persistentVolumeClaim.Name - pvc, err := client.CoreV1().PersistentVolumeClaims(namespace.Name).Get(context.TODO(), pvcName, metav1.GetOptions{}) + pvc, _ := client.CoreV1().PersistentVolumeClaims(namespace.Name).Get(context.TODO(), pvcName, metav1.GetOptions{}) By(fmt.Sprintf("Get pvc name: %v", pvc.Name)) originalSize := pvc.Spec.Resources.Requests["storage"] delta := resource.Quantity{} diff --git a/tests/e2e/testsuites/pre_provisioned_snapshot_volume_tester.go b/tests/e2e/testsuites/pre_provisioned_snapshot_volume_tester.go index 7648c0ae3d..b4d2af45f2 100644 --- a/tests/e2e/testsuites/pre_provisioned_snapshot_volume_tester.go +++ b/tests/e2e/testsuites/pre_provisioned_snapshot_volume_tester.go @@ -24,8 +24,6 @@ import ( k8srestclient "k8s.io/client-go/rest" "k8s.io/kubernetes/test/e2e/framework" - awscloud "github.com/kubernetes-sigs/aws-ebs-csi-driver/pkg/cloud" - . "github.com/onsi/ginkgo/v2" ) @@ -34,10 +32,6 @@ type PreProvisionedVolumeSnapshotTest struct { Pod PodDetails } -var ( - tCloud awscloud.Cloud -) - func (t *PreProvisionedVolumeSnapshotTest) Run(client clientset.Interface, restclient k8srestclient.Interface, namespace *v1.Namespace, snapshotId string) { By("taking snapshots") diff --git a/tests/e2e/testsuites/testsuites.go b/tests/e2e/testsuites/testsuites.go index a6218bb4c7..724c4255ad 100644 --- a/tests/e2e/testsuites/testsuites.go +++ b/tests/e2e/testsuites/testsuites.go @@ -183,7 +183,7 @@ func (t *TestVolumeSnapshotClass) CreateStaticVolumeSnapshotContent(snapshotId s func (t *TestVolumeSnapshotClass) UpdateStaticVolumeSnapshotContent(volumeSnapshot *volumesnapshotv1.VolumeSnapshot, volumeSnapshotContent *volumesnapshotv1.VolumeSnapshotContent) { volumeSnapshotContent.Spec.VolumeSnapshotRef.Name = volumeSnapshot.Name - volumeSnapshotContent, err := snapshotclientset.New(t.client).SnapshotV1().VolumeSnapshotContents().Update(context.TODO(), volumeSnapshotContent, metav1.UpdateOptions{}) + _, err := snapshotclientset.New(t.client).SnapshotV1().VolumeSnapshotContents().Update(context.TODO(), volumeSnapshotContent, metav1.UpdateOptions{}) framework.ExpectNoError(err) } @@ -192,7 +192,7 @@ func (t *TestVolumeSnapshotClass) ReadyToUse(snapshot *volumesnapshotv1.VolumeSn err := wait.Poll(15*time.Second, 5*time.Minute, func() (bool, error) { vs, err := snapshotclientset.New(t.client).SnapshotV1().VolumeSnapshots(t.namespace.Name).Get(context.TODO(), snapshot.Name, metav1.GetOptions{}) if err != nil { - return false, fmt.Errorf("did not see ReadyToUse: %v", err) + return false, fmt.Errorf("did not see ReadyToUse: %w", err) } if vs.Status == nil || vs.Status.ReadyToUse == nil { @@ -214,8 +214,7 @@ func (t *TestVolumeSnapshotClass) DeleteSnapshot(vs *volumesnapshotv1.VolumeSnap func (t *TestVolumeSnapshotClass) DeleteVolumeSnapshotContent(vsc *volumesnapshotv1.VolumeSnapshotContent) { By("deleting a VolumeSnapshotContent " + vsc.Name) - snapshotclientset.New(t.client).SnapshotV1().VolumeSnapshotContents().Delete(context.TODO(), vsc.Name, metav1.DeleteOptions{}) - + snapshotclientset.New(t.client).SnapshotV1().VolumeSnapshotContents().Delete(context.TODO(), vsc.Name, metav1.DeleteOptions{}) //nolint err := t.waitForVolumeSnapshotContentDeleted(vsc.Name, 5*time.Second, 5*time.Minute) framework.ExpectNoError(err) } @@ -569,7 +568,7 @@ func (t *TestDeployment) DeletePodAndWait() { err := t.client.CoreV1().Pods(t.namespace.Name).Delete(context.TODO(), t.podName, metav1.DeleteOptions{}) if err != nil { if !apierrs.IsNotFound(err) { - framework.ExpectNoError(fmt.Errorf("pod %q Delete API error: %v", t.podName, err)) + framework.ExpectNoError(fmt.Errorf("pod %q Delete API error: %w", t.podName, err)) } return } @@ -577,7 +576,7 @@ func (t *TestDeployment) DeletePodAndWait() { err = e2epod.WaitForPodNotFoundInNamespace(t.client, t.podName, t.namespace.Name, 3*time.Minute) if err != nil { if !apierrs.IsNotFound(err) { - framework.ExpectNoError(fmt.Errorf("pod %q error waiting for delete: %v", t.podName, err)) + framework.ExpectNoError(fmt.Errorf("pod %q error waiting for delete: %w", t.podName, err)) } } } @@ -671,6 +670,8 @@ var podFailedCondition = func(pod *v1.Pod) (bool, error) { return true, nil case v1.PodSucceeded: return true, fmt.Errorf("pod %q successed with reason: %q, message: %q", pod.Name, pod.Status.Reason, pod.Status.Message) + case v1.PodPending, v1.PodRunning, v1.PodUnknown: + return false, nil default: return false, nil } diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 3b08476780..ed7a75dc41 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -16,8 +16,8 @@ package integration import ( "context" + "errors" "fmt" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -158,10 +158,10 @@ func testAttachWriteReadDetach(volumeID, volName, nodeID string, readOnly bool) // Write a file testFileContents := []byte("sample content") testFile := filepath.Join(publishDir, "testfile") - err := ioutil.WriteFile(testFile, testFileContents, 0644) + err := os.WriteFile(testFile, testFileContents, 0644) Expect(err).To(BeNil(), "Failed to write file") // Read the file and check if content is correct - data, err := ioutil.ReadFile(testFile) + data, err := os.ReadFile(testFile) Expect(err).To(BeNil(), "Failed to read file") Expect(data).To(Equal(testFileContents), "File content is incorrect") } @@ -181,7 +181,8 @@ func waitForVolume(volumeID string, nVolumes int) { volumes, err := describeVolumes(params) if err != nil { if nVolumes == 0 { - if awsErr, ok := err.(awserr.Error); ok { + var awsErr awserr.Error + if errors.As(err, &awsErr) { if awsErr.Code() == "InvalidVolume.NotFound" { return true, nil } diff --git a/tests/integration/setup_test.go b/tests/integration/setup_test.go index fd7fb19240..6d6c67870f 100644 --- a/tests/integration/setup_test.go +++ b/tests/integration/setup_test.go @@ -32,6 +32,7 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" ) @@ -84,7 +85,7 @@ type CSIClient struct { func newCSIClient() (*CSIClient, error) { opts := []grpc.DialOption{ - grpc.WithInsecure(), + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), grpc.WithContextDialer( func(context.Context, string) (net.Conn, error) {