From 41261a0d95a51216e39519e2465cc346a9972678 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 10:42:00 +0530 Subject: [PATCH 01/17] Enable gocyclo linter --- .golangci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.golangci.yml b/.golangci.yml index 7b516a98ea..33d12d5059 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,6 +12,7 @@ linters: - whitespace - gocognit - unparam + - gocyclo run: timeout: 10m # golangci-lint run's timeout. @@ -29,3 +30,7 @@ issues: - text: "`ctx` is unused" # Context might not be in use in places, but for consistency, we pass it. linters: - unparam + +linter-settings: + gocyclo: + min-complexity: 20 \ No newline at end of file From 118bc8a1bd8a3c58bb16f5638b7505d46672cde7 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 11:58:14 +0530 Subject: [PATCH 02/17] Enable gocritic linter --- .golangci.yml | 1 + cmd/kanctl/main.go | 2 +- pkg/blockstorage/awsefs/awsefs.go | 2 +- pkg/blockstorage/azure/azuredisk.go | 6 +++--- pkg/blockstorage/tags/tags.go | 10 +++++----- pkg/blockstorage/vmware/vmware.go | 7 ++++--- pkg/blockstorage/zone/zone_test.go | 6 +++--- pkg/blueprint/validate/validate.go | 5 +++-- pkg/controller/controller.go | 7 ++++--- pkg/controller/controller_test.go | 10 +++++----- .../repositoryserver_controller_test.go | 6 +++--- pkg/datamover/profile_test.go | 2 +- pkg/filter/filter.go | 2 +- pkg/function/export_rds_snapshot_location.go | 3 +-- pkg/kanctl/actionset.go | 4 +--- pkg/kanctl/profile.go | 16 +++++----------- pkg/kanctl/repositoryserver.go | 4 +--- pkg/kanctl/validate.go | 4 +--- pkg/kando/location_test.go | 2 +- pkg/kando/output.go | 8 ++------ pkg/kando/stream_push.go | 4 +--- pkg/kube/job_test.go | 2 +- pkg/kube/pod.go | 3 +-- pkg/kube/volume/volume.go | 2 +- pkg/log/log_test.go | 4 ++-- pkg/objectstore/directory.go | 2 +- pkg/objectstore/objectstore_test.go | 2 +- 27 files changed, 55 insertions(+), 71 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 33d12d5059..2a75536c63 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,7 @@ linters: - gocognit - unparam - gocyclo + - gocritic run: timeout: 10m # golangci-lint run's timeout. diff --git a/cmd/kanctl/main.go b/cmd/kanctl/main.go index d594b48d4a..81aef8fbeb 100644 --- a/cmd/kanctl/main.go +++ b/cmd/kanctl/main.go @@ -21,7 +21,7 @@ import ( func init() { // We silence all non-fatal log messages. - //logrus.SetLevel(logrus.ErrorLevel) + // logrus.SetLevel(logrus.ErrorLevel) } func main() { diff --git a/pkg/blockstorage/awsefs/awsefs.go b/pkg/blockstorage/awsefs/awsefs.go index c7af278296..f62d301a90 100644 --- a/pkg/blockstorage/awsefs/awsefs.go +++ b/pkg/blockstorage/awsefs/awsefs.go @@ -565,7 +565,7 @@ func (e *Efs) SnapshotsListWLimit(ctx context.Context, tags map[string]string, l req := &backup.ListRecoveryPointsByBackupVaultInput{} req.SetBackupVaultName(e.backupVaultName) req.SetMaxResults(limit) - resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) //backup API + resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) // backup API if err != nil { return nil, errors.Wrap(err, "Failed to list recovery points by vault") } diff --git a/pkg/blockstorage/azure/azuredisk.go b/pkg/blockstorage/azure/azuredisk.go index c5051b26ee..eb2a0636db 100644 --- a/pkg/blockstorage/azure/azuredisk.go +++ b/pkg/blockstorage/azure/azuredisk.go @@ -270,10 +270,10 @@ func isMigrateStorageAccountorKey(migrateStorageAccount, migrateStorageKey strin return migrateStorageAccount == "" || migrateStorageKey == "" } -func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, ID string) { +func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, id string) { _, err := s.azCli.SnapshotsClient.RevokeAccess(ctx, rg, name) if err != nil { - log.Print("Failed to revoke access from snapshot", field.M{"snapshot": ID}) + log.Print("Failed to revoke access from snapshot", field.M{"snapshot": id}) } } @@ -545,7 +545,7 @@ func (s *AdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot block } func (s *AdStorage) getRegionAndZoneID(ctx context.Context, sourceRegion, volAz string) (string, string, error) { - //check if current node region is zoned or not + // check if current node region is zoned or not kubeCli, err := kube.NewClient() if err != nil { return "", "", err diff --git a/pkg/blockstorage/tags/tags.go b/pkg/blockstorage/tags/tags.go index b482124e4f..c27a2d4b29 100644 --- a/pkg/blockstorage/tags/tags.go +++ b/pkg/blockstorage/tags/tags.go @@ -103,14 +103,14 @@ func IsSubset(set map[string]string, subset map[string]string) bool { return true } -// Union returns union of A and B as a new map. -// B's values have priority if a key from A and B collides. -func Union(A map[string]string, B map[string]string) map[string]string { +// Union returns union of first and second as a new map. +// second's values have priority if a key from first and second collides. +func Union(first map[string]string, second map[string]string) map[string]string { result := make(map[string]string) - for k, v := range A { + for k, v := range first { result[k] = v } - for k, v := range B { + for k, v := range second { result[k] = v } return result diff --git a/pkg/blockstorage/vmware/vmware.go b/pkg/blockstorage/vmware/vmware.go index ceeea73867..51013a7d24 100644 --- a/pkg/blockstorage/vmware/vmware.go +++ b/pkg/blockstorage/vmware/vmware.go @@ -811,11 +811,12 @@ func (ge govmomiError) ExtractMessages() []string { case govmomitask.Error: foundHandledErrorType = true default: - if soap.IsSoapFault(err) { + switch { + case soap.IsSoapFault(err): foundHandledErrorType = true - } else if soap.IsVimFault(err) { + case soap.IsVimFault(err): foundHandledErrorType = true - } else { + default: err = errors.Unwrap(err) } } diff --git a/pkg/blockstorage/zone/zone_test.go b/pkg/blockstorage/zone/zone_test.go index f74c289d05..4e69b5a2b5 100644 --- a/pkg/blockstorage/zone/zone_test.go +++ b/pkg/blockstorage/zone/zone_test.go @@ -23,7 +23,7 @@ import ( "github.com/kanisterio/kanister/pkg/kube" . "gopkg.in/check.v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" @@ -543,14 +543,14 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { outZones []string outErr error }{ - { //success case + { // success case inRegion: "us-west-2", inZones: []string{"us-west-2a"}, inCli: cli, outZones: []string{"us-west-2a"}, outErr: nil, }, - { //success case gce multi region + { // success case gce multi region inRegion: "us-west1", inZones: []string{"us-west1-a"}, inCli: cligce, diff --git a/pkg/blueprint/validate/validate.go b/pkg/blueprint/validate/validate.go index 4a40a98988..44a496e426 100644 --- a/pkg/blueprint/validate/validate.go +++ b/pkg/blueprint/validate/validate.go @@ -73,9 +73,10 @@ func Do(bp *crv1alpha1.Blueprint, funcVersion string) error { func validatePhaseNames(bp *crv1alpha1.Blueprint) error { phasesCount := make(map[string]int) for _, action := range bp.Actions { - allPhases := action.Phases + allPhases := []crv1alpha1.BlueprintPhase{} + allPhases = append(allPhases, action.Phases...) if action.DeferPhase != nil { - allPhases = append(action.Phases, *action.DeferPhase) + allPhases = append(allPhases, *action.DeferPhase) } for _, phase := range allPhases { diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 8221e3d52e..ae2da03fe7 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -232,11 +232,12 @@ func (c *Controller) onUpdateActionSet(oldAS, newAS *crv1alpha1.ActionSet) error return err } if newAS.Status == nil || newAS.Status.State != crv1alpha1.StateRunning { - if newAS.Status == nil { + switch { + case newAS.Status == nil: log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": "nil"}) - } else if newAS.Status.State == crv1alpha1.StateComplete { + case newAS.Status.State == crv1alpha1.StateComplete: c.logAndSuccessEvent(ctx, fmt.Sprintf("Updated ActionSet '%s' Status->%s", newAS.Name, newAS.Status.State), "Update Complete", newAS) - } else { + default: log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": newAS.Status.State}) } return nil diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index e96956ffbe..73f70b6a58 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -664,7 +664,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { msg := "Unit testing event logs" reason := "Test Logs" - //Create nil ActionSet + // Create nil ActionSet var nilAs = (*crv1alpha1.ActionSet)(nil) // Create Blueprint @@ -672,7 +672,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { bp, err = s.crCli.Blueprints(s.namespace).Create(ctx, bp, metav1.CreateOptions{}) c.Assert(err, IsNil) - //Test the logAndErrorEvent function + // Test the logAndErrorEvent function ctx = field.Context(ctx, consts.ActionsetNameKey, as.GetName()) config, err := kube.LoadConfig() c.Assert(err, IsNil) @@ -686,19 +686,19 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { c.Assert(len(events.Items) > 0, Equals, true) c.Assert(events.Items[0].Message, Equals, msg) - //Testing nil ActionSet error event logging + // Testing nil ActionSet error event logging events, err = s.cli.CoreV1().Events(as.Namespace).Search(scheme.Scheme, nilAs) c.Assert(err, NotNil) c.Assert(len(events.Items), Equals, 0) - //Testing Blueprint error event logging + // Testing Blueprint error event logging events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, bp) c.Assert(err, IsNil) c.Assert(events, NotNil) c.Assert(len(events.Items) > 0, Equals, true) c.Assert(events.Items[0].Message, Equals, msg) - //Testing empty Blueprint + // Testing empty Blueprint testbp := &crv1alpha1.Blueprint{} ctlr.logAndErrorEvent(ctx, msg, reason, errors.New("Testing Event Logs"), testbp) events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, testbp) diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index 1bfba79b66..e8eda1bf9d 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -247,7 +247,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerStatusIsServerReady(c *C err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) @@ -294,7 +294,7 @@ func (s *RepoServerControllerSuite) TestCreationOfOwnedResources(c *C) { err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) @@ -401,7 +401,7 @@ func (s *RepoServerControllerSuite) TestFilestoreLocationVolumeMountOnRepoServer err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) diff --git a/pkg/datamover/profile_test.go b/pkg/datamover/profile_test.go index ef1537d780..1f8af86363 100644 --- a/pkg/datamover/profile_test.go +++ b/pkg/datamover/profile_test.go @@ -64,7 +64,7 @@ func (ps *ProfileSuite) TestLocationOperationsForProfileDataMover(c *C) { err = locationDelete(ps.ctx, p, path) c.Assert(err, IsNil) - //test deleting dir with multiple artifacts + // test deleting dir with multiple artifacts source = bytes.NewBufferString(testContent) err = locationPush(ps.ctx, p, path, source) c.Assert(err, IsNil) diff --git a/pkg/filter/filter.go b/pkg/filter/filter.go index 1d8547ba21..ae161213d7 100644 --- a/pkg/filter/filter.go +++ b/pkg/filter/filter.go @@ -145,7 +145,7 @@ type ResourceRequirement struct { // DeepCopyInto provides explicit deep copy implementation to avoid func (r ResourceRequirement) DeepCopyInto(out *ResourceRequirement) { r.LocalObjectReference.DeepCopyInto(&out.LocalObjectReference) - (*out).ResourceTypeRequirement = r.ResourceTypeRequirement + out.ResourceTypeRequirement = r.ResourceTypeRequirement r.LabelSelector.DeepCopyInto(&out.LabelSelector) } diff --git a/pkg/function/export_rds_snapshot_location.go b/pkg/function/export_rds_snapshot_location.go index 2c9664ed97..b6e2cf04cc 100644 --- a/pkg/function/export_rds_snapshot_location.go +++ b/pkg/function/export_rds_snapshot_location.go @@ -278,8 +278,7 @@ func prepareCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction, dbList = filterRestrictedDB(dbList) } - switch dbEngine { - case PostgrSQLEngine: + if dbEngine == PostgrSQLEngine { switch action { case BackupAction: command, err := postgresBackupCommand(dbEndpoint, username, password, dbList, backupPrefix, backupID, profileJson) diff --git a/pkg/kanctl/actionset.go b/pkg/kanctl/actionset.go index 59a4c3ffb6..32e2803f0e 100644 --- a/pkg/kanctl/actionset.go +++ b/pkg/kanctl/actionset.go @@ -84,9 +84,7 @@ func newActionSetCmd() *cobra.Command { Use: "actionset", Short: "Create a new ActionSet or override a ActionSet", Args: cobra.ExactArgs(0), - RunE: func(c *cobra.Command, args []string) error { - return initializeAndPerform(c, args) - }, + RunE: initializeAndPerform, } cmd.Flags().StringP(sourceFlagName, "f", "", "specify name of the action set") diff --git a/pkg/kanctl/profile.go b/pkg/kanctl/profile.go index c7866a5857..2938712bb6 100644 --- a/pkg/kanctl/profile.go +++ b/pkg/kanctl/profile.go @@ -95,9 +95,7 @@ func newS3CompliantProfileCmd() *cobra.Command { Use: "s3compliant", Short: "Create new S3 compliant profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(awsAccessKeyFlag, "a", "", "access key of the s3 compliant bucket") @@ -114,9 +112,7 @@ func newGCPProfileCmd() *cobra.Command { Use: "gcp", Short: "Create new gcp profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(gcpProjectIDFlag, "a", "", "Project ID of the google application") @@ -132,9 +128,7 @@ func newAzureProfileCmd() *cobra.Command { Use: "azure", Short: "Create new azure profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(AzureStorageAccountFlag, "a", "", "Storage account name of the azure storage") @@ -263,7 +257,7 @@ func constructProfile(lP *locationParams, secret *v1.Secret) *v1alpha1.Profile { }, }, } - case lP.locationType == v1alpha1.LocationTypeGCS: //GCP + case lP.locationType == v1alpha1.LocationTypeGCS: // GCP creds = v1alpha1.Credential{ Type: v1alpha1.CredentialTypeKeyPair, KeyPair: &v1alpha1.KeyPair{ @@ -490,7 +484,7 @@ func getServiceKey(ctx context.Context, filename string) (string, error) { if err != nil { return "", err } - //Parse the service key + // Parse the service key _, err = google.CredentialsFromJSON(ctx, b, compute.ComputeScope) if err != nil { return "", err diff --git a/pkg/kanctl/repositoryserver.go b/pkg/kanctl/repositoryserver.go index 52c660b9f7..a3ac978649 100644 --- a/pkg/kanctl/repositoryserver.go +++ b/pkg/kanctl/repositoryserver.go @@ -64,9 +64,7 @@ func newRepositoryServerCommand() *cobra.Command { Use: "repository-server", Short: "Create a new RepositoryServer", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewRepositoryServer(cmd, args) - }, + RunE: createNewRepositoryServer, } cmd.PersistentFlags().StringP(tlsSecretFlag, "t", "", "name of the tls secret needed for secure kopia client and kopia repository server communication") diff --git a/pkg/kanctl/validate.go b/pkg/kanctl/validate.go index c3de036df8..b643c7ce03 100644 --- a/pkg/kanctl/validate.go +++ b/pkg/kanctl/validate.go @@ -42,9 +42,7 @@ func newValidateCommand() *cobra.Command { Use: "validate ", Short: "Validate custom Kanister resources", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return performValidation(cmd, args) - }, + RunE: performValidation, } cmd.Flags().String(nameFlag, "", "specify the K8s name of the custom resource to validate") cmd.Flags().StringP(filenameFlag, "f", "", "yaml or json file of the custom resource to validate") diff --git a/pkg/kando/location_test.go b/pkg/kando/location_test.go index a0b7585aaa..221041acb5 100644 --- a/pkg/kando/location_test.go +++ b/pkg/kando/location_test.go @@ -55,7 +55,7 @@ func (s *LocationSuite) TestLocationObjectStore(c *C) { err = locationDelete(ctx, p, path) c.Assert(err, IsNil) - //test deleting dir with multiple artifacts + // test deleting dir with multiple artifacts source = bytes.NewBufferString(testContent) err = locationPush(ctx, p, path, source) c.Assert(err, IsNil) diff --git a/pkg/kando/output.go b/pkg/kando/output.go index e00838da58..13f372163c 100644 --- a/pkg/kando/output.go +++ b/pkg/kando/output.go @@ -25,13 +25,9 @@ func newOutputCommand() *cobra.Command { cmd := &cobra.Command{ Use: "output ", Short: "Create phase output with given key:value", - Args: func(c *cobra.Command, args []string) error { - return validateArguments(c, args) - }, + Args: validateArguments, // TODO: Example invocations - RunE: func(c *cobra.Command, args []string) error { - return runOutputCommand(c, args) - }, + RunE: runOutputCommand, } return cmd } diff --git a/pkg/kando/stream_push.go b/pkg/kando/stream_push.go index 8ec041239d..8497b34439 100644 --- a/pkg/kando/stream_push.go +++ b/pkg/kando/stream_push.go @@ -34,9 +34,7 @@ func newStreamPushCommand() *cobra.Command { Use: "push ", Short: "Push the output of a stream source to object storage", Args: cobra.ExactArgs(1), - RunE: func(c *cobra.Command, args []string) error { - return runStreamPush(c, args) - }, + RunE: runStreamPush, } cmd.Flags().StringP(streamPushDirPathFlagName, "d", "", "Specify a root directory path for the data stream (required)") cmd.Flags().StringP(streamPushFilePathFlagName, "f", "", "Specify a file name or path for the data stream (required)") diff --git a/pkg/kube/job_test.go b/pkg/kube/job_test.go index acf10cf9fa..67c6aaa155 100644 --- a/pkg/kube/job_test.go +++ b/pkg/kube/job_test.go @@ -47,7 +47,7 @@ func (s *JobSuite) SetUpSuite(c *C) { } func (s *JobSuite) SetUpTest(c *C) { - testJobName = testJobName + rand.String(5) + testJobName += rand.String(5) } // Verifies that the Job object is not created if the job name is not specified. diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index 7dbcc12d96..651b787b17 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -393,8 +393,7 @@ func WaitForPodCompletion(ctx context.Context, cli kubernetes.Interface, namespa return true, err } containerForLogs = p.Spec.Containers[0].Name - switch p.Status.Phase { - case v1.PodFailed: + if p.Status.Phase == v1.PodFailed { return false, errors.Errorf("Pod %s failed. Pod status: %s", name, p.Status.String()) } return p.Status.Phase == v1.PodSucceeded, nil diff --git a/pkg/kube/volume/volume.go b/pkg/kube/volume/volume.go index e63ddec8ed..7bcd47356f 100644 --- a/pkg/kube/volume/volume.go +++ b/pkg/kube/volume/volume.go @@ -309,6 +309,6 @@ func labelSelector(labels map[string]string) string { // zoneToRegion removes -latter or just last latter from provided zone. func zoneToRegion(zone string) string { - r, _ := regexp.Compile("-?[a-z]$") + r, _ := regexp.Compile("-?[a-z]$") //nolint:gocritic return r.ReplaceAllString(zone, "") } diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 0f0eee14be..dfbff9f6a6 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -174,14 +174,14 @@ func (s *LogSuite) TestLogLevel(c *C) { log.SetOutput(&output) ctx := field.Context(context.Background(), "key", "value") var entry map[string]interface{} - //Check if debug level log is printed when log level is info + // Check if debug level log is printed when log level is info Debug().WithContext(ctx).Print("Testing debug level") err := json.Unmarshal(output.Bytes(), &entry) c.Assert(err, NotNil) c.Assert(output.String(), HasLen, 0) - //Check if debug level log is printed when log level is debug + // Check if debug level log is printed when log level is debug os.Setenv(LevelEnvName, "debug") defer func() { os.Unsetenv(LevelEnvName) diff --git a/pkg/objectstore/directory.go b/pkg/objectstore/directory.go index dc6ae0b360..e1d28f5674 100644 --- a/pkg/objectstore/directory.go +++ b/pkg/objectstore/directory.go @@ -298,7 +298,7 @@ func (d *directory) absPathName(name string) string { func sanitizeTags(tags map[string]string) map[string]interface{} { cTags := make(map[string]interface{}) for key, val := range tags { - cKey := strings.Replace(key, "/", "-", -1) + cKey := strings.ReplaceAll(key, "/", "-") cTags[cKey] = val } return cTags diff --git a/pkg/objectstore/objectstore_test.go b/pkg/objectstore/objectstore_test.go index a03a03f6ea..af44ae732c 100644 --- a/pkg/objectstore/objectstore_test.go +++ b/pkg/objectstore/objectstore_test.go @@ -421,7 +421,7 @@ func (s *ObjectStoreProviderSuite) createBucketName(c *C) string { } // GCS bucket names cannot contain '.' (except for recognized top-level domains) - bucketName = strings.Replace(bucketName, ".", "-", -1) + bucketName = strings.ReplaceAll(bucketName, ".", "-") return bucketName } From 9fe8ef0073eb412c1598b023a33ebb6b6b26e6b2 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 13:08:19 +0530 Subject: [PATCH 03/17] Fix typo for linters-settings, fix gocyclo lint failures --- .golangci.yml | 4 +- pkg/blockstorage/azure/azuredisk.go | 81 ++++++++++++++++++----------- pkg/kanctl/actionset.go | 2 +- pkg/kube/pod.go | 7 ++- 4 files changed, 58 insertions(+), 36 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 2a75536c63..90bc437aba 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -32,6 +32,6 @@ issues: linters: - unparam -linter-settings: +linters-settings: gocyclo: - min-complexity: 20 \ No newline at end of file + min-complexity: 20 diff --git a/pkg/blockstorage/azure/azuredisk.go b/pkg/blockstorage/azure/azuredisk.go index eb2a0636db..faacd22511 100644 --- a/pkg/blockstorage/azure/azuredisk.go +++ b/pkg/blockstorage/azure/azuredisk.go @@ -199,47 +199,20 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. blob := container.GetBlobReference(blobName) defer deleteBlob(blob, blobName) - var copyOptions *storage.CopyOptions - if t, ok := ctx.Deadline(); ok { - time := time.Until(t).Seconds() - if time <= 0 { - return nil, errors.New("Context deadline exceeded, cannot copy snapshot") - } - copyOptions = &storage.CopyOptions{ - Timeout: uint(time), - } + copyOptions, err := getCopyOptions(ctx) + if err != nil { + return nil, err } err = blob.Copy(*accessURI.AccessSAS, copyOptions) if err != nil { return nil, errors.Wrapf(err, "Failed to copy disk to blob") } - blobURI := blob.GetURL() - snapId, err := uuid.NewV1() if err != nil { return nil, errors.Wrap(err, "Failed to create UUID") } snapName := fmt.Sprintf(snapshotNameFmt, snapId.String()) - var tags = make(map[string]string) - for _, tag := range from.Volume.Tags { - if _, found := tags[tag.Key]; !found { - tags[tag.Key] = tag.Value - } - } - tags = blockstorage.SanitizeTags(ktags.GetTags(tags)) - - createSnap := azcompute.Snapshot{ - Name: azto.StringPtr(snapName), - Location: azto.StringPtr(to.Region), - Tags: *azto.StringMapPtr(tags), - SnapshotProperties: &azcompute.SnapshotProperties{ - CreationData: &azcompute.CreationData{ - CreateOption: azcompute.Import, - StorageAccountID: azto.StringPtr(storageAccountID), - SourceURI: azto.StringPtr(blobURI), - }, - }, - } + createSnap := getSnapshotObject(blob, from, to, snapName, storageAccountID) migrateResourceGroup := s.azCli.ResourceGroup if val, ok := args[blockstorage.AzureMigrateResourceGroup]; ok && val != "" { @@ -266,6 +239,52 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. return snap, nil } +func getCopyOptions(ctx context.Context) (*storage.CopyOptions, error) { + var copyOptions *storage.CopyOptions + if t, ok := ctx.Deadline(); ok { + time := time.Until(t).Seconds() + if time <= 0 { + return nil, errors.New("Context deadline exceeded, cannot copy snapshot") + } + copyOptions = &storage.CopyOptions{ + Timeout: uint(time), + } + } + return copyOptions, nil +} + +func getSnapshotObject( + blob *storage.Blob, + from, + to blockstorage.Snapshot, + snapName, + storageAccountID string, +) azcompute.Snapshot { + blobURI := blob.GetURL() + + var tags = make(map[string]string) + for _, tag := range from.Volume.Tags { + if _, found := tags[tag.Key]; !found { + tags[tag.Key] = tag.Value + } + } + tags = blockstorage.SanitizeTags(ktags.GetTags(tags)) + + createSnap := azcompute.Snapshot{ + Name: azto.StringPtr(snapName), + Location: azto.StringPtr(to.Region), + Tags: *azto.StringMapPtr(tags), + SnapshotProperties: &azcompute.SnapshotProperties{ + CreationData: &azcompute.CreationData{ + CreateOption: azcompute.Import, + StorageAccountID: azto.StringPtr(storageAccountID), + SourceURI: azto.StringPtr(blobURI), + }, + }, + } + return createSnap +} + func isMigrateStorageAccountorKey(migrateStorageAccount, migrateStorageKey string) bool { return migrateStorageAccount == "" || migrateStorageKey == "" } diff --git a/pkg/kanctl/actionset.go b/pkg/kanctl/actionset.go index 32e2803f0e..5b134a73a9 100644 --- a/pkg/kanctl/actionset.go +++ b/pkg/kanctl/actionset.go @@ -501,7 +501,7 @@ func parseGenericObjectReference(s string) (crv1alpha1.ObjectReference, error) { }, nil } -func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) { +func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) { //nolint:gocyclo ctx := context.Background() var objects []crv1alpha1.ObjectReference appendObj := func(kind, namespace, name string) { diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index 651b787b17..b9b83ef7b9 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -146,6 +146,10 @@ func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1 return patchedSpecs.Containers[i].Name == defaultContainerName }) + return createPodSpec(opts, patchedSpecs, ns), nil +} + +func createPodSpec(opts *PodOptions, patchedSpecs v1.PodSpec, ns string) *v1.Pod { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: opts.GenerateName, @@ -195,8 +199,7 @@ func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1 } pod.Namespace = ns - - return pod, nil + return pod } // CreatePod creates a pod with a single container based on the specified image From 88f109720ab057b86ff9050c3d4be0e70429e504 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 13:58:41 +0530 Subject: [PATCH 04/17] Add lll linter --- .golangci.yml | 4 ++ pkg/app/cassandra.go | 13 ++++-- pkg/app/mariadb.go | 5 ++- pkg/app/mongodb-deploymentconfig.go | 4 +- pkg/app/mongodb.go | 4 +- pkg/app/mysql.go | 4 +- pkg/aws/rds/rds.go | 27 +++++++++++- pkg/blockstorage/vmware/vmware.go | 8 +++- pkg/function/delete_data.go | 25 ++++++++++- pkg/function/export_rds_snapshot_location.go | 44 ++++++++++++++++++-- pkg/function/restore_rds_snapshot.go | 40 ++++++++++++++++-- pkg/kanctl/actionset.go | 3 +- pkg/kopia/command/parse_command_output.go | 1 + pkg/kube/snapshot/snapshot_beta.go | 13 +++++- pkg/kube/volume/volume.go | 22 +++++++++- 15 files changed, 193 insertions(+), 24 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 90bc437aba..90d4eea6b4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,7 @@ linters: - unparam - gocyclo - gocritic + - lll run: timeout: 10m # golangci-lint run's timeout. @@ -27,6 +28,7 @@ issues: linters: - errcheck # Errors may be ignored in tests. - unparam # Tests might have unused function parameters. + - lll - text: "`ctx` is unused" # Context might not be in use in places, but for consistency, we pass it. linters: @@ -35,3 +37,5 @@ issues: linters-settings: gocyclo: min-complexity: 20 + lll: + line-length: 240 diff --git a/pkg/app/cassandra.go b/pkg/app/cassandra.go index d5b9c071e8..46d9c5d24b 100644 --- a/pkg/app/cassandra.go +++ b/pkg/app/cassandra.go @@ -158,7 +158,9 @@ func (cas *CassandraInstance) Ping(ctx context.Context) error { // Insert is used to insert the records into the database func (cas *CassandraInstance) Insert(ctx context.Context) error { log.Print("Inserting records into the database.", field.M{"app": cas.name}) - insertCMD := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"insert into restaurants.guests (id, firstname, lastname, birthday) values (uuid(), 'Tom', 'Singh', '2015-02-18');\" --request-timeout=%s", cqlTimeout)} + insertCMD := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"insert into "+ + "restaurants.guests (id, firstname, lastname, birthday) values (uuid(), 'Tom', 'Singh', "+ + "'2015-02-18');\" --request-timeout=%s", cqlTimeout)} _, stderr, err := cas.execCommand(ctx, insertCMD) if err != nil { return errors.Wrapf(err, "Error %s inserting records into the database.", stderr) @@ -191,7 +193,8 @@ func (cas *CassandraInstance) Count(ctx context.Context) (int, error) { // Reset is used to reset or imitate disaster, in the database func (cas *CassandraInstance) Reset(ctx context.Context) error { // delete keyspace and table if they already exist - delRes := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e 'drop table if exists restaurants.guests; drop keyspace if exists restaurants;' --request-timeout=%s", cqlTimeout)} + delRes := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e "+ + "'drop table if exists restaurants.guests; drop keyspace if exists restaurants;' --request-timeout=%s", cqlTimeout)} _, stderr, err := cas.execCommand(ctx, delRes) if err != nil { return errors.Wrapf(err, "Error %s, deleting resources while reseting application.", stderr) @@ -202,14 +205,16 @@ func (cas *CassandraInstance) Reset(ctx context.Context) error { // Initialize is used to initialize the database or create schema func (cas *CassandraInstance) Initialize(ctx context.Context) error { // create the keyspace - createKS := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"create keyspace restaurants with replication = {'class':'SimpleStrategy', 'replication_factor': 3};\" --request-timeout=%s", cqlTimeout)} + createKS := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"create keyspace "+ + "restaurants with replication = {'class':'SimpleStrategy', 'replication_factor': 3};\" --request-timeout=%s", cqlTimeout)} _, stderr, err := cas.execCommand(ctx, createKS) if err != nil { return errors.Wrapf(err, "Error %s while creating the keyspace for application.", stderr) } // create the table - createTab := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"create table restaurants.guests (id UUID primary key, firstname text, lastname text, birthday timestamp);\" --request-timeout=%s", cqlTimeout)} + createTab := []string{"sh", "-c", fmt.Sprintf("cqlsh -u cassandra -p $CASSANDRA_PASSWORD -e \"create table "+ + "restaurants.guests (id UUID primary key, firstname text, lastname text, birthday timestamp);\" --request-timeout=%s", cqlTimeout)} _, stderr, err = cas.execCommand(ctx, createTab) if err != nil { return errors.Wrapf(err, "Error %s creating table.", stderr) diff --git a/pkg/app/mariadb.go b/pkg/app/mariadb.go index 3d4a4c316f..c295327bc3 100644 --- a/pkg/app/mariadb.go +++ b/pkg/app/mariadb.go @@ -204,7 +204,10 @@ func (m *MariaDB) Reset(ctx context.Context) error { func (m *MariaDB) Initialize(ctx context.Context) error { // create the database and a pets table - createTableCMD := []string{"sh", "-c", "mysql -u root --password=$MARIADB_ROOT_PASSWORD -e 'create database testdb; use testdb; CREATE TABLE pets (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);'"} + createTableCMD := []string{"sh", "-c", "mysql -u root --password=$MARIADB_ROOT_PASSWORD " + + "-e 'create database testdb; use testdb; " + + "CREATE TABLE pets (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), " + + "birth DATE, death DATE);'"} _, stderr, err := m.execCommand(ctx, createTableCMD) if err != nil { return errors.Wrapf(err, "Error while creating the maria table: %s", stderr) diff --git a/pkg/app/mongodb-deploymentconfig.go b/pkg/app/mongodb-deploymentconfig.go index 84e901636e..043508028d 100644 --- a/pkg/app/mongodb-deploymentconfig.go +++ b/pkg/app/mongodb-deploymentconfig.go @@ -134,7 +134,9 @@ func (mongo *MongoDBDepConfig) Ping(ctx context.Context) error { func (mongo *MongoDBDepConfig) Insert(ctx context.Context) error { log.Print("Inserting documents into collection.", field.M{"app": mongo.name}) - insertCMD := []string{"bash", "-c", fmt.Sprintf("mongo admin --authenticationDatabase admin -u %s -p $MONGODB_ADMIN_PASSWORD --quiet --eval \"db.restaurants.insert({'_id': '%s','name' : 'Tom', 'cuisine' : 'Hawaiian', 'id' : '8675309'})\"", mongo.user, uuid.New())} + insertCMD := []string{"bash", "-c", fmt.Sprintf("mongo admin --authenticationDatabase admin -u %s -p "+ + "$MONGODB_ADMIN_PASSWORD --quiet --eval \"db.restaurants.insert({'_id': '%s','name' : 'Tom', "+ + "'cuisine' : 'Hawaiian', 'id' : '8675309'})\"", mongo.user, uuid.New())} _, stderr, err := mongo.execCommand(ctx, insertCMD) if err != nil { return errors.Wrapf(err, "Error %s while inserting data data into mongodb collection.", stderr) diff --git a/pkg/app/mongodb.go b/pkg/app/mongodb.go index d284896fca..d722f108d5 100644 --- a/pkg/app/mongodb.go +++ b/pkg/app/mongodb.go @@ -180,7 +180,9 @@ func (mongo *MongoDB) Ping(ctx context.Context) error { func (mongo *MongoDB) Insert(ctx context.Context) error { log.Print("Inserting documents into collection.", field.M{"app": mongo.name}) - insertCMD := []string{"sh", "-c", fmt.Sprintf("mongosh admin --authenticationDatabase admin -u %s -p $MONGODB_ROOT_PASSWORD --quiet --eval \"db.restaurants.insertOne({'_id': '%s','name' : 'Tom', 'cuisine' : 'Hawaiian', 'id' : '8675309'})\"", mongo.username, uuid.New())} + insertCMD := []string{"sh", "-c", fmt.Sprintf("mongosh admin --authenticationDatabase admin -u %s -p "+ + "$MONGODB_ROOT_PASSWORD --quiet --eval \"db.restaurants.insertOne({'_id': '%s','name' : 'Tom', "+ + "'cuisine' : 'Hawaiian', 'id' : '8675309'})\"", mongo.username, uuid.New())} _, stderr, err := mongo.execCommand(ctx, insertCMD) if err != nil { return errors.Wrapf(err, "Error %s while inserting data data into mongodb collection.", stderr) diff --git a/pkg/app/mysql.go b/pkg/app/mysql.go index d113cac06b..fde3719d41 100644 --- a/pkg/app/mysql.go +++ b/pkg/app/mysql.go @@ -215,7 +215,9 @@ func (mdb *MysqlDB) Reset(ctx context.Context) error { // Initialize is used to initialize the database or create schema func (mdb *MysqlDB) Initialize(ctx context.Context) error { // create the database and a pets table - createTableCMD := []string{"sh", "-c", "mysql -u root --password=$MYSQL_ROOT_PASSWORD -e 'create database testdb; use testdb; CREATE TABLE pets (name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);'"} + createTableCMD := []string{"sh", "-c", "mysql -u root --password=$MYSQL_ROOT_PASSWORD -e " + + "'create database testdb; use testdb; CREATE TABLE pets (name VARCHAR(20), owner VARCHAR(20), " + + "species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);'"} _, stderr, err := mdb.execCommand(ctx, createTableCMD) if err != nil { return errors.Wrapf(err, "Error while creating the mysql table: %s", stderr) diff --git a/pkg/aws/rds/rds.go b/pkg/aws/rds/rds.go index f98314e5db..658680fd7c 100644 --- a/pkg/aws/rds/rds.go +++ b/pkg/aws/rds/rds.go @@ -48,7 +48,19 @@ func NewClient(ctx context.Context, awsConfig *aws.Config, region string) (*RDS, } // CreateDBInstanceWithContext -func (r RDS) CreateDBInstance(ctx context.Context, storage *int64, instanceClass, instanceID, engine, username, password string, sgIDs []string, publicAccess *bool, restoredClusterID *string, dbSubnetGroup string) (*rds.CreateDBInstanceOutput, error) { +func (r RDS) CreateDBInstance( + ctx context.Context, + storage *int64, + instanceClass, + instanceID, + engine, + username, + password string, + sgIDs []string, + publicAccess *bool, + restoredClusterID *string, + dbSubnetGroup string, +) (*rds.CreateDBInstanceOutput, error) { dbi := &rds.CreateDBInstanceInput{ DBInstanceClass: &instanceClass, DBInstanceIdentifier: &instanceID, @@ -74,7 +86,18 @@ func (r RDS) CreateDBInstance(ctx context.Context, storage *int64, instanceClass return r.CreateDBInstanceWithContext(ctx, dbi) } -func (r RDS) CreateDBCluster(ctx context.Context, storage int64, instanceClass, instanceID, dbSubnetGroup, engine, dbName, username, password string, sgIDs []string) (*rds.CreateDBClusterOutput, error) { +func (r RDS) CreateDBCluster( + ctx context.Context, + storage int64, + instanceClass, + instanceID, + dbSubnetGroup, + engine, + dbName, + username, + password string, + sgIDs []string, +) (*rds.CreateDBClusterOutput, error) { dbi := &rds.CreateDBClusterInput{ DBClusterIdentifier: &instanceID, DatabaseName: &dbName, diff --git a/pkg/blockstorage/vmware/vmware.go b/pkg/blockstorage/vmware/vmware.go index 51013a7d24..8cc2c23954 100644 --- a/pkg/blockstorage/vmware/vmware.go +++ b/pkg/blockstorage/vmware/vmware.go @@ -357,10 +357,14 @@ func (p *FcdProvider) SnapshotDelete(ctx context.Context, snapshot *blockstorage if soap.IsVimFault(lerr) { switch soap.ToVimFault(lerr).(type) { case *types.InvalidArgument: - log.Error().WithError(lerr).Print("Disk doesn't have given snapshot due to the snapshot stamp being removed in the previous DeleteSnapshot operation which failed with an InvalidState fault. It will be resolved by the next snapshot operation on the same VM. Will NOT retry") + log.Error().WithError(lerr).Print("Disk doesn't have given snapshot due to the snapshot stamp being " + + "removed in the previous DeleteSnapshot operation which failed with an InvalidState fault. It " + + "will be resolved by the next snapshot operation on the same VM. Will NOT retry") return true, nil case *types.NotFound: - log.Error().WithError(lerr).Print("There is a temporary catalog mismatch due to a race condition with one another concurrent DeleteSnapshot operation. It will be resolved by the next consolidateDisks operation on the same VM. Will NOT retry") + log.Error().WithError(lerr).Print("There is a temporary catalog mismatch due to a race condition with " + + "one another concurrent DeleteSnapshot operation. It will be resolved by the next " + + "consolidateDisks operation on the same VM. Will NOT retry") return true, nil case *types.InvalidState: log.Error().WithError(lerr).Print("There is some operation, other than this DeleteSnapshot invocation, on the same VM still being protected by its VM state. Will retry") diff --git a/pkg/function/delete_data.go b/pkg/function/delete_data.go index 51cec40356..97448b9001 100644 --- a/pkg/function/delete_data.go +++ b/pkg/function/delete_data.go @@ -65,7 +65,19 @@ func (*deleteDataFunc) Name() string { return DeleteDataFuncName } -func deleteData(ctx context.Context, cli kubernetes.Interface, tp param.TemplateParams, reclaimSpace bool, namespace, encryptionKey string, targetPaths, deleteTags, deleteIdentifiers []string, jobPrefix string, podOverride crv1alpha1.JSONMap) (map[string]interface{}, error) { +func deleteData( + ctx context.Context, + cli kubernetes.Interface, + tp param.TemplateParams, + reclaimSpace bool, + namespace, + encryptionKey string, + targetPaths, + deleteTags, + deleteIdentifiers []string, + jobPrefix string, + podOverride crv1alpha1.JSONMap, +) (map[string]interface{}, error) { options := &kube.PodOptions{ Namespace: namespace, GenerateName: jobPrefix, @@ -79,7 +91,16 @@ func deleteData(ctx context.Context, cli kubernetes.Interface, tp param.Template } //nolint:gocognit -func deleteDataPodFunc(cli kubernetes.Interface, tp param.TemplateParams, reclaimSpace bool, namespace, encryptionKey string, targetPaths, deleteTags, deleteIdentifiers []string) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func deleteDataPodFunc( + cli kubernetes.Interface, + tp param.TemplateParams, + reclaimSpace bool, + namespace, + encryptionKey string, + targetPaths, + deleteTags, + deleteIdentifiers []string, +) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { diff --git a/pkg/function/export_rds_snapshot_location.go b/pkg/function/export_rds_snapshot_location.go index b6e2cf04cc..bec1bbd5cc 100644 --- a/pkg/function/export_rds_snapshot_location.go +++ b/pkg/function/export_rds_snapshot_location.go @@ -76,7 +76,20 @@ func (*exportRDSSnapshotToLocationFunc) Name() string { return ExportRDSSnapshotToLocFuncName } -func exportRDSSnapshotToLoc(ctx context.Context, namespace, instanceID, snapshotID, username, password string, databases []string, dbSubnetGroup, backupPrefix string, dbEngine RDSDBEngine, sgIDs []string, profile *param.Profile) (map[string]interface{}, error) { +func exportRDSSnapshotToLoc( + ctx context.Context, + namespace, + instanceID, + snapshotID, + username, + password string, + databases []string, + dbSubnetGroup, + backupPrefix string, + dbEngine RDSDBEngine, + sgIDs []string, + profile *param.Profile, +) (map[string]interface{}, error) { // Validate profilextractDumpFromDBe if err := ValidateProfile(profile); err != nil { return nil, errors.Wrap(err, "Profile Validation failed") @@ -217,7 +230,20 @@ func (*exportRDSSnapshotToLocationFunc) Arguments() []string { } } -func execDumpCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction, namespace, dbEndpoint, username, password string, databases []string, backupPrefix, backupID string, profile *param.Profile, dbEngineVersion string) (map[string]interface{}, error) { +func execDumpCommand( + ctx context.Context, + dbEngine RDSDBEngine, + action RDSAction, + namespace, + dbEndpoint, + username, + password string, + databases []string, + backupPrefix, + backupID string, + profile *param.Profile, + dbEngineVersion string, +) (map[string]interface{}, error) { // Trim "\n" from creds username = strings.TrimSpace(username) password = strings.TrimSpace(password) @@ -250,7 +276,19 @@ func execDumpCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction return kubeTask(ctx, cli, namespace, image, command, injectPostgresSecrets(secretName)) } -func prepareCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction, dbEndpoint, username, password string, dbList []string, backupPrefix, backupID string, profile *param.Profile, dbEngineVersion string) ([]string, string, error) { +func prepareCommand( + ctx context.Context, + dbEngine RDSDBEngine, + action RDSAction, + dbEndpoint, + username, + password string, + dbList []string, + backupPrefix, + backupID string, + profile *param.Profile, + dbEngineVersion string, +) ([]string, string, error) { // Convert profile object into json profileJson, err := json.Marshal(profile) if err != nil { diff --git a/pkg/function/restore_rds_snapshot.go b/pkg/function/restore_rds_snapshot.go index d57926ae97..cd16edc712 100644 --- a/pkg/function/restore_rds_snapshot.go +++ b/pkg/function/restore_rds_snapshot.go @@ -145,7 +145,20 @@ func (*restoreRDSSnapshotFunc) Exec(ctx context.Context, tp param.TemplateParams return restoreRDSSnapshot(ctx, namespace, instanceID, subnetGroup, snapshotID, backupArtifactPrefix, backupID, username, password, dbEngine, sgIDs, tp.Profile) } -func restoreRDSSnapshot(ctx context.Context, namespace, instanceID, subnetGroup, snapshotID, backupArtifactPrefix, backupID, username, password string, dbEngine RDSDBEngine, sgIDs []string, profile *param.Profile) (map[string]interface{}, error) { +func restoreRDSSnapshot( + ctx context.Context, + namespace, + instanceID, + subnetGroup, + snapshotID, + backupArtifactPrefix, + backupID, + username, + password string, + dbEngine RDSDBEngine, + sgIDs []string, + profile *param.Profile, +) (map[string]interface{}, error) { // Validate profile if err := ValidateProfile(profile); err != nil { return nil, errors.Wrap(err, "Error validating profile") @@ -206,7 +219,16 @@ func restoreRDSSnapshot(ctx context.Context, namespace, instanceID, subnetGroup, } //nolint:unparam -func postgresRestoreCommand(pgHost, username, password string, dbList []string, backupArtifactPrefix, backupID string, profile []byte, dbEngineVersion string) ([]string, error) { +func postgresRestoreCommand( + pgHost, + username, + password string, + dbList []string, + backupArtifactPrefix, + backupID string, + profile []byte, + dbEngineVersion string, +) ([]string, error) { replaceCommand := "" if len(dbList) == 0 { return nil, errors.New("No database found. Atleast one db needed to connect") @@ -308,7 +330,19 @@ func restoreAuroraFromSnapshot(ctx context.Context, rdsCli *rds.RDS, instanceID, log.WithContext(ctx).Print("Creating DB instance in the cluster") // After Aurora cluster is created, we will have to explictly create the DB instance - dbInsOp, err := rdsCli.CreateDBInstance(ctx, nil, defaultAuroraInstanceClass, fmt.Sprintf("%s-%s", *op.DBCluster.DBClusterIdentifier, restoredAuroraInstanceSuffix), dbEngine, "", "", nil, nil, aws.String(*op.DBCluster.DBClusterIdentifier), subnetGroup) + dbInsOp, err := rdsCli.CreateDBInstance( + ctx, + nil, + defaultAuroraInstanceClass, + fmt.Sprintf("%s-%s", *op.DBCluster.DBClusterIdentifier, restoredAuroraInstanceSuffix), + dbEngine, + "", + "", + nil, + nil, + aws.String(*op.DBCluster.DBClusterIdentifier), + subnetGroup, + ) if err != nil { return errors.Wrap(err, "Error while creating Aurora DB instance in the cluster.") } diff --git a/pkg/kanctl/actionset.go b/pkg/kanctl/actionset.go index 5b134a73a9..70c42d2c7d 100644 --- a/pkg/kanctl/actionset.go +++ b/pkg/kanctl/actionset.go @@ -99,7 +99,8 @@ func newActionSetCmd() *cobra.Command { cmd.Flags().StringSliceP(pvcFlagName, "v", []string{}, "pvc for the action set, comma separated namespace/name pairs (eg: --pvc namespace1/name1,namespace2/name2)") cmd.Flags().StringSliceP(secretsFlagName, "s", []string{}, "secrets for the action set, comma separated ref=namespace/name pairs (eg: --secrets ref1=namespace1/name1,ref2=namespace2/name2)") cmd.Flags().StringSliceP(statefulSetFlagName, "t", []string{}, "statefulset for the action set, comma separated namespace/name pairs (eg: --statefulset namespace1/name1,namespace2/name2)") - cmd.Flags().StringSliceP(deploymentConfigFlagName, "D", []string{}, "deploymentconfig for action set, comma separated namespace/name pairs (e.g. --deploymentconfig namespace1/name1,namespace2/name2). Will ideally be used on openshift clusters.") + cmd.Flags().StringSliceP(deploymentConfigFlagName, "D", []string{}, "deploymentconfig for action set, comma separated namespace/name pairs "+ + "(e.g. --deploymentconfig namespace1/name1,namespace2/name2). Will ideally be used on openshift clusters.") cmd.Flags().StringP(selectorFlagName, "l", "", "k8s selector for objects") cmd.Flags().StringP(selectorKindFlag, "k", "all", "resource kind to apply selector on. Used along with the selector specified using --selector/-l") cmd.Flags().String(selectorNamespaceFlag, "", "namespace to apply selector on. Used along with the selector specified using --selector/-l") diff --git a/pkg/kopia/command/parse_command_output.go b/pkg/kopia/command/parse_command_output.go index 3724aaaf3e..a925d921fd 100644 --- a/pkg/kopia/command/parse_command_output.go +++ b/pkg/kopia/command/parse_command_output.go @@ -36,6 +36,7 @@ const ( typeKey = "type" snapshotValue = "snapshot" + //nolint:lll snapshotCreateOutputRegEx = `(?P[|/\-\\\*]).+[^\d](?P\d+) hashed \((?P[^\)]+)\), (?P\d+) cached \((?P[^\)]+)\), uploaded (?P[^\)]+), (?:estimating...|estimated (?P[^\)]+) \((?P[^\)]+)\%\).+)` extractSnapshotIDRegEx = `Created snapshot with root ([^\s]+) and ID ([^\s]+).*$` repoTotalSizeFromBlobStatsRegEx = `Total: (\d+)$` diff --git a/pkg/kube/snapshot/snapshot_beta.go b/pkg/kube/snapshot/snapshot_beta.go index 646a12695c..3f6369d3a7 100644 --- a/pkg/kube/snapshot/snapshot_beta.go +++ b/pkg/kube/snapshot/snapshot_beta.go @@ -83,7 +83,18 @@ func (sna *SnapshotBeta) Create(ctx context.Context, name, namespace, volumeName return createSnapshot(ctx, sna.dynCli, sna.kubeCli, v1beta1.VolSnapGVR, name, namespace, volumeName, snapshotClass, waitForReady, labels) } -func createSnapshot(ctx context.Context, dynCli dynamic.Interface, kubeCli kubernetes.Interface, snapGVR schema.GroupVersionResource, name, namespace, volumeName string, snapshotClass *string, waitForReady bool, labels map[string]string) error { +func createSnapshot( + ctx context.Context, + dynCli dynamic.Interface, + kubeCli kubernetes.Interface, + snapGVR schema.GroupVersionResource, + name, + namespace, + volumeName string, + snapshotClass *string, + waitForReady bool, + labels map[string]string, +) error { if _, err := kubeCli.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumeName, metav1.GetOptions{}); err != nil { if k8errors.IsNotFound(err) { return errors.Errorf("Failed to find PVC %s, Namespace %s", volumeName, namespace) diff --git a/pkg/kube/volume/volume.go b/pkg/kube/volume/volume.go index 7bcd47356f..b3092297b3 100644 --- a/pkg/kube/volume/volume.go +++ b/pkg/kube/volume/volume.go @@ -48,7 +48,17 @@ const ( // An empty 'targetVolID' indicates the caller would like the PV to be dynamically provisioned // An empty 'name' indicates the caller would like the name to be auto-generated // An error indicating that the PVC already exists is ignored (for idempotency) -func CreatePVC(ctx context.Context, kubeCli kubernetes.Interface, ns string, name string, sizeInBytes int64, targetVolID string, annotations map[string]string, accessmodes []v1.PersistentVolumeAccessMode, volumemode *v1.PersistentVolumeMode) (string, error) { +func CreatePVC( + ctx context.Context, + kubeCli kubernetes.Interface, + ns, + name string, + sizeInBytes int64, + targetVolID string, + annotations map[string]string, + accessmodes []v1.PersistentVolumeAccessMode, + volumemode *v1.PersistentVolumeMode, +) (string, error) { sizeFmt := fmt.Sprintf("%d", sizeInBytes) size, err := resource.ParseQuantity(sizeFmt) emptyStorageClass := "" @@ -208,7 +218,15 @@ func getPVCRestoreSize(ctx context.Context, args *CreatePVCFromSnapshotArgs) (*r // CreatePV creates a PersistentVolume and returns its name // For retry idempotency, checks whether PV associated with volume already exists -func CreatePV(ctx context.Context, kubeCli kubernetes.Interface, vol *blockstorage.Volume, volType blockstorage.Type, annotations map[string]string, accessmodes []v1.PersistentVolumeAccessMode, volumemode *v1.PersistentVolumeMode) (string, error) { +func CreatePV( + ctx context.Context, + kubeCli kubernetes.Interface, + vol *blockstorage.Volume, + volType blockstorage.Type, + annotations map[string]string, + accessmodes []v1.PersistentVolumeAccessMode, + volumemode *v1.PersistentVolumeMode, +) (string, error) { sizeFmt := fmt.Sprintf("%d", vol.SizeInBytes) size, err := resource.ParseQuantity(sizeFmt) if err != nil { From cf599c92abb8b446ca97a3a9eeb842e2dd1b4341 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 14:21:50 +0530 Subject: [PATCH 05/17] Add nakedret linter --- .golangci.yml | 3 + pkg/chronicle/chronicle_push.go | 16 +++-- .../repositoryserver/repository.go | 8 +-- pkg/function/scale_test.go | 12 ++-- pkg/function/scale_workload.go | 59 ++++++++++++------- pkg/testutil/testutil.go | 2 +- 6 files changed, 58 insertions(+), 42 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 90d4eea6b4..2dd533b60f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,7 @@ linters: - gocyclo - gocritic - lll + - nakedret run: timeout: 10m # golangci-lint run's timeout. @@ -39,3 +40,5 @@ linters-settings: min-complexity: 20 lll: line-length: 240 + nakedret: + max-func-lines: 2 diff --git a/pkg/chronicle/chronicle_push.go b/pkg/chronicle/chronicle_push.go index 3dd8d2de97..be7c4df5fe 100644 --- a/pkg/chronicle/chronicle_push.go +++ b/pkg/chronicle/chronicle_push.go @@ -142,23 +142,21 @@ func readArtifactPathFile(path string) (string, error) { return t, errors.Wrap(err, "Could not read artifact path file") } -func readProfile(path string) (p param.Profile, ok bool, err error) { +func readProfile(path string) (param.Profile, bool, error) { var buf []byte - buf, err = os.ReadFile(path) + buf, err := os.ReadFile(path) + var p param.Profile switch { case os.IsNotExist(err): err = nil - return + return p, false, err case err != nil: - err = errors.Wrap(err, "Failed to read profile") - return + return p, false, errors.Wrap(err, "Failed to read profile") } if err = json.Unmarshal(buf, &p); err != nil { - err = errors.Wrap(err, "Failed to unmarshal profile") - } else { - ok = true + return p, false, errors.Wrap(err, "Failed to unmarshal profile") } - return + return p, true, nil } func writeProfile(path string, p param.Profile) error { diff --git a/pkg/controllers/repositoryserver/repository.go b/pkg/controllers/repositoryserver/repository.go index 8f409dc3eb..9e66adfedc 100644 --- a/pkg/controllers/repositoryserver/repository.go +++ b/pkg/controllers/repositoryserver/repository.go @@ -52,19 +52,19 @@ func (h *RepoServerHandler) connectToKopiaRepository() error { ) } -func (h *RepoServerHandler) getRepositoryCacheSettings() (contentCacheMB, metadataCacheMB int, err error) { +func (h *RepoServerHandler) getRepositoryCacheSettings() (contentCacheMB int, metadataCacheMB int, err error) { contentCacheMB, metadataCacheMB = command.GetGeneralCacheSizeSettings() if h.RepositoryServer.Spec.Repository.CacheSizeSettings.Content != "" { contentCacheMB, err = strconv.Atoi(h.RepositoryServer.Spec.Repository.CacheSizeSettings.Content) if err != nil { - return + return contentCacheMB, metadataCacheMB, err } } if h.RepositoryServer.Spec.Repository.CacheSizeSettings.Metadata != "" { metadataCacheMB, err = strconv.Atoi(h.RepositoryServer.Spec.Repository.CacheSizeSettings.Metadata) if err != nil { - return + return contentCacheMB, metadataCacheMB, err } } - return + return contentCacheMB, metadataCacheMB, err } diff --git a/pkg/function/scale_test.go b/pkg/function/scale_test.go index 50b668480a..887767e0ab 100644 --- a/pkg/function/scale_test.go +++ b/pkg/function/scale_test.go @@ -315,15 +315,15 @@ func (s *ScaleSuite) TestGetArgs(c *C) { check: IsNil, }, } { - namespace, kind, name, replicas, waitForReady, err := getArgs(tc.tp, tc.args) + scaleWorkloadArgs, err := getArgs(tc.tp, tc.args) c.Assert(err, tc.check) if err != nil { continue } - c.Assert(namespace, Equals, tc.wantNamespace) - c.Assert(name, Equals, tc.wantName) - c.Assert(kind, Equals, tc.wantKind) - c.Assert(replicas, Equals, tc.wantReplicas) - c.Assert(waitForReady, Equals, tc.wantWaitForReady) + c.Assert(scaleWorkloadArgs.namespace, Equals, tc.wantNamespace) + c.Assert(scaleWorkloadArgs.name, Equals, tc.wantName) + c.Assert(scaleWorkloadArgs.kind, Equals, tc.wantKind) + c.Assert(scaleWorkloadArgs.replicas, Equals, tc.wantReplicas) + c.Assert(scaleWorkloadArgs.waitForReady, Equals, tc.wantWaitForReady) } } diff --git a/pkg/function/scale_workload.go b/pkg/function/scale_workload.go index 673a4fe4e8..31b07035b6 100644 --- a/pkg/function/scale_workload.go +++ b/pkg/function/scale_workload.go @@ -53,9 +53,7 @@ func (*scaleWorkloadFunc) Name() string { } func (*scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, args map[string]interface{}) (map[string]interface{}, error) { - var namespace, kind, name string - var replicas int32 - namespace, kind, name, replicas, waitForReady, err := getArgs(tp, args) + scaleWorkloadArgs, err := getArgs(tp, args) if err != nil { return nil, err } @@ -68,19 +66,19 @@ func (*scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, arg if err != nil { return nil, errors.Wrapf(err, "Failed to create Kubernetes client") } - switch strings.ToLower(kind) { + switch strings.ToLower(scaleWorkloadArgs.kind) { case param.StatefulSetKind: - return nil, kube.ScaleStatefulSet(ctx, cli, namespace, name, replicas, waitForReady) + return nil, kube.ScaleStatefulSet(ctx, cli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) case param.DeploymentKind: - return nil, kube.ScaleDeployment(ctx, cli, namespace, name, replicas, waitForReady) + return nil, kube.ScaleDeployment(ctx, cli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) case param.DeploymentConfigKind: osCli, err := osversioned.NewForConfig(cfg) if err != nil { return nil, errors.Wrapf(err, "Failed to create OpenShift client") } - return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, namespace, name, replicas, waitForReady) + return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) } - return nil, errors.New("Workload type not supported " + kind) + return nil, errors.New("Workload type not supported " + scaleWorkloadArgs.kind) } func (*scaleWorkloadFunc) RequiredArgs() []string { @@ -97,14 +95,27 @@ func (*scaleWorkloadFunc) Arguments() []string { } } -func getArgs(tp param.TemplateParams, args map[string]interface{}) (namespace, kind, name string, replicas int32, waitForReady bool, err error) { +type scaleWorkloadArgs struct { + namespace string + kind string + name string + replicas int32 + waitForReady bool +} + +func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleWorkloadArgs, error) { var rep interface{} - waitForReady = true - err = Arg(args, ScaleWorkloadReplicas, &rep) + waitForReady := true + err := Arg(args, ScaleWorkloadReplicas, &rep) if err != nil { - return + return nil, err } + var ( + namespace, kind, name string + replicas int32 + ) + switch val := rep.(type) { case int: replicas = int32(val) @@ -115,13 +126,11 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (namespace, k case string: var v int if v, err = strconv.Atoi(val); err != nil { - err = errors.Wrapf(err, "Cannot convert %s to int ", val) - return + return nil, errors.Wrapf(err, "Cannot convert %s to int ", val) } replicas = int32(v) default: - err = errors.Errorf("Invalid arg type %T for Arg %s ", rep, ScaleWorkloadReplicas) - return + return nil, errors.Errorf("Invalid arg type %T for Arg %s ", rep, ScaleWorkloadReplicas) } // Populate default values for optional arguments from template parameters switch { @@ -139,25 +148,31 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (namespace, k namespace = tp.DeploymentConfig.Namespace default: if !ArgExists(args, ScaleWorkloadNamespaceArg) || !ArgExists(args, ScaleWorkloadNameArg) || !ArgExists(args, ScaleWorkloadKindArg) { - return namespace, kind, name, replicas, waitForReady, errors.New("Workload information not available via defaults or namespace/name/kind parameters") + return nil, errors.New("Workload information not available via defaults or namespace/name/kind parameters") } } err = OptArg(args, ScaleWorkloadNamespaceArg, &namespace, namespace) if err != nil { - return + return nil, err } err = OptArg(args, ScaleWorkloadNameArg, &name, name) if err != nil { - return + return nil, err } err = OptArg(args, ScaleWorkloadKindArg, &kind, kind) if err != nil { - return + return nil, err } err = OptArg(args, ScaleWorkloadWaitArg, &waitForReady, waitForReady) if err != nil { - return + return nil, err } - return + return &scaleWorkloadArgs{ + namespace: namespace, + name: name, + kind: kind, + replicas: replicas, + waitForReady: waitForReady, + }, nil } diff --git a/pkg/testutil/testutil.go b/pkg/testutil/testutil.go index 631bd69f48..3ec9d3871c 100644 --- a/pkg/testutil/testutil.go +++ b/pkg/testutil/testutil.go @@ -376,7 +376,7 @@ func CreateSecret(cli kubernetes.Interface, namespace, name string, secrettype v se.APIVersion = "v1" se.Kind = "Secret" } - return + return se, err } func GetRepoPasswordSecretData(password string) map[string][]byte { From 4c91b50893d393dc99c459f9734efa6f2c405a6a Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 14:46:36 +0530 Subject: [PATCH 06/17] Enable dupl linter --- .golangci.yml | 6 ++++++ pkg/app/cockroachdb.go | 2 +- pkg/app/couchbase.go | 2 +- pkg/app/mariadb.go | 2 +- pkg/app/mysql.go | 2 +- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 2dd533b60f..03192ca308 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,6 +16,11 @@ linters: - gocritic - lll - nakedret + - asciicheck + - depguard + - dogsled + - dupl + run: timeout: 10m # golangci-lint run's timeout. @@ -30,6 +35,7 @@ issues: - errcheck # Errors may be ignored in tests. - unparam # Tests might have unused function parameters. - lll + - dupl - text: "`ctx` is unused" # Context might not be in use in places, but for consistency, we pass it. linters: diff --git a/pkg/app/cockroachdb.go b/pkg/app/cockroachdb.go index a07ff5927d..cd967f3bd5 100644 --- a/pkg/app/cockroachdb.go +++ b/pkg/app/cockroachdb.go @@ -57,7 +57,7 @@ func (c *CockroachDB) Init(context.Context) error { return err } -func (c *CockroachDB) Install(ctx context.Context, namespace string) error { +func (c *CockroachDB) Install(ctx context.Context, namespace string) error { //nolint:dupl log.Info().Print("Installing cockroachdb cluster helm chart.", field.M{"app": c.name}) c.namespace = namespace diff --git a/pkg/app/couchbase.go b/pkg/app/couchbase.go index 7f660fbdaa..0040e156ad 100644 --- a/pkg/app/couchbase.go +++ b/pkg/app/couchbase.go @@ -80,7 +80,7 @@ func (cb *CouchbaseDB) Init(ctx context.Context) error { return err } -func (cb *CouchbaseDB) Install(ctx context.Context, ns string) error { +func (cb *CouchbaseDB) Install(ctx context.Context, ns string) error { //nolint:dupl log.Info().Print("Installing couchbase operator and cluster helm chart.", field.M{"app": cb.name}) cb.namespace = ns diff --git a/pkg/app/mariadb.go b/pkg/app/mariadb.go index c295327bc3..f17bf18a9d 100644 --- a/pkg/app/mariadb.go +++ b/pkg/app/mariadb.go @@ -74,7 +74,7 @@ func (m *MariaDB) Init(context.Context) error { return nil } -func (m *MariaDB) Install(ctx context.Context, namespace string) error { +func (m *MariaDB) Install(ctx context.Context, namespace string) error { //nolint:dupl m.namespace = namespace cli, err := helm.NewCliClient() if err != nil { diff --git a/pkg/app/mysql.go b/pkg/app/mysql.go index fde3719d41..bba3260794 100644 --- a/pkg/app/mysql.go +++ b/pkg/app/mysql.go @@ -83,7 +83,7 @@ func (mdb *MysqlDB) Init(ctx context.Context) error { return nil } -func (mdb *MysqlDB) Install(ctx context.Context, namespace string) error { +func (mdb *MysqlDB) Install(ctx context.Context, namespace string) error { //nolint:dupl mdb.namespace = namespace cli, err := helm.NewCliClient() if err != nil { From 54d1d5e2cb78bcbf3cb863823505987888d77535 Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 14:54:33 +0530 Subject: [PATCH 07/17] Enable exportloopref linter --- .golangci.yml | 2 +- pkg/aws/rds/rds.go | 3 ++- pkg/kube/snapshot/snapshot_test.go | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 03192ca308..65d7f5a57a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,7 +20,7 @@ linters: - depguard - dogsled - dupl - + - exportloopref run: timeout: 10m # golangci-lint run's timeout. diff --git a/pkg/aws/rds/rds.go b/pkg/aws/rds/rds.go index 658680fd7c..dd5249d6e3 100644 --- a/pkg/aws/rds/rds.go +++ b/pkg/aws/rds/rds.go @@ -342,7 +342,8 @@ func (r RDS) RestoreDBClusterFromDBSnapshot(ctx context.Context, instanceID, dbS func convertSGIDs(sgIDs []string) []*string { var refSGIDs []*string for _, ID := range sgIDs { - refSGIDs = append(refSGIDs, &ID) + idPtr := &ID + refSGIDs = append(refSGIDs, idPtr) } return refSGIDs } diff --git a/pkg/kube/snapshot/snapshot_test.go b/pkg/kube/snapshot/snapshot_test.go index 72f647f37f..ed1e6530ef 100644 --- a/pkg/kube/snapshot/snapshot_test.go +++ b/pkg/kube/snapshot/snapshot_test.go @@ -587,7 +587,8 @@ func (s *SnapshotTestSuite) TestNewSnapshotter(c *C) { check: IsNil, }, } { - fakeCli.Resources = []*metav1.APIResourceList{&tc.apiResources} + apiRes := tc.apiResources + fakeCli.Resources = []*metav1.APIResourceList{&apiRes} ss, err := snapshot.NewSnapshotter(fakeCli, nil) c.Assert(err, tc.check) c.Assert(reflect.TypeOf(ss).String(), Equals, tc.expected) From ad041088b8b3cbb745266973b43e162b840a669a Mon Sep 17 00:00:00 2001 From: Ankit Date: Thu, 3 Aug 2023 15:27:09 +0530 Subject: [PATCH 08/17] Enable importas linter --- .golangci.yml | 12 ++ cmd/reposervercontroller/main.go | 4 +- pkg/app/csi-snapshot.go | 32 ++-- pkg/app/mssql.go | 20 +-- pkg/app/postgresql-deploymentconfig.go | 4 +- pkg/app/rds_aurora_mysql.go | 4 +- pkg/app/rds_postgres.go | 6 +- pkg/app/utils.go | 8 +- pkg/blockstorage/ibm/client_kube_test.go | 12 +- pkg/blockstorage/ibm/utils/ibmcloud_utils.go | 4 +- pkg/blockstorage/zone/zone.go | 6 +- pkg/blockstorage/zone/zone_test.go | 168 +++++++++--------- pkg/client/listers/cr/v1alpha1/actionset.go | 4 +- pkg/client/listers/cr/v1alpha1/blueprint.go | 4 +- pkg/client/listers/cr/v1alpha1/profile.go | 4 +- .../listers/cr/v1alpha1/repositoryserver.go | 4 +- pkg/controller/controller.go | 24 +-- pkg/controller/controller_test.go | 10 +- pkg/controllers/repositoryserver/handler.go | 7 +- .../repositoryserver/repository_test.go | 8 +- .../repositoryserver_controller.go | 16 +- .../repositoryserver_controller_test.go | 71 ++++---- pkg/eventer/event_recorder.go | 6 +- pkg/filter/filter.go | 4 +- pkg/filter/filter_test.go | 14 +- pkg/function/backup_data_stats.go | 6 +- pkg/function/checkRepository.go | 6 +- .../create_csi_snapshot_static_test.go | 4 +- pkg/function/create_csi_snapshot_test.go | 18 +- .../create_volume_from_snapshot_test.go | 6 +- pkg/function/create_volume_snapshot.go | 4 +- pkg/function/create_volume_snapshot_test.go | 46 ++--- pkg/function/data_test.go | 6 +- pkg/function/delete_csi_snapshot_test.go | 16 +- pkg/function/delete_data.go | 8 +- pkg/function/describe_backups.go | 6 +- pkg/function/e2e_volume_snapshot_test.go | 26 +-- pkg/function/kube_exec_all_test.go | 4 +- pkg/function/kube_exec_test.go | 4 +- pkg/function/kube_task_test.go | 4 +- pkg/function/kubeops_test.go | 4 +- pkg/function/prepare_data.go | 6 +- pkg/function/prepare_data_test.go | 4 +- pkg/function/restore_csi_snapshot.go | 40 ++--- pkg/function/restore_csi_snapshot_test.go | 32 ++-- pkg/function/restore_data.go | 6 +- pkg/function/scale_test.go | 16 +- pkg/function/utils.go | 4 +- pkg/function/utils_test.go | 10 +- .../wait_for_snapshot_completion_test.go | 6 +- pkg/function/wait_test.go | 4 +- pkg/function/waitv2_test.go | 4 +- pkg/kanctl/profile.go | 102 +++++------ pkg/kanctl/profile_test.go | 44 ++--- pkg/kanctl/repositoryserver.go | 20 +-- pkg/kopia/command/storage/secret_utils.go | 30 ++-- .../command/storage/secret_utils_test.go | 48 ++--- pkg/kube/exec.go | 4 +- pkg/kube/exec_test.go | 26 +-- pkg/kube/fips_test.go | 12 +- pkg/kube/job.go | 34 ++-- pkg/kube/pod.go | 70 ++++---- pkg/kube/pod_runner.go | 6 +- pkg/kube/pod_runner_test.go | 18 +- pkg/kube/pod_writer_test.go | 14 +- pkg/kube/snapshot/apis/v1alpha1/types.go | 8 +- pkg/kube/snapshot/apis/v1beta1/types.go | 4 +- pkg/kube/snapshot/snapshot_alpha.go | 5 +- pkg/kube/snapshot/snapshot_beta.go | 5 +- pkg/kube/snapshot/snapshot_stable.go | 3 +- pkg/kube/snapshot/snapshot_test.go | 9 +- pkg/kube/statefulset_test.go | 4 +- pkg/kube/utils.go | 16 +- pkg/kube/volume/volume.go | 56 +++--- pkg/kube/volume/volume_test.go | 12 +- pkg/kube/workload.go | 26 +-- pkg/kube/workload_ready_test.go | 8 +- pkg/kube/workload_test.go | 10 +- pkg/location/location_test.go | 18 +- pkg/param/param.go | 28 +-- pkg/param/param_test.go | 40 ++--- pkg/reconcile/reconcile_test.go | 4 +- pkg/resource/resource_test.go | 4 +- pkg/restic/restic.go | 4 +- pkg/restic/restic_test.go | 50 +++--- pkg/secrets/aws.go | 6 +- pkg/secrets/aws_test.go | 32 ++-- pkg/secrets/azure.go | 6 +- pkg/secrets/azure_test.go | 20 +-- pkg/secrets/gcp.go | 4 +- pkg/secrets/gcp_test.go | 24 +-- .../repositoryserver/aws_secrets_test.go | 18 +- .../repositoryserver/azure_secrets_test.go | 14 +- .../repositoryserver/gcp_secrets_test.go | 14 +- .../repository_password_test.go | 18 +- ...epository_server_admin_credentials_test.go | 22 +-- .../s3compliant_secrets_test.go | 22 +-- pkg/secrets/secrets_test.go | 28 +-- pkg/testing/e2e_test.go | 6 +- pkg/testing/integration_test.go | 14 +- pkg/testutil/fixture.go | 4 +- pkg/testutil/testutil.go | 67 ++++--- pkg/validate/validate_test.go | 18 +- 103 files changed, 920 insertions(+), 915 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 65d7f5a57a..e1847359c1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,6 +21,7 @@ linters: - dogsled - dupl - exportloopref + - importas run: timeout: 10m # golangci-lint run's timeout. @@ -48,3 +49,14 @@ linters-settings: line-length: 240 nakedret: max-func-lines: 2 + importas: + no-unaliased: true + alias: + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1 + alias: crv1alpha1 \ No newline at end of file diff --git a/cmd/reposervercontroller/main.go b/cmd/reposervercontroller/main.go index 6b11ee7289..5941cd1a94 100644 --- a/cmd/reposervercontroller/main.go +++ b/cmd/reposervercontroller/main.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" - crkanisteriov1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/controllers/repositoryserver" "github.com/kanisterio/kanister/pkg/log" "github.com/kanisterio/kanister/pkg/resource" @@ -46,7 +46,7 @@ var ( func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) - utilruntime.Must(crkanisteriov1alpha1.AddToScheme(scheme)) + utilruntime.Must(crv1alpha1.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme } diff --git a/pkg/app/csi-snapshot.go b/pkg/app/csi-snapshot.go index 5a8fba0f78..43d9ef146b 100644 --- a/pkg/app/csi-snapshot.go +++ b/pkg/app/csi-snapshot.go @@ -19,7 +19,7 @@ import ( "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -36,7 +36,7 @@ type TimeLogCSI struct { namespace string name string deployment appsv1.Deployment - pvc v1.PersistentVolumeClaim + pvc corev1.PersistentVolumeClaim } // NewTimeLogCSI instantiates the TimeLogCSI integration test app @@ -184,18 +184,18 @@ func (tlc TimeLogCSI) getAppDeploymentObj() *appsv1.Deployment { Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{"app": tlc.name}, }, - Template: v1.PodTemplateSpec{ + Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"app": tlc.name}, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "test-container", Image: "ghcr.io/kanisterio/kanister-tools:0.93.0", Command: []string{"sh", "-c"}, Args: []string{"while true; do for x in $(seq 1200); do date >> /var/log/time.log; sleep 1; done; truncate /var/log/time.log --size 0; done"}, - VolumeMounts: []v1.VolumeMount{ + VolumeMounts: []corev1.VolumeMount{ { Name: "data", MountPath: "/var/log", @@ -203,11 +203,11 @@ func (tlc TimeLogCSI) getAppDeploymentObj() *appsv1.Deployment { }, }, }, - Volumes: []v1.Volume{ + Volumes: []corev1.Volume{ { Name: "data", - VolumeSource: v1.VolumeSource{ - PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ + VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: "time-log-pvc", }, }, @@ -220,19 +220,19 @@ func (tlc TimeLogCSI) getAppDeploymentObj() *appsv1.Deployment { return deployment } -func (tlc TimeLogCSI) getAppPersistentVolumeClaimObj() *v1.PersistentVolumeClaim { +func (tlc TimeLogCSI) getAppPersistentVolumeClaimObj() *corev1.PersistentVolumeClaim { storageClassName := "csi-hostpath-sc" - pvc := &v1.PersistentVolumeClaim{ + pvc := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "time-log-pvc", Labels: map[string]string{"app": tlc.name}, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ StorageClassName: &storageClassName, - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: *resource.NewQuantity(1073741824, resource.BinarySI), + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: *resource.NewQuantity(1073741824, resource.BinarySI), }, }, }, diff --git a/pkg/app/mssql.go b/pkg/app/mssql.go index b83facb5ae..c4edcc1abb 100644 --- a/pkg/app/mssql.go +++ b/pkg/app/mssql.go @@ -9,7 +9,7 @@ import ( "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/kubernetes" @@ -32,9 +32,9 @@ type MssqlDB struct { namespace string name string deployment *appsv1.Deployment - service *v1.Service - pvc *v1.PersistentVolumeClaim - secret *v1.Secret + service *corev1.Service + pvc *corev1.PersistentVolumeClaim + secret *corev1.Secret } func NewMssqlDB(name string) App { @@ -298,7 +298,7 @@ spec: return deployment, err } -func (m *MssqlDB) getPVCObj() (*v1.PersistentVolumeClaim, error) { +func (m *MssqlDB) getPVCObj() (*corev1.PersistentVolumeClaim, error) { pvcmaniFest := `kind: PersistentVolumeClaim apiVersion: v1 @@ -311,12 +311,12 @@ spec: requests: storage: 4Gi` - var pvc *v1.PersistentVolumeClaim + var pvc *corev1.PersistentVolumeClaim err := yaml.Unmarshal([]byte(pvcmaniFest), &pvc) return pvc, err } -func (m *MssqlDB) getServiceObj() (*v1.Service, error) { +func (m *MssqlDB) getServiceObj() (*corev1.Service, error) { serviceManifest := `apiVersion: v1 kind: Service @@ -331,13 +331,13 @@ spec: targetPort: 1433 type: ClusterIP` - var service *v1.Service + var service *corev1.Service err := yaml.Unmarshal([]byte(serviceManifest), &service) return service, err } -func (m MssqlDB) getSecretObj() *v1.Secret { - return &v1.Secret{ +func (m MssqlDB) getSecretObj() *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: m.name, }, diff --git a/pkg/app/postgresql-deploymentconfig.go b/pkg/app/postgresql-deploymentconfig.go index 575491d5a4..90b2356c84 100644 --- a/pkg/app/postgresql-deploymentconfig.go +++ b/pkg/app/postgresql-deploymentconfig.go @@ -23,7 +23,7 @@ import ( osversioned "github.com/openshift/client-go/apps/clientset/versioned" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -99,7 +99,7 @@ func (pgres *PostgreSQLDepConfig) Install(ctx context.Context, namespace string) } func (pgres *PostgreSQLDepConfig) createPostgreSQLSecret(ctx context.Context) error { - postgreSQLSecret := &v1.Secret{ + postgreSQLSecret := &corev1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", APIVersion: "v1", diff --git a/pkg/app/rds_aurora_mysql.go b/pkg/app/rds_aurora_mysql.go index 2d6ddf55e6..5ae9e98b98 100644 --- a/pkg/app/rds_aurora_mysql.go +++ b/pkg/app/rds_aurora_mysql.go @@ -24,7 +24,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" awsrds "github.com/aws/aws-sdk-go/service/rds" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -205,7 +205,7 @@ func (a *RDSAuroraMySQLDB) Install(ctx context.Context, namespace string) error a.host = *dbCluster.DBClusters[0].Endpoint // Configmap that is going to store the details for blueprint - cm := &v1.ConfigMap{ + cm := &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: "ConfigMap", APIVersion: "v1", diff --git a/pkg/app/rds_postgres.go b/pkg/app/rds_postgres.go index a9f778bb23..8dafff210e 100644 --- a/pkg/app/rds_postgres.go +++ b/pkg/app/rds_postgres.go @@ -25,7 +25,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" awsrds "github.com/aws/aws-sdk-go/service/rds" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -200,7 +200,7 @@ func (pdb *RDSPostgresDB) Install(ctx context.Context, ns string) error { pdb.host = *dbInstance.DBInstances[0].Endpoint.Address // Create configmap - dbconfig := &v1.ConfigMap{ + dbconfig := &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "ConfigMap", @@ -222,7 +222,7 @@ func (pdb *RDSPostgresDB) Install(ctx context.Context, ns string) error { } // Create secret - dbsecret := &v1.Secret{ + dbsecret := &corev1.Secret{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Secret", diff --git a/pkg/app/utils.go b/pkg/app/utils.go index c53dd6a99b..0b446d91e4 100644 --- a/pkg/app/utils.go +++ b/pkg/app/utils.go @@ -23,7 +23,7 @@ import ( "github.com/kanisterio/kanister/pkg/aws/rds" "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/rand" ) @@ -83,14 +83,14 @@ func bastionDebugWorkloadSpec(ctx context.Context, name string, image string, na }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": name}}, - Template: v1.PodTemplateSpec{ + Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": name, }, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: name, Image: image, diff --git a/pkg/blockstorage/ibm/client_kube_test.go b/pkg/blockstorage/ibm/client_kube_test.go index d48c02b620..e98e3e94df 100644 --- a/pkg/blockstorage/ibm/client_kube_test.go +++ b/pkg/blockstorage/ibm/client_kube_test.go @@ -22,7 +22,7 @@ import ( "os" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -36,7 +36,7 @@ const ( ) type KubeTestIBMClient struct { - k8sSec *v1.Secret + k8sSec *corev1.Secret k8scli kubernetes.Interface } @@ -57,11 +57,11 @@ func (s *KubeTestIBMClient) SetUpSuite(c *C) { s.k8scli, err = kube.NewClient() c.Assert(err, IsNil) - k8sSec := v1.Secret{ + k8sSec := corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: testSecretName, }, - Type: v1.SecretTypeOpaque, + Type: corev1.SecretTypeOpaque, Data: secretData, } s.k8sSec, err = s.k8scli.CoreV1().Secrets(IBMK8sSecretNS).Create(context.TODO(), &k8sSec, metav1.CreateOptions{}) @@ -103,11 +103,11 @@ func (s KubeTestIBMClient) TestIBMOldSecret(c *C) { s.k8scli, err = kube.NewClient() c.Assert(err, IsNil) - k8sSec := v1.Secret{ + k8sSec := corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: testOldSecretName, }, - Type: v1.SecretTypeOpaque, + Type: corev1.SecretTypeOpaque, Data: secretData, } s.k8sSec, err = s.k8scli.CoreV1().Secrets(IBMK8sSecretNS).Create(context.TODO(), &k8sSec, metav1.CreateOptions{}) diff --git a/pkg/blockstorage/ibm/utils/ibmcloud_utils.go b/pkg/blockstorage/ibm/utils/ibmcloud_utils.go index 8616947005..8467c2dd11 100644 --- a/pkg/blockstorage/ibm/utils/ibmcloud_utils.go +++ b/pkg/blockstorage/ibm/utils/ibmcloud_utils.go @@ -21,7 +21,7 @@ import ( ibmprov "github.com/IBM/ibmcloud-storage-volume-lib/lib/provider" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kanisterio/kanister/pkg/kube" @@ -43,7 +43,7 @@ func AuthorizeSoftLayerFileHosts(ctx context.Context, vol *ibmprov.Volume, slCli for _, node := range nodes.Items { for _, ip := range node.Status.Addresses { - if ip.Type == v1.NodeInternalIP { + if ip.Type == corev1.NodeInternalIP { nodeips = append(nodeips, ip.Address) } } diff --git a/pkg/blockstorage/zone/zone.go b/pkg/blockstorage/zone/zone.go index 894ac1ebfd..f90c149eb7 100644 --- a/pkg/blockstorage/zone/zone.go +++ b/pkg/blockstorage/zone/zone.go @@ -21,7 +21,7 @@ import ( "strings" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -194,14 +194,14 @@ func NodeZonesAndRegion(ctx context.Context, cli kubernetes.Interface) (map[stri // 2) Needs to be ready. // Derived from "k8s.io/kubernetes/test/e2e/framework/node" // TODO: check for taints as well -func GetReadySchedulableNodes(cli kubernetes.Interface) ([]v1.Node, error) { +func GetReadySchedulableNodes(cli kubernetes.Interface) ([]corev1.Node, error) { ns, err := cli.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) if err != nil { return nil, err } total := len(ns.Items) var unschedulable, notReady int - var l []v1.Node + var l []corev1.Node for _, node := range ns.Items { switch { case !kube.IsNodeReady(&node): diff --git a/pkg/blockstorage/zone/zone_test.go b/pkg/blockstorage/zone/zone_test.go index 4e69b5a2b5..b345ccfe80 100644 --- a/pkg/blockstorage/zone/zone_test.go +++ b/pkg/blockstorage/zone/zone_test.go @@ -23,7 +23,7 @@ import ( "github.com/kanisterio/kanister/pkg/kube" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" @@ -38,13 +38,13 @@ var _ = Suite(&ZoneSuite{}) func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { ctx := context.Background() - node1 := &v1.Node{ + node1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-a"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -52,13 +52,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { }, }, } - node2 := &v1.Node{ + node2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-b"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -66,13 +66,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { }, }, } - node3 := &v1.Node{ + node3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -81,13 +81,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { }, } // error nodes - node4 := &v1.Node{ + node4 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node4", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "False", Type: "Ready", @@ -95,16 +95,16 @@ func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { }, }, } - node5 := &v1.Node{ + node5 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node5", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-c"}, }, - Spec: v1.NodeSpec{ + Spec: corev1.NodeSpec{ Unschedulable: true, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -129,13 +129,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionGCP(c *C) { func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { ctx := context.Background() - node1 := &v1.Node{ + node1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2a"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -143,13 +143,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { }, }, } - node2 := &v1.Node{ + node2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2b"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -157,13 +157,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { }, }, } - node3 := &v1.Node{ + node3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -172,13 +172,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { }, } // error nodes - node4 := &v1.Node{ + node4 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node4", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "False", Type: "Ready", @@ -186,16 +186,16 @@ func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { }, }, } - node5 := &v1.Node{ + node5 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node5", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2c"}, }, - Spec: v1.NodeSpec{ + Spec: corev1.NodeSpec{ Unschedulable: true, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -220,13 +220,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionEBS(c *C) { func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { ctx := context.Background() - node1 := &v1.Node{ + node1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "westus2", kube.FDZoneLabelName: "westus2-1"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -234,13 +234,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { }, }, } - node2 := &v1.Node{ + node2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.TopologyRegionLabelName: "westus2", kube.TopologyZoneLabelName: "westus2-2"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -248,13 +248,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { }, }, } - node3 := &v1.Node{ + node3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "westus2", kube.FDZoneLabelName: "westus2-3"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -263,13 +263,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { }, } // non-zonal node (FaultDomain) - node4 := &v1.Node{ + node4 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node4", Labels: map[string]string{kube.FDRegionLabelName: "westus", kube.FDZoneLabelName: "0"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -278,13 +278,13 @@ func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { }, } // error nodes - node5 := &v1.Node{ + node5 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node5", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-4"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "False", Type: "Ready", @@ -292,16 +292,16 @@ func (s ZoneSuite) TestNodeZoneAndRegionAD(c *C) { }, }, } - node6 := &v1.Node{ + node6 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node6", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-5"}, }, - Spec: v1.NodeSpec{ + Spec: corev1.NodeSpec{ Unschedulable: true, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -428,13 +428,13 @@ func (s ZoneSuite) TestSanitizeZones(c *C) { func (s ZoneSuite) TestFromSourceRegionZone(c *C) { ctx := context.Background() var t = &ebsTest{} - node1 := &v1.Node{ + node1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2a"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -442,13 +442,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, }, } - node2 := &v1.Node{ + node2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2b"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -456,13 +456,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, }, } - node3 := &v1.Node{ + node3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "us-west-2", kube.FDZoneLabelName: "us-west-2c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -471,13 +471,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, } - gceNode1 := &v1.Node{ + gceNode1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-a"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -486,13 +486,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, } - gceNode2 := &v1.Node{ + gceNode2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-b"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -501,13 +501,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, } - gceNode3 := &v1.Node{ + gceNode3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "us-west2", kube.FDZoneLabelName: "us-west2-c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -516,13 +516,13 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { }, } - noZonesNode := &v1.Node{ + noZonesNode := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "noZoneNode", Labels: map[string]string{kube.FDRegionLabelName: "us-east2", kube.FDZoneLabelName: "us-east2-c"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -672,13 +672,13 @@ func (et *ebsTest) FromRegion(ctx context.Context, region string) ([]string, err } func (s ZoneSuite) TestGetReadySchedulableNodes(c *C) { - node1 := &v1.Node{ + node1 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Labels: map[string]string{kube.FDRegionLabelName: "westus2", kube.FDZoneLabelName: "westus2-1"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -686,16 +686,16 @@ func (s ZoneSuite) TestGetReadySchedulableNodes(c *C) { }, }, } - node2 := &v1.Node{ + node2 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node2", Labels: map[string]string{kube.FDRegionLabelName: "westus2", kube.FDZoneLabelName: "westus2-2"}, }, - Spec: v1.NodeSpec{ + Spec: corev1.NodeSpec{ Unschedulable: true, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "True", Type: "Ready", @@ -703,13 +703,13 @@ func (s ZoneSuite) TestGetReadySchedulableNodes(c *C) { }, }, } - node3 := &v1.Node{ + node3 := &corev1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node3", Labels: map[string]string{kube.FDRegionLabelName: "westus2", kube.FDZoneLabelName: "westus2-3"}, }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ { Status: "False", Type: "Ready", @@ -722,7 +722,7 @@ func (s ZoneSuite) TestGetReadySchedulableNodes(c *C) { c.Assert(err, IsNil) c.Assert(len(nl), Equals, 1) - node1.Spec = v1.NodeSpec{ + node1.Spec = corev1.NodeSpec{ Unschedulable: true, } cli = fake.NewSimpleClientset(node1, node2, node3) diff --git a/pkg/client/listers/cr/v1alpha1/actionset.go b/pkg/client/listers/cr/v1alpha1/actionset.go index 939eb4bd81..fd39e95ada 100644 --- a/pkg/client/listers/cr/v1alpha1/actionset.go +++ b/pkg/client/listers/cr/v1alpha1/actionset.go @@ -20,7 +20,7 @@ package v1alpha1 import ( v1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) @@ -93,7 +93,7 @@ func (s actionSetNamespaceLister) Get(name string) (*v1alpha1.ActionSet, error) return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("actionset"), name) + return nil, apierrors.NewNotFound(v1alpha1.Resource("actionset"), name) } return obj.(*v1alpha1.ActionSet), nil } diff --git a/pkg/client/listers/cr/v1alpha1/blueprint.go b/pkg/client/listers/cr/v1alpha1/blueprint.go index ba52c3a967..aa46e3ab61 100644 --- a/pkg/client/listers/cr/v1alpha1/blueprint.go +++ b/pkg/client/listers/cr/v1alpha1/blueprint.go @@ -20,7 +20,7 @@ package v1alpha1 import ( v1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) @@ -93,7 +93,7 @@ func (s blueprintNamespaceLister) Get(name string) (*v1alpha1.Blueprint, error) return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("blueprint"), name) + return nil, apierrors.NewNotFound(v1alpha1.Resource("blueprint"), name) } return obj.(*v1alpha1.Blueprint), nil } diff --git a/pkg/client/listers/cr/v1alpha1/profile.go b/pkg/client/listers/cr/v1alpha1/profile.go index 5b69bb1561..738e18987f 100644 --- a/pkg/client/listers/cr/v1alpha1/profile.go +++ b/pkg/client/listers/cr/v1alpha1/profile.go @@ -20,7 +20,7 @@ package v1alpha1 import ( v1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) @@ -93,7 +93,7 @@ func (s profileNamespaceLister) Get(name string) (*v1alpha1.Profile, error) { return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("profile"), name) + return nil, apierrors.NewNotFound(v1alpha1.Resource("profile"), name) } return obj.(*v1alpha1.Profile), nil } diff --git a/pkg/client/listers/cr/v1alpha1/repositoryserver.go b/pkg/client/listers/cr/v1alpha1/repositoryserver.go index 8f5af56852..09ca6448b2 100644 --- a/pkg/client/listers/cr/v1alpha1/repositoryserver.go +++ b/pkg/client/listers/cr/v1alpha1/repositoryserver.go @@ -20,7 +20,7 @@ package v1alpha1 import ( v1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) @@ -93,7 +93,7 @@ func (s repositoryServerNamespaceLister) Get(name string) (*v1alpha1.RepositoryS return nil, err } if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("repositoryserver"), name) + return nil, apierrors.NewNotFound(v1alpha1.Resource("repositoryserver"), name) } return obj.(*v1alpha1.RepositoryServer), nil } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index ae2da03fe7..2ce577dcd1 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -31,7 +31,7 @@ import ( "github.com/pkg/errors" "gopkg.in/tomb.v2" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" @@ -124,13 +124,13 @@ func (c *Controller) StartWatch(ctx context.Context, namespace string) error { } func checkCRAccess(ctx context.Context, cli versioned.Interface, ns string) error { - if _, err := cli.CrV1alpha1().ActionSets(ns).List(ctx, v1.ListOptions{}); err != nil { + if _, err := cli.CrV1alpha1().ActionSets(ns).List(ctx, metav1.ListOptions{}); err != nil { return errors.Wrap(err, "Could not list ActionSets") } - if _, err := cli.CrV1alpha1().Blueprints(ns).List(ctx, v1.ListOptions{}); err != nil { + if _, err := cli.CrV1alpha1().Blueprints(ns).List(ctx, metav1.ListOptions{}); err != nil { return errors.Wrap(err, "Could not list Blueprints") } - if _, err := cli.CrV1alpha1().Profiles(ns).List(ctx, v1.ListOptions{}); err != nil { + if _, err := cli.CrV1alpha1().Profiles(ns).List(ctx, metav1.ListOptions{}); err != nil { return errors.Wrap(err, "Could not list Profiles") } return nil @@ -168,7 +168,7 @@ func (c *Controller) onUpdate(oldObj, newObj interface{}) { new := newObj.(*crv1alpha1.ActionSet) if err := c.onUpdateActionSet(old, new); err != nil { bpName := new.Spec.Actions[0].Blueprint - bp, _ := c.crClient.CrV1alpha1().Blueprints(new.GetNamespace()).Get(context.TODO(), bpName, v1.GetOptions{}) + bp, _ := c.crClient.CrV1alpha1().Blueprints(new.GetNamespace()).Get(context.TODO(), bpName, metav1.GetOptions{}) c.logAndErrorEvent(context.TODO(), "Callback onUpdateActionSet() failed:", "Error", err, new, bp) } case *crv1alpha1.Blueprint: @@ -185,7 +185,7 @@ func (c *Controller) onDelete(obj interface{}) { case *crv1alpha1.ActionSet: if err := c.onDeleteActionSet(v); err != nil { bpName := v.Spec.Actions[0].Blueprint - bp, _ := c.crClient.CrV1alpha1().Blueprints(v.GetNamespace()).Get(context.TODO(), bpName, v1.GetOptions{}) + bp, _ := c.crClient.CrV1alpha1().Blueprints(v.GetNamespace()).Get(context.TODO(), bpName, metav1.GetOptions{}) c.logAndErrorEvent(context.TODO(), "Callback onDeleteActionSet() failed:", "Error", err, v, bp) } case *crv1alpha1.Blueprint: @@ -203,7 +203,7 @@ func (c *Controller) onAddActionSet(ctx context.Context, t *tomb.Tomb, as *crv1a if as.Status == nil { c.initActionSetStatus(ctx, as) } - as, err := c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Get(ctx, as.GetName(), v1.GetOptions{}) + as, err := c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Get(ctx, as.GetName(), metav1.GetOptions{}) if err != nil { return errors.WithStack(err) } @@ -303,7 +303,7 @@ func (c *Controller) initActionSetStatus(ctx context.Context, as *crv1alpha1.Act break } var bp *crv1alpha1.Blueprint - if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, v1.GetOptions{}); err != nil { + if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, metav1.GetOptions{}); err != nil { err = errors.Wrap(err, "Failed to query blueprint") c.logAndErrorEvent(ctx, "Could not get blueprint:", "Error", err, as) break @@ -326,7 +326,7 @@ func (c *Controller) initActionSetStatus(ctx context.Context, as *crv1alpha1.Act as.Status.State = crv1alpha1.StatePending as.Status.Actions = actions } - if _, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, v1.UpdateOptions{}); err != nil { + if _, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, metav1.UpdateOptions{}); err != nil { c.logAndErrorEvent(ctx, "Could not update ActionSet:", "Update Failed", err, as) } } @@ -370,7 +370,7 @@ func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1 return nil } as.Status.State = crv1alpha1.StateRunning - if as, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, v1.UpdateOptions{}); err != nil { + if as, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, metav1.UpdateOptions{}); err != nil { return errors.WithStack(err) } ctx = field.Context(ctx, consts.ActionsetNameKey, as.GetName()) @@ -391,7 +391,7 @@ func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1 for i, a := range as.Status.Actions { var bp *crv1alpha1.Blueprint - if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, v1.GetOptions{}); err != nil { + if bp, err = c.crClient.CrV1alpha1().Blueprints(as.GetNamespace()).Get(ctx, a.Blueprint, metav1.GetOptions{}); err != nil { err = errors.Wrap(err, "Failed to query blueprint") c.logAndErrorEvent(ctx, "Could not get blueprint:", "Error", err, as) break @@ -411,7 +411,7 @@ func (c *Controller) handleActionSet(ctx context.Context, t *tomb.Tomb, as *crv1 as.Status.Error = crv1alpha1.Error{ Message: err.Error(), } - _, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, v1.UpdateOptions{}) + _, err = c.crClient.CrV1alpha1().ActionSets(as.GetNamespace()).Update(ctx, as, metav1.UpdateOptions{}) return errors.WithStack(err) } log.WithContext(ctx).Print("Created actionset and started executing actions", field.M{"NewActionSetName": as.GetName()}) diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index 73f70b6a58..257ccbce41 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -24,7 +24,7 @@ import ( "github.com/pkg/errors" . "gopkg.in/check.v1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes" @@ -55,7 +55,7 @@ type ControllerSuite struct { cancel func() ss *appsv1.StatefulSet deployment *appsv1.Deployment - confimap *v1.ConfigMap + confimap *corev1.ConfigMap recorder record.EventRecorder } @@ -81,7 +81,7 @@ func (s *ControllerSuite) SetUpSuite(c *C) { s.recorder = eventer.NewEventRecorder(s.cli, "Controller Test") - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanistercontrollertest-", }, @@ -558,7 +558,7 @@ func (s *ControllerSuite) TestExecActionSet(c *C) { { funcNames: []string{testutil.ArgFuncName}, name: "ArgFuncVersionFallback", - version: "v1.2.3", + version: "corev1.2.3", }, { funcNames: []string{testutil.ArgFuncName}, @@ -568,7 +568,7 @@ func (s *ControllerSuite) TestExecActionSet(c *C) { { funcNames: []string{testutil.VersionMismatchFuncName}, name: "VersionMismatchFunc", - version: "v1.2.3", + version: "corev1.2.3", }, { funcNames: []string{testutil.ArgFuncName, testutil.OutputFuncName}, diff --git a/pkg/controllers/repositoryserver/handler.go b/pkg/controllers/repositoryserver/handler.go index a949d12352..67b864879f 100644 --- a/pkg/controllers/repositoryserver/handler.go +++ b/pkg/controllers/repositoryserver/handler.go @@ -32,7 +32,6 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - crkanisteriov1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/kube" "github.com/kanisterio/kanister/pkg/poll" @@ -331,7 +330,7 @@ func (h *RepoServerHandler) updateRepoServerProgress(ctx context.Context, progre func (h *RepoServerHandler) setupKopiaRepositoryServer(ctx context.Context, logger logr.Logger) (ctrl.Result, error) { logger.Info("Start Kopia Repository Server") if err := h.startRepoProxyServer(ctx); err != nil { - if uerr := h.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Failed); uerr != nil { + if uerr := h.updateRepoServerProgress(ctx, crv1alpha1.Failed); uerr != nil { return ctrl.Result{}, uerr } return ctrl.Result{}, err @@ -339,7 +338,7 @@ func (h *RepoServerHandler) setupKopiaRepositoryServer(ctx context.Context, logg logger.Info("Add/Update users in Kopia Repository Server") if err := h.createOrUpdateClientUsers(ctx); err != nil { - if uerr := h.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Failed); uerr != nil { + if uerr := h.updateRepoServerProgress(ctx, crv1alpha1.Failed); uerr != nil { return ctrl.Result{}, uerr } return ctrl.Result{}, err @@ -347,7 +346,7 @@ func (h *RepoServerHandler) setupKopiaRepositoryServer(ctx context.Context, logg logger.Info("Refresh Kopia Repository Server") if err := h.refreshServer(ctx); err != nil { - if uerr := h.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Failed); uerr != nil { + if uerr := h.updateRepoServerProgress(ctx, crv1alpha1.Failed); uerr != nil { return ctrl.Result{}, uerr } return ctrl.Result{}, err diff --git a/pkg/controllers/repositoryserver/repository_test.go b/pkg/controllers/repositoryserver/repository_test.go index 85c00fdfa4..1739c943fc 100644 --- a/pkg/controllers/repositoryserver/repository_test.go +++ b/pkg/controllers/repositoryserver/repository_test.go @@ -15,7 +15,7 @@ package repositoryserver import ( - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/kopia/command" "github.com/kanisterio/kanister/pkg/testutil" . "gopkg.in/check.v1" @@ -42,7 +42,7 @@ func (s *RepoServerControllerSuite) TestCacheSizeConfiguration(c *C) { c.Assert(metadataCacheMB, Equals, defaultmetadataCacheMB) // Test if configfured cache size settings are set - repositoryServer.Spec.Repository.CacheSizeSettings = v1alpha1.CacheSizeSettings{ + repositoryServer.Spec.Repository.CacheSizeSettings = crv1alpha1.CacheSizeSettings{ Metadata: "1000", Content: "1100", } @@ -52,7 +52,7 @@ func (s *RepoServerControllerSuite) TestCacheSizeConfiguration(c *C) { c.Assert(metadataCacheMB, Equals, 1000) // Check if default Content Cache size is set - repositoryServer.Spec.Repository.CacheSizeSettings = v1alpha1.CacheSizeSettings{ + repositoryServer.Spec.Repository.CacheSizeSettings = crv1alpha1.CacheSizeSettings{ Metadata: "1000", Content: "", } @@ -62,7 +62,7 @@ func (s *RepoServerControllerSuite) TestCacheSizeConfiguration(c *C) { c.Assert(metadataCacheMB, Equals, 1000) // Check if default Metadata Cache size is set - repositoryServer.Spec.Repository.CacheSizeSettings = v1alpha1.CacheSizeSettings{ + repositoryServer.Spec.Repository.CacheSizeSettings = crv1alpha1.CacheSizeSettings{ Metadata: "", Content: "1100", } diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller.go b/pkg/controllers/repositoryserver/repositoryserver_controller.go index 54a79718ec..924cf1b234 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/predicate" - crkanisteriov1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" ) // RepositoryServerReconciler reconciles a RepositoryServer object @@ -71,12 +71,12 @@ func (r *RepositoryServerReconciler) Reconcile(ctx context.Context, req ctrl.Req return ctrl.Result{}, errors.Wrap(err, "Failed to get a k8s client") } - repositoryServer := &crkanisteriov1alpha1.RepositoryServer{} + repositoryServer := &crv1alpha1.RepositoryServer{} if err = r.Get(ctx, req.NamespacedName, repositoryServer); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } - repositoryServer.Status.Progress = crkanisteriov1alpha1.Pending + repositoryServer.Status.Progress = crv1alpha1.Pending repoServerHandler := newRepositoryServerHandler(ctx, req, logger, r, kubeCli, repositoryServer) repoServerHandler.RepositoryServer = repositoryServer @@ -88,7 +88,7 @@ func (r *RepositoryServerReconciler) Reconcile(ctx context.Context, req ctrl.Req logger.Info("Create or update owned resources by Repository Server CR") if err := repoServerHandler.CreateOrUpdateOwnedResources(ctx); err != nil { logger.Info("Setting the CR status as 'Failed' since an error occurred in create/update event") - if uerr := repoServerHandler.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Failed); uerr != nil { + if uerr := repoServerHandler.updateRepoServerProgress(ctx, crv1alpha1.Failed); uerr != nil { return ctrl.Result{}, uerr } r.Recorder.Event(repoServerHandler.RepositoryServer, corev1.EventTypeWarning, "Failed", err.Error()) @@ -97,7 +97,7 @@ func (r *RepositoryServerReconciler) Reconcile(ctx context.Context, req ctrl.Req logger.Info("Connect to Kopia Repository") if err := repoServerHandler.connectToKopiaRepository(); err != nil { - if uerr := repoServerHandler.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Failed); uerr != nil { + if uerr := repoServerHandler.updateRepoServerProgress(ctx, crv1alpha1.Failed); uerr != nil { return ctrl.Result{}, uerr } return ctrl.Result{}, err @@ -107,7 +107,7 @@ func (r *RepositoryServerReconciler) Reconcile(ctx context.Context, req ctrl.Req return result, err } - if uerr := repoServerHandler.updateRepoServerProgress(ctx, crkanisteriov1alpha1.Ready); uerr != nil { + if uerr := repoServerHandler.updateRepoServerProgress(ctx, crv1alpha1.Ready); uerr != nil { return ctrl.Result{}, uerr } @@ -120,7 +120,7 @@ func newRepositoryServerHandler( logger logr.Logger, reconciler *RepositoryServerReconciler, kubeCli kubernetes.Interface, - repositoryServer *crkanisteriov1alpha1.RepositoryServer) RepoServerHandler { + repositoryServer *crv1alpha1.RepositoryServer) RepoServerHandler { return RepoServerHandler{ Req: req, Logger: logger, @@ -136,7 +136,7 @@ func (r *RepositoryServerReconciler) SetupWithManager(mgr ctrl.Manager) error { // child resources and run the same reconcile loop for all events on child resources r.Recorder = mgr.GetEventRecorderFor("RepositoryServer") return ctrl.NewControllerManagedBy(mgr). - For(&crkanisteriov1alpha1.RepositoryServer{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + For(&crv1alpha1.RepositoryServer{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). Owns(&corev1.Service{}). Owns(&networkingv1.NetworkPolicy{}). Owns(&corev1.Pod{}). diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index e8eda1bf9d..7c80ed87f2 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -24,7 +24,7 @@ import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" k8sresource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -35,7 +35,6 @@ import ( k8sscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crclientv1alpha1 "github.com/kanisterio/kanister/pkg/client/clientset/versioned/typed/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/consts" @@ -97,7 +96,7 @@ func (s *RepoServerControllerSuite) SetUpSuite(c *C) { utilruntime.Must(k8sscheme.AddToScheme(scheme)) utilruntime.Must(crv1alpha1.AddToScheme(scheme)) - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "repositoryservercontrollertest-", }, @@ -173,36 +172,36 @@ func (s *RepoServerControllerSuite) createRepositoryServerSecrets(c *C) { c.Assert(err, IsNil) } -func (s *RepoServerControllerSuite) CreateRepositoryServerAdminSecret(data map[string][]byte) (se *v1.Secret, err error) { +func (s *RepoServerControllerSuite) CreateRepositoryServerAdminSecret(data map[string][]byte) (se *corev1.Secret, err error) { return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-admin-", reposerver.AdminCredentialsSecret, data) } -func (s *RepoServerControllerSuite) CreateRepositoryServerUserAccessSecret(data map[string][]byte) (se *v1.Secret, err error) { +func (s *RepoServerControllerSuite) CreateRepositoryServerUserAccessSecret(data map[string][]byte) (se *corev1.Secret, err error) { return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-user-access-", "", data) } -func (s *RepoServerControllerSuite) CreateRepositoryPasswordSecret(data map[string][]byte) (se *v1.Secret, err error) { +func (s *RepoServerControllerSuite) CreateRepositoryPasswordSecret(data map[string][]byte) (se *corev1.Secret, err error) { return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-password-", reposerver.RepositoryPasswordSecret, data) } -func (s *RepoServerControllerSuite) CreateKopiaTLSSecret(data map[string][]byte) (se *v1.Secret, err error) { - return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-kopia-tls-", v1.SecretTypeTLS, data) +func (s *RepoServerControllerSuite) CreateKopiaTLSSecret(data map[string][]byte) (se *corev1.Secret, err error) { + return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-kopia-tls-", corev1.SecretTypeTLS, data) } -func (s *RepoServerControllerSuite) CreateStorageLocationSecret(data map[string][]byte) (se *v1.Secret, err error) { +func (s *RepoServerControllerSuite) CreateStorageLocationSecret(data map[string][]byte) (se *corev1.Secret, err error) { return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-", reposerver.Location, data) } -func (s *RepoServerControllerSuite) CreateAWSStorageCredentialsSecret(data map[string][]byte) (se *v1.Secret, err error) { - return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", v1.SecretType(secrets.AWSSecretType), data) +func (s *RepoServerControllerSuite) CreateAWSStorageCredentialsSecret(data map[string][]byte) (se *corev1.Secret, err error) { + return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", corev1.SecretType(secrets.AWSSecretType), data) } -func (s *RepoServerControllerSuite) CreateAzureStorageCredentialsSecret(data map[string][]byte) (se *v1.Secret, err error) { - return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", v1.SecretType(secrets.AzureSecretType), data) +func (s *RepoServerControllerSuite) CreateAzureStorageCredentialsSecret(data map[string][]byte) (se *corev1.Secret, err error) { + return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", corev1.SecretType(secrets.AzureSecretType), data) } -func (s *RepoServerControllerSuite) CreateGCPStorageCredentialsSecret(data map[string][]byte) (se *v1.Secret, err error) { - return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", v1.SecretType(secrets.GCPSecretType), data) +func (s *RepoServerControllerSuite) CreateGCPStorageCredentialsSecret(data map[string][]byte) (se *corev1.Secret, err error) { + return testutil.CreateSecret(s.kubeCli, s.repoServerControllerNamespace, "test-repository-server-storage-creds-", corev1.SecretType(secrets.GCPSecretType), data) } func (s *RepoServerControllerSuite) TestRepositoryServerImmutability(c *C) { @@ -274,7 +273,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerCRStateWithoutSecrets(c state, err := s.waitOnRepositoryServerState(c, repoServerCRCreated.Name) c.Assert(err, NotNil) - c.Assert(state, Equals, v1alpha1.Failed) + c.Assert(state, Equals, crv1alpha1.Failed) err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Delete(context.Background(), repoServerCRCreated.Name, metav1.DeleteOptions{}) c.Assert(err, IsNil) @@ -318,11 +317,11 @@ func (s *RepoServerControllerSuite) TestInvalidRepositoryPassword(c *C) { setRepositoryServerSecretsInCR(&s.repoServerSecrets, &originalrepoServerCR) for _, tc := range []struct { description string - testFunction func(rs *v1alpha1.RepositoryServer) + testFunction func(rs *crv1alpha1.RepositoryServer) }{ { description: "Invalid Repository Password", - testFunction: func(rs *v1alpha1.RepositoryServer) { + testFunction: func(rs *crv1alpha1.RepositoryServer) { InvalidRepositoryPassword, err := s.CreateRepositoryPasswordSecret(testutil.GetRepoPasswordSecretData("invalidPassword")) c.Assert(err, IsNil) @@ -332,7 +331,7 @@ func (s *RepoServerControllerSuite) TestInvalidRepositoryPassword(c *C) { }, { description: "Invalid Storage Location", - testFunction: func(rs *v1alpha1.RepositoryServer) { + testFunction: func(rs *crv1alpha1.RepositoryServer) { storageLocationData := testutil.GetDefaultS3CompliantStorageLocation() storageLocationData[repositoryserver.BucketKey] = []byte("invalidbucket") @@ -345,7 +344,7 @@ func (s *RepoServerControllerSuite) TestInvalidRepositoryPassword(c *C) { }, { description: "Invalid Storage location credentials", - testFunction: func(rs *v1alpha1.RepositoryServer) { + testFunction: func(rs *crv1alpha1.RepositoryServer) { storageLocationCredsData := testutil.GetDefaultS3StorageCreds(c) storageLocationCredsData[secrets.AWSAccessKeyID] = []byte("testaccesskey") @@ -365,7 +364,7 @@ func (s *RepoServerControllerSuite) TestInvalidRepositoryPassword(c *C) { state, err := s.waitOnRepositoryServerState(c, repoServerCRCreated.Name) c.Assert(err, NotNil) - c.Assert(state, Equals, v1alpha1.Failed) + c.Assert(state, Equals, crv1alpha1.Failed) } } @@ -374,15 +373,15 @@ func (s *RepoServerControllerSuite) TestFilestoreLocationVolumeMountOnRepoServer ctx := context.Background() repoServerCR := testutil.GetTestKopiaRepositoryServerCR(s.repoServerControllerNamespace) setRepositoryServerSecretsInCR(&s.repoServerSecrets, &repoServerCR) - pvc := &v1.PersistentVolumeClaim{ + pvc := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-pvc-", }, - Spec: v1.PersistentVolumeClaimSpec{ - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): k8sresource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): k8sresource.MustParse("1Gi"), }, }, }, @@ -446,11 +445,11 @@ func (s *RepoServerControllerSuite) waitForRepoServerInfoUpdateInCR(repoServerNa return err } -func (s *RepoServerControllerSuite) waitOnRepositoryServerState(c *C, reposerverName string) (v1alpha1.RepositoryServerProgress, error) { +func (s *RepoServerControllerSuite) waitOnRepositoryServerState(c *C, reposerverName string) (crv1alpha1.RepositoryServerProgress, error) { ctxTimeout := 15 * time.Minute ctx, cancel := context.WithTimeout(context.Background(), ctxTimeout) defer cancel() - var repoServerState v1alpha1.RepositoryServerProgress + var repoServerState crv1alpha1.RepositoryServerProgress err := poll.Wait(ctx, func(ctx context.Context) (bool, error) { repoServerCR, err := s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, reposerverName, metav1.GetOptions{}) if err != nil { @@ -458,13 +457,13 @@ func (s *RepoServerControllerSuite) waitOnRepositoryServerState(c *C, reposerver return false, err } repoServerState = repoServerCR.Status.Progress - if repoServerCR.Status.Progress == "" || repoServerCR.Status.Progress == v1alpha1.Pending { + if repoServerCR.Status.Progress == "" || repoServerCR.Status.Progress == crv1alpha1.Pending { return false, nil } - if repoServerCR.Status.Progress == v1alpha1.Failed { + if repoServerCR.Status.Progress == crv1alpha1.Failed { return false, errors.New(fmt.Sprintf(" There is failure in staring the repository server, server is in %s state, please check logs", repoServerCR.Status.Progress)) } - if repoServerCR.Status.Progress == v1alpha1.Ready { + if repoServerCR.Status.Progress == crv1alpha1.Ready { return true, nil } return false, errors.New(fmt.Sprintf("Unexpected Repository server state: %s", repoServerCR.Status.Progress)) @@ -496,8 +495,8 @@ func setRepositoryServerSecretsInCR(secrets *repositoryServerSecrets, repoServer } } -func getTestKanisterToolsPod(podName string) (pod *v1.Pod) { - return &v1.Pod{ +func getTestKanisterToolsPod(podName string) (pod *corev1.Pod) { + return &corev1.Pod{ TypeMeta: metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", @@ -505,8 +504,8 @@ func getTestKanisterToolsPod(podName string) (pod *v1.Pod) { ObjectMeta: metav1.ObjectMeta{ Name: podName, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "kanister-tools", Image: consts.LatestKanisterToolsImage, diff --git a/pkg/eventer/event_recorder.go b/pkg/eventer/event_recorder.go index f45265f3d3..482be8b10d 100644 --- a/pkg/eventer/event_recorder.go +++ b/pkg/eventer/event_recorder.go @@ -17,7 +17,7 @@ package eventer import ( "context" - core "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" @@ -31,12 +31,12 @@ func NewEventRecorder(client kubernetes.Interface, component string) record.Even // Event Broadcaster broadcaster := record.NewBroadcaster() broadcaster.StartEventWatcher( - func(event *core.Event) { + func(event *corev1.Event) { if _, err := client.CoreV1().Events(event.Namespace).Create(context.TODO(), event, metav1.CreateOptions{}); err != nil { log.Error().WithError(err).Print("Error while creating the event") } }, ) - return broadcaster.NewRecorder(scheme.Scheme, core.EventSource{Component: component}) + return broadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: component}) } diff --git a/pkg/filter/filter.go b/pkg/filter/filter.go index ae161213d7..440486b01a 100644 --- a/pkg/filter/filter.go +++ b/pkg/filter/filter.go @@ -15,7 +15,7 @@ package filter import ( - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" @@ -135,7 +135,7 @@ func JoinResourceTypeMatchers(ms ...ResourceTypeMatcher) ResourceTypeMatcher { // ResourceRequirement allows specifying a resource requirement by type and/or name type ResourceRequirement struct { // Provides the Name of the resource object - v1.LocalObjectReference `json:",inline,omitempty"` + corev1.LocalObjectReference `json:",inline,omitempty"` // Provides the Group, Version, and Resource values (GVR) ResourceTypeRequirement `json:",inline,omitempty"` // Specifies a set of label requirements to be used as filters for matches diff --git a/pkg/filter/filter_test.go b/pkg/filter/filter_test.go index c7eb15054e..ce2b7f2e2b 100644 --- a/pkg/filter/filter_test.go +++ b/pkg/filter/filter_test.go @@ -18,7 +18,7 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) @@ -503,7 +503,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { { // Match a specific resource m: ResourceMatcher{ - ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "pvc1"}, ResourceTypeRequirement: pvcTypeRequirement}, + ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "pvc1"}, ResourceTypeRequirement: pvcTypeRequirement}, }, resources: []Resource{ss1, ss2, pvc1, pvc2}, include: []Resource{pvc1}, @@ -512,7 +512,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { { // Match a specific resource name only (no GVR), matches only one object m: ResourceMatcher{ - ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "pvc1"}}, + ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "pvc1"}}, }, resources: []Resource{ss1, ss2, pvc1, pvc2}, include: []Resource{pvc1}, @@ -521,7 +521,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { { // Match a specific resource name only (no GVR), matches mulitple resources m: ResourceMatcher{ - ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "specificname"}}, + ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "specificname"}}, }, resources: []Resource{ss1, ss2, pvc1, pvc2}, include: []Resource{ss2, pvc2}, @@ -530,7 +530,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { { // Match a specific resource name with different GVR, matches only one object m: ResourceMatcher{ - ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "specificname"}, + ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "specificname"}, ResourceTypeRequirement: ssTypeRequirement, }, }, @@ -541,7 +541,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { { // Match by GVR and labels m: ResourceMatcher{ - ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "specificname"}, + ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "specificname"}, LabelSelector: metav1.LabelSelector{MatchLabels: map[string]string{ "testkey2": "testval2", // Include only the labels with 2 }}}, @@ -629,7 +629,7 @@ func (s *FilterSuite) TestResourceIncludeExclude(c *C) { } func (s *FilterSuite) TestResourceRequirementDeepCopyInto(c *C) { - rr := ResourceRequirement{LocalObjectReference: v1.LocalObjectReference{Name: "specificname"}, + rr := ResourceRequirement{LocalObjectReference: corev1.LocalObjectReference{Name: "specificname"}, ResourceTypeRequirement: ResourceTypeRequirement{Group: "apps", Resource: "statefulsets"}, LabelSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ diff --git a/pkg/function/backup_data_stats.go b/pkg/function/backup_data_stats.go index 2767b44468..602665e197 100644 --- a/pkg/function/backup_data_stats.go +++ b/pkg/function/backup_data_stats.go @@ -18,7 +18,7 @@ import ( "context" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" kanister "github.com/kanisterio/kanister/pkg" @@ -74,8 +74,8 @@ func backupDataStats(ctx context.Context, cli kubernetes.Interface, tp param.Tem return pr.Run(ctx, podFunc) } -func backupDataStatsPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, backupArtifactPrefix, backupID, mode string) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func backupDataStatsPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, backupArtifactPrefix, backupID, mode string) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to be ready", pod.Name) diff --git a/pkg/function/checkRepository.go b/pkg/function/checkRepository.go index 443bced7f8..1a3ede4b18 100644 --- a/pkg/function/checkRepository.go +++ b/pkg/function/checkRepository.go @@ -5,7 +5,7 @@ import ( "strings" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" kanister "github.com/kanisterio/kanister/pkg" @@ -58,8 +58,8 @@ func CheckRepository(ctx context.Context, cli kubernetes.Interface, tp param.Tem return pr.Run(ctx, podFunc) } -func CheckRepositoryPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, targetPath string) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func CheckRepositoryPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, targetPath string) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to be ready", pod.Name) diff --git a/pkg/function/create_csi_snapshot_static_test.go b/pkg/function/create_csi_snapshot_static_test.go index 4b518a677b..7e0a68be6d 100644 --- a/pkg/function/create_csi_snapshot_static_test.go +++ b/pkg/function/create_csi_snapshot_static_test.go @@ -20,7 +20,7 @@ import ( "strings" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -78,7 +78,7 @@ func (testSuite *CreateCSISnapshotStaticTestSuite) TestCreateCSISnapshotStatic(c fakeSnapshotter, err := snapshot.NewSnapshotter(fakeCli, dynCli) c.Assert(err, IsNil) - namespace := &v1.Namespace{ + namespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: namespace, }, diff --git a/pkg/function/create_csi_snapshot_test.go b/pkg/function/create_csi_snapshot_test.go index a0b3a71d31..1097ee3f77 100644 --- a/pkg/function/create_csi_snapshot_test.go +++ b/pkg/function/create_csi_snapshot_test.go @@ -18,7 +18,7 @@ import ( "context" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -87,7 +87,7 @@ func (testSuite *CreateCSISnapshotTestSuite) TestCreateCSISnapshot(c *C) { fakeCli := fake.NewSimpleClientset() fakeCli.Resources = []*metav1.APIResourceList{apiResourceList} - _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) + _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) c.Assert(err, IsNil) scheme := runtime.NewScheme() @@ -105,17 +105,17 @@ func (testSuite *CreateCSISnapshotTestSuite) TestCreateCSISnapshot(c *C) { } } -func getPVCManifest(pvcName, storageClassName string) *v1.PersistentVolumeClaim { - return &v1.PersistentVolumeClaim{ +func getPVCManifest(pvcName, storageClassName string) *corev1.PersistentVolumeClaim { + return &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: pvcName, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ StorageClassName: &storageClassName, - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: resource.MustParse("1Gi"), + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: resource.MustParse("1Gi"), }, }, }, diff --git a/pkg/function/create_volume_from_snapshot_test.go b/pkg/function/create_volume_from_snapshot_test.go index 4a3c3928b7..d2dd4a9f95 100644 --- a/pkg/function/create_volume_from_snapshot_test.go +++ b/pkg/function/create_volume_from_snapshot_test.go @@ -20,7 +20,7 @@ import ( "fmt" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" @@ -56,12 +56,12 @@ func (s *CreateVolumeFromSnapshotTestSuite) TestCreateVolumeFromSnapshot(c *C) { cli := fake.NewSimpleClientset() // fake doesn't handle generated names for PVs, so ... var i int - pvl := &v1.PersistentVolumeList{} + pvl := &corev1.PersistentVolumeList{} // kube.CreatePV() calls create() and list() which is to be handled for fake client cli.PrependReactor("create", "persistentvolumes", func(action testing.Action) (handled bool, ret runtime.Object, err error) { ca := action.(testing.CreateAction) - pv := ca.GetObject().(*v1.PersistentVolume) + pv := ca.GetObject().(*corev1.PersistentVolume) pvl.Items = append(pvl.Items, *pv) if pv.ObjectMeta.Name == "" && pv.ObjectMeta.GenerateName != "" { pv.ObjectMeta.Name = fmt.Sprintf("%s%d", pv.ObjectMeta.GenerateName, i) diff --git a/pkg/function/create_volume_snapshot.go b/pkg/function/create_volume_snapshot.go index 87f28684e7..a7189fe9de 100644 --- a/pkg/function/create_volume_snapshot.go +++ b/pkg/function/create_volume_snapshot.go @@ -23,7 +23,7 @@ import ( "sync" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -189,7 +189,7 @@ func getPVCInfo(ctx context.Context, kubeCli kubernetes.Interface, namespace str } pvLabels := pv.GetObjectMeta().GetLabels() var size int64 - if cap, ok := pv.Spec.Capacity[v1.ResourceStorage]; ok { + if cap, ok := pv.Spec.Capacity[corev1.ResourceStorage]; ok { size = cap.Value() } // Check to see which provider is the source. Spec mandates only one of the provider diff --git a/pkg/function/create_volume_snapshot_test.go b/pkg/function/create_volume_snapshot_test.go index fc404e4fc4..48a37f8ed1 100644 --- a/pkg/function/create_volume_snapshot_test.go +++ b/pkg/function/create_volume_snapshot_test.go @@ -18,7 +18,7 @@ import ( "context" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" k8sresource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" @@ -54,16 +54,16 @@ func (s *CreateVolumeSnapshotTestSuite) TestGetPVCInfo(c *C) { }, } cli := fake.NewSimpleClientset( - &v1.PersistentVolumeClaim{ + &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "pvc-test-1", Namespace: ns, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ VolumeName: "pv-test-1", }, }, - &v1.PersistentVolume{ + &corev1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: "pv-test-1", Labels: map[string]string{ @@ -71,60 +71,60 @@ func (s *CreateVolumeSnapshotTestSuite) TestGetPVCInfo(c *C) { kube.FDRegionLabelName: "us-west-2", }, }, - Spec: v1.PersistentVolumeSpec{ - Capacity: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): k8sresource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeSpec{ + Capacity: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): k8sresource.MustParse("1Gi"), }, - PersistentVolumeSource: v1.PersistentVolumeSource{ - AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ + PersistentVolumeSource: corev1.PersistentVolumeSource{ + AWSElasticBlockStore: &corev1.AWSElasticBlockStoreVolumeSource{ VolumeID: "vol-abc123", }, }, }, }, - &v1.PersistentVolumeClaim{ + &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "pvc-test-2", Namespace: ns, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ VolumeName: "pv-test-2", }, }, - &v1.PersistentVolume{ + &corev1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: "pv-test-2", }, - Spec: v1.PersistentVolumeSpec{ - Capacity: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): k8sresource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeSpec{ + Capacity: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): k8sresource.MustParse("1Gi"), }, - PersistentVolumeSource: v1.PersistentVolumeSource{ - AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ + PersistentVolumeSource: corev1.PersistentVolumeSource{ + AWSElasticBlockStore: &corev1.AWSElasticBlockStoreVolumeSource{ VolumeID: "vol-abc123", }, }, }, }, - &v1.PersistentVolumeClaim{ + &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "pvc-test-3", Namespace: ns, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ VolumeName: "pv-test-3", }, }, - &v1.PersistentVolume{ + &corev1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: "pv-test-3", Labels: map[string]string{ kube.FDZoneLabelName: "us-west-2a", }, }, - Spec: v1.PersistentVolumeSpec{ - Capacity: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): k8sresource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeSpec{ + Capacity: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): k8sresource.MustParse("1Gi"), }, }, }, diff --git a/pkg/function/data_test.go b/pkg/function/data_test.go index 7cd7763069..b285635bcb 100644 --- a/pkg/function/data_test.go +++ b/pkg/function/data_test.go @@ -21,7 +21,7 @@ import ( "os" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes" @@ -316,7 +316,7 @@ func (s *DataSuite) getTemplateParamsAndPVCName(c *C, replicas int32) (*param.Te pvcs = append(pvcs, pvc.GetName()) } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "secret-datatest-", Namespace: s.namespace, @@ -572,7 +572,7 @@ func runAction(c *C, bp crv1alpha1.Blueprint, action string, tp *param.TemplateP return out } -func (s *DataSuite) initPVCTemplateParams(c *C, pvc *v1.PersistentVolumeClaim, options map[string]string) *param.TemplateParams { +func (s *DataSuite) initPVCTemplateParams(c *C, pvc *corev1.PersistentVolumeClaim, options map[string]string) *param.TemplateParams { as := crv1alpha1.ActionSpec{ Object: crv1alpha1.ObjectReference{ Kind: param.PVCKind, diff --git a/pkg/function/delete_csi_snapshot_test.go b/pkg/function/delete_csi_snapshot_test.go index 49f1175750..1755e56c7a 100644 --- a/pkg/function/delete_csi_snapshot_test.go +++ b/pkg/function/delete_csi_snapshot_test.go @@ -18,7 +18,7 @@ import ( "context" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -81,23 +81,23 @@ func (testSuite *DeleteCSISnapshotTestSuite) TestDeleteCSISnapshot(c *C) { fakeCli := fake.NewSimpleClientset() fakeCli.Resources = []*metav1.APIResourceList{apiResourceList} - _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) + _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) c.Assert(err, IsNil) scheme := runtime.NewScheme() fakeSnapshotter, err := snapshot.NewSnapshotter(fakeCli, dynfake.NewSimpleDynamicClient(scheme)) c.Assert(err, IsNil) - originalPVC := &v1.PersistentVolumeClaim{ + originalPVC := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: testSuite.pvcName, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ StorageClassName: &testSuite.storageClass, - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: resource.MustParse("1Gi"), + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: resource.MustParse("1Gi"), }, }, }, diff --git a/pkg/function/delete_data.go b/pkg/function/delete_data.go index 97448b9001..5b2feeb03c 100644 --- a/pkg/function/delete_data.go +++ b/pkg/function/delete_data.go @@ -20,7 +20,7 @@ import ( "strings" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" kanister "github.com/kanisterio/kanister/pkg" @@ -100,8 +100,8 @@ func deleteDataPodFunc( targetPaths, deleteTags, deleteIdentifiers []string, -) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to be ready", pod.Name) @@ -158,7 +158,7 @@ func deleteDataPodFunc( } } -func pruneData(cli kubernetes.Interface, tp param.TemplateParams, pod *v1.Pod, namespace, encryptionKey, targetPath string) (string, error) { +func pruneData(cli kubernetes.Interface, tp param.TemplateParams, pod *corev1.Pod, namespace, encryptionKey, targetPath string) (string, error) { cmd, err := restic.PruneCommand(tp.Profile, targetPath, encryptionKey) if err != nil { return "", err diff --git a/pkg/function/describe_backups.go b/pkg/function/describe_backups.go index a58cf82483..34dd3801ca 100644 --- a/pkg/function/describe_backups.go +++ b/pkg/function/describe_backups.go @@ -19,7 +19,7 @@ import ( "strings" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" kanister "github.com/kanisterio/kanister/pkg" @@ -76,8 +76,8 @@ func describeBackups(ctx context.Context, cli kubernetes.Interface, tp param.Tem return pr.Run(ctx, podFunc) } -func describeBackupsPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, targetPath string) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func describeBackupsPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, targetPath string) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to be ready", pod.Name) diff --git a/pkg/function/e2e_volume_snapshot_test.go b/pkg/function/e2e_volume_snapshot_test.go index 62baa1ff08..9977fd962c 100644 --- a/pkg/function/e2e_volume_snapshot_test.go +++ b/pkg/function/e2e_volume_snapshot_test.go @@ -23,7 +23,7 @@ import ( "google.golang.org/api/compute/v1" . "gopkg.in/check.v1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" k8sresource "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic/fake" @@ -124,8 +124,8 @@ func (s *VolumeSnapshotTestSuite) SetUpTest(c *C) { } // NewTestProfileSecret function returns a pointer to a new Secret test object. -func NewTestProfileSecret(id string, secret string) *v1.Secret { - return &v1.Secret{ +func NewTestProfileSecret(id string, secret string) *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-secret-", }, @@ -267,18 +267,18 @@ func newStatefulSet(namespace string) *appsv1.StatefulSet { Spec: appsv1.StatefulSetSpec{ Replicas: &replicas, Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "test"}}, - Template: v1.PodTemplateSpec{ + Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "test", }, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "nginx", Image: "nginx:1.18.0", - VolumeMounts: []v1.VolumeMount{ + VolumeMounts: []corev1.VolumeMount{ { Name: "kanister-test-pvc-snap-vol1", MountPath: "/var/lib/vol1", @@ -288,17 +288,17 @@ func newStatefulSet(namespace string) *appsv1.StatefulSet { }, }, }, - VolumeClaimTemplates: []v1.PersistentVolumeClaim{ + VolumeClaimTemplates: []corev1.PersistentVolumeClaim{ { ObjectMeta: metav1.ObjectMeta{ Name: "kanister-test-pvc-snap-vol1", Namespace: namespace, }, - Spec: v1.PersistentVolumeClaimSpec{ - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): k8sresource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): k8sresource.MustParse("1Gi"), }, }, }, diff --git a/pkg/function/kube_exec_all_test.go b/pkg/function/kube_exec_all_test.go index 40ffbc27ba..31b793a0b8 100644 --- a/pkg/function/kube_exec_all_test.go +++ b/pkg/function/kube_exec_all_test.go @@ -19,7 +19,7 @@ import ( "fmt" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes" @@ -63,7 +63,7 @@ func (s *KubeExecAllTest) SetUpSuite(c *C) { s.osCli = osCli ctx := context.Background() - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kubeexecall-", }, diff --git a/pkg/function/kube_exec_test.go b/pkg/function/kube_exec_test.go index 81ae8d9a7a..1d6bb328af 100644 --- a/pkg/function/kube_exec_test.go +++ b/pkg/function/kube_exec_test.go @@ -20,7 +20,7 @@ import ( "strings" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes" @@ -64,7 +64,7 @@ func (s *KubeExecTest) SetUpSuite(c *C) { s.osCli = osCli ctx := context.Background() - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterkubeexectest-", }, diff --git a/pkg/function/kube_task_test.go b/pkg/function/kube_task_test.go index 1e6ea14e47..2c1f0e0a77 100644 --- a/pkg/function/kube_task_test.go +++ b/pkg/function/kube_task_test.go @@ -20,7 +20,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -43,7 +43,7 @@ func (s *KubeTaskSuite) SetUpSuite(c *C) { c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterkubetasktest-", }, diff --git a/pkg/function/kubeops_test.go b/pkg/function/kubeops_test.go index 3a9fa25cc3..30ef45abe5 100644 --- a/pkg/function/kubeops_test.go +++ b/pkg/function/kubeops_test.go @@ -20,7 +20,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" crdclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -105,7 +105,7 @@ func (s *KubeOpsSuite) SetUpSuite(c *C) { c.Assert(err, IsNil) s.dynCli = dynCli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterkubeopstest-", }, diff --git a/pkg/function/prepare_data.go b/pkg/function/prepare_data.go index 6fe46a71d7..1c6602c7f8 100644 --- a/pkg/function/prepare_data.go +++ b/pkg/function/prepare_data.go @@ -19,7 +19,7 @@ import ( "fmt" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -98,8 +98,8 @@ func prepareData(ctx context.Context, cli kubernetes.Interface, namespace, servi return pr.Run(ctx, podFunc) } -func prepareDataPodFunc(cli kubernetes.Interface) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func prepareDataPodFunc(cli kubernetes.Interface) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod completion if err := kube.WaitForPodCompletion(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to complete", pod.Name) diff --git a/pkg/function/prepare_data_test.go b/pkg/function/prepare_data_test.go index 625bc4aec1..8392efdeb2 100644 --- a/pkg/function/prepare_data_test.go +++ b/pkg/function/prepare_data_test.go @@ -19,7 +19,7 @@ import ( "fmt" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -47,7 +47,7 @@ func (s *PrepareDataSuite) SetUpSuite(c *C) { c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "preparedatatest-", }, diff --git a/pkg/function/restore_csi_snapshot.go b/pkg/function/restore_csi_snapshot.go index 6196944a5d..895aaf2997 100644 --- a/pkg/function/restore_csi_snapshot.go +++ b/pkg/function/restore_csi_snapshot.go @@ -19,7 +19,7 @@ import ( "errors" "fmt" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -68,9 +68,9 @@ type restoreCSISnapshotArgs struct { Namespace string StorageClass string RestoreSize *resource.Quantity - AccessModes []v1.PersistentVolumeAccessMode + AccessModes []corev1.PersistentVolumeAccessMode Labels map[string]string - VolumeMode v1.PersistentVolumeMode + VolumeMode corev1.PersistentVolumeMode } func (*restoreCSISnapshotFunc) Name() string { @@ -95,13 +95,13 @@ func (*restoreCSISnapshotFunc) Exec(ctx context.Context, tp param.TemplateParams if err := Arg(args, RestoreCSISnapshotRestoreSizeArg, &restoreSize); err != nil { return nil, err } - if err := OptArg(args, RestoreCSISnapshotAccessModesArg, &restoreArgs.AccessModes, []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}); err != nil { + if err := OptArg(args, RestoreCSISnapshotAccessModesArg, &restoreArgs.AccessModes, []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}); err != nil { return nil, err } if err := validateVolumeAccessModesArg(restoreArgs.AccessModes); err != nil { return nil, err } - if err := OptArg(args, RestoreCSISnapshotVolumeModeArg, &restoreArgs.VolumeMode, v1.PersistentVolumeFilesystem); err != nil { + if err := OptArg(args, RestoreCSISnapshotVolumeModeArg, &restoreArgs.VolumeMode, corev1.PersistentVolumeFilesystem); err != nil { return nil, err } if err := validateVolumeModeArg(restoreArgs.VolumeMode); err != nil { @@ -157,7 +157,7 @@ func getClient() (kubernetes.Interface, error) { return kubeCli, err } -func restoreCSISnapshot(ctx context.Context, kubeCli kubernetes.Interface, args restoreCSISnapshotArgs) (*v1.PersistentVolumeClaim, error) { +func restoreCSISnapshot(ctx context.Context, kubeCli kubernetes.Interface, args restoreCSISnapshotArgs) (*corev1.PersistentVolumeClaim, error) { pvc := newPVCManifest(args) if _, err := kubeCli.CoreV1().PersistentVolumeClaims(args.Namespace).Create(ctx, pvc, metav1.CreateOptions{}); err != nil { return nil, err @@ -165,25 +165,25 @@ func restoreCSISnapshot(ctx context.Context, kubeCli kubernetes.Interface, args return pvc, nil } -func newPVCManifest(args restoreCSISnapshotArgs) *v1.PersistentVolumeClaim { +func newPVCManifest(args restoreCSISnapshotArgs) *corev1.PersistentVolumeClaim { snapshotAPIGroup := SnapshotAPIGroup - pvc := &v1.PersistentVolumeClaim{ + pvc := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: args.PVC, Namespace: args.Namespace, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: args.AccessModes, VolumeMode: &args.VolumeMode, - DataSource: &v1.TypedLocalObjectReference{ + DataSource: &corev1.TypedLocalObjectReference{ APIGroup: &snapshotAPIGroup, Kind: "VolumeSnapshot", Name: args.Name, }, StorageClassName: &args.StorageClass, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: *args.RestoreSize, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: *args.RestoreSize, }, }, }, @@ -194,22 +194,22 @@ func newPVCManifest(args restoreCSISnapshotArgs) *v1.PersistentVolumeClaim { return pvc } -func validateVolumeModeArg(volumeMode v1.PersistentVolumeMode) error { +func validateVolumeModeArg(volumeMode corev1.PersistentVolumeMode) error { switch volumeMode { - case v1.PersistentVolumeFilesystem, - v1.PersistentVolumeBlock: + case corev1.PersistentVolumeFilesystem, + corev1.PersistentVolumeBlock: default: return errors.New("Given volumeMode " + string(volumeMode) + " is invalid") } return nil } -func validateVolumeAccessModesArg(accessModes []v1.PersistentVolumeAccessMode) error { +func validateVolumeAccessModesArg(accessModes []corev1.PersistentVolumeAccessMode) error { for _, accessModeInArg := range accessModes { switch accessModeInArg { - case v1.ReadOnlyMany, - v1.ReadWriteMany, - v1.ReadWriteOnce: + case corev1.ReadOnlyMany, + corev1.ReadWriteMany, + corev1.ReadWriteOnce: default: return errors.New("Given accessMode " + string(accessModeInArg) + " is invalid") } diff --git a/pkg/function/restore_csi_snapshot_test.go b/pkg/function/restore_csi_snapshot_test.go index be72ced748..87bd628f07 100644 --- a/pkg/function/restore_csi_snapshot_test.go +++ b/pkg/function/restore_csi_snapshot_test.go @@ -20,7 +20,7 @@ import ( "github.com/kanisterio/kanister/pkg/kube/snapshot" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -85,7 +85,7 @@ func (testSuite *RestoreCSISnapshotTestSuite) TestRestoreCSISnapshot(c *C) { fakeCli := fake.NewSimpleClientset() fakeCli.Resources = []*metav1.APIResourceList{apiResourceList} - _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) + _, err := fakeCli.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testSuite.namespace}}, metav1.CreateOptions{}) c.Assert(err, IsNil) scheme := runtime.NewScheme() @@ -123,7 +123,7 @@ func (testSuite *RestoreCSISnapshotTestSuite) TestRestoreCSISnapshot(c *C) { func (testSuite *RestoreCSISnapshotTestSuite) TestValidateVolumeModeArg(c *C) { for _, scenario := range []struct { - Arg v1.PersistentVolumeMode + Arg corev1.PersistentVolumeMode ExpectedErr Checker }{ { @@ -131,7 +131,7 @@ func (testSuite *RestoreCSISnapshotTestSuite) TestValidateVolumeModeArg(c *C) { ExpectedErr: NotNil, }, { - Arg: v1.PersistentVolumeFilesystem, + Arg: corev1.PersistentVolumeFilesystem, ExpectedErr: IsNil, }, } { @@ -142,15 +142,15 @@ func (testSuite *RestoreCSISnapshotTestSuite) TestValidateVolumeModeArg(c *C) { func (testSuite *RestoreCSISnapshotTestSuite) TestValidateAccessModeArg(c *C) { for _, scenario := range []struct { - Arg []v1.PersistentVolumeAccessMode + Arg []corev1.PersistentVolumeAccessMode ExpectedErr Checker }{ { - Arg: []v1.PersistentVolumeAccessMode{"test"}, + Arg: []corev1.PersistentVolumeAccessMode{"test"}, ExpectedErr: NotNil, }, { - Arg: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + Arg: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, ExpectedErr: IsNil, }, } { @@ -159,24 +159,24 @@ func (testSuite *RestoreCSISnapshotTestSuite) TestValidateAccessModeArg(c *C) { } } -func createPVC(c *C, namespace string, pvc *v1.PersistentVolumeClaim, fakeCli *fake.Clientset) { +func createPVC(c *C, namespace string, pvc *corev1.PersistentVolumeClaim, fakeCli *fake.Clientset) { _, err := fakeCli.CoreV1().PersistentVolumeClaims(namespace).Create(context.TODO(), pvc, metav1.CreateOptions{}) c.Assert(err, IsNil) } -func getOriginalPVCManifest(pvcName, storageClassName string) *v1.PersistentVolumeClaim { - volumeMode := v1.PersistentVolumeFilesystem - return &v1.PersistentVolumeClaim{ +func getOriginalPVCManifest(pvcName, storageClassName string) *corev1.PersistentVolumeClaim { + volumeMode := corev1.PersistentVolumeFilesystem + return &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: pvcName, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ StorageClassName: &storageClassName, - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, VolumeMode: &volumeMode, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: resource.MustParse("1Gi"), + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: resource.MustParse("1Gi"), }, }, }, diff --git a/pkg/function/restore_data.go b/pkg/function/restore_data.go index c8d82a4887..654a79be18 100644 --- a/pkg/function/restore_data.go +++ b/pkg/function/restore_data.go @@ -18,7 +18,7 @@ import ( "context" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -129,8 +129,8 @@ func restoreData(ctx context.Context, cli kubernetes.Interface, tp param.Templat return pr.Run(ctx, podFunc) } -func restoreDataPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, backupArtifactPrefix, restorePath, backupTag, backupID string) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func restoreDataPodFunc(cli kubernetes.Interface, tp param.TemplateParams, namespace, encryptionKey, backupArtifactPrefix, restorePath, backupTag, backupID string) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { // Wait for pod to reach running state if err := kube.WaitForPodReady(ctx, cli, pod.Namespace, pod.Name); err != nil { return nil, errors.Wrapf(err, "Failed while waiting for Pod %s to be ready", pod.Name) diff --git a/pkg/function/scale_test.go b/pkg/function/scale_test.go index 887767e0ab..cc858ec275 100644 --- a/pkg/function/scale_test.go +++ b/pkg/function/scale_test.go @@ -19,7 +19,7 @@ import ( "fmt" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes" @@ -61,7 +61,7 @@ func (s *ScaleSuite) SetUpTest(c *C) { err = resource.CreateCustomResources(context.Background(), config) c.Assert(err, IsNil) - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanister-scale-test-", }, @@ -134,9 +134,9 @@ func newScaleBlueprint(kind string) *crv1alpha1.Blueprint { func (s *ScaleSuite) TestScaleDeployment(c *C) { ctx := context.Background() d := testutil.NewTestDeployment(1) - d.Spec.Template.Spec.Containers[0].Lifecycle = &v1.Lifecycle{ - PreStop: &v1.LifecycleHandler{ - Exec: &v1.ExecAction{ + d.Spec.Template.Spec.Containers[0].Lifecycle = &corev1.Lifecycle{ + PreStop: &corev1.LifecycleHandler{ + Exec: &corev1.ExecAction{ Command: []string{"sleep", "30"}, }, }, @@ -183,9 +183,9 @@ func (s *ScaleSuite) TestScaleDeployment(c *C) { func (s *ScaleSuite) TestScaleStatefulSet(c *C) { ctx := context.Background() ss := testutil.NewTestStatefulSet(1) - ss.Spec.Template.Spec.Containers[0].Lifecycle = &v1.Lifecycle{ - PreStop: &v1.LifecycleHandler{ - Exec: &v1.ExecAction{ + ss.Spec.Template.Spec.Containers[0].Lifecycle = &corev1.Lifecycle{ + PreStop: &corev1.LifecycleHandler{ + Exec: &corev1.ExecAction{ Command: []string{"sleep", "30"}, }, }, diff --git a/pkg/function/utils.go b/pkg/function/utils.go index 1f5b831b34..8db1bc1f00 100644 --- a/pkg/function/utils.go +++ b/pkg/function/utils.go @@ -11,7 +11,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" rdserr "github.com/aws/aws-sdk-go/service/rds" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -249,7 +249,7 @@ func rdsDBEngineVersion(ctx context.Context, rdsCli *rds.RDS, instanceID string) } func createPostgresSecret(cli kubernetes.Interface, name, namespace, username, password string) error { - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, diff --git a/pkg/function/utils_test.go b/pkg/function/utils_test.go index 7d1fa1ceeb..67fc47b342 100644 --- a/pkg/function/utils_test.go +++ b/pkg/function/utils_test.go @@ -16,7 +16,7 @@ package function import ( . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/param" @@ -134,8 +134,8 @@ func newValidProfileWithSecretCredentials() *param.Profile { }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AWSSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AWSSecretType), Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte("key-id"), secrets.AWSSecretAccessKey: []byte("access-key"), @@ -177,8 +177,8 @@ func newInvalidProfileWithSecretCredentials() *param.Profile { }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AWSSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AWSSecretType), Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte("key-id"), secrets.AWSSecretAccessKey: []byte("access-key"), diff --git a/pkg/function/wait_for_snapshot_completion_test.go b/pkg/function/wait_for_snapshot_completion_test.go index ea55ff6e97..b2a9c9eee1 100644 --- a/pkg/function/wait_for_snapshot_completion_test.go +++ b/pkg/function/wait_for_snapshot_completion_test.go @@ -19,7 +19,7 @@ import ( "encoding/json" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/blockstorage" @@ -74,8 +74,8 @@ func (s *WaitForSnapshotCompletionTestSuite) TestWaitwithRole(c *C) { }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AWSSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AWSSecretType), Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte("key-id"), secrets.AWSSecretAccessKey: []byte("access-key"), diff --git a/pkg/function/wait_test.go b/pkg/function/wait_test.go index 511e6474ae..417fbc6945 100644 --- a/pkg/function/wait_test.go +++ b/pkg/function/wait_test.go @@ -19,7 +19,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -44,7 +44,7 @@ func (s *WaitSuite) SetUpSuite(c *C) { c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterwaittest-", }, diff --git a/pkg/function/waitv2_test.go b/pkg/function/waitv2_test.go index fc28bb02fc..1800a2538e 100644 --- a/pkg/function/waitv2_test.go +++ b/pkg/function/waitv2_test.go @@ -19,7 +19,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -44,7 +44,7 @@ func (s *WaitV2Suite) SetUpSuite(c *C) { c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterwaittest-", }, diff --git a/pkg/kanctl/profile.go b/pkg/kanctl/profile.go index 2938712bb6..c7628dd946 100644 --- a/pkg/kanctl/profile.go +++ b/pkg/kanctl/profile.go @@ -24,13 +24,13 @@ import ( "github.com/spf13/cobra" "golang.org/x/oauth2/google" compute "google.golang.org/api/compute/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8sYAML "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/kubernetes" "sigs.k8s.io/yaml" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/client/clientset/versioned" "github.com/kanisterio/kanister/pkg/secrets" "github.com/kanisterio/kanister/pkg/utils" @@ -62,7 +62,7 @@ const ( ) type locationParams struct { - locationType v1alpha1.LocationType + locationType crv1alpha1.LocationType profileName string namespace string bucket string @@ -188,7 +188,7 @@ func createNewProfile(cmd *cobra.Command, args []string) error { } func getLocationParams(cmd *cobra.Command) (*locationParams, error) { - var lType v1alpha1.LocationType + var lType crv1alpha1.LocationType var profileName string ns, err := resolveNamespace(cmd) if err != nil { @@ -202,13 +202,13 @@ func getLocationParams(cmd *cobra.Command) (*locationParams, error) { switch cmd.Name() { case "s3compliant": - lType = v1alpha1.LocationTypeS3Compliant + lType = crv1alpha1.LocationTypeS3Compliant profileName = "s3-profile-" case "gcp": - lType = v1alpha1.LocationTypeGCS + lType = crv1alpha1.LocationTypeGCS profileName = "gcp-profile-" case "azure": - lType = v1alpha1.LocationTypeAzure + lType = crv1alpha1.LocationTypeAzure profileName = "azure-profile-" default: return nil, errors.New("Profile type not supported: " + cmd.Name()) @@ -226,68 +226,68 @@ func getLocationParams(cmd *cobra.Command) (*locationParams, error) { }, nil } -func constructProfile(lP *locationParams, secret *v1.Secret) *v1alpha1.Profile { - var creds v1alpha1.Credential +func constructProfile(lP *locationParams, secret *corev1.Secret) *crv1alpha1.Profile { + var creds crv1alpha1.Credential switch { - case lP.locationType == v1alpha1.LocationTypeS3Compliant && string(secret.StringData[secrets.ConfigRole]) != "": // aws case with role - creds = v1alpha1.Credential{ - Type: v1alpha1.CredentialTypeSecret, - Secret: &v1alpha1.ObjectReference{ + case lP.locationType == crv1alpha1.LocationTypeS3Compliant && string(secret.StringData[secrets.ConfigRole]) != "": // aws case with role + creds = crv1alpha1.Credential{ + Type: crv1alpha1.CredentialTypeSecret, + Secret: &crv1alpha1.ObjectReference{ Name: secret.GetName(), Namespace: secret.GetNamespace(), }, } - case lP.locationType == v1alpha1.LocationTypeAzure && string(secret.StringData[secrets.AzureStorageEnvironment]) != "": // azure case with env - creds = v1alpha1.Credential{ - Type: v1alpha1.CredentialTypeSecret, - Secret: &v1alpha1.ObjectReference{ + case lP.locationType == crv1alpha1.LocationTypeAzure && string(secret.StringData[secrets.AzureStorageEnvironment]) != "": // azure case with env + creds = crv1alpha1.Credential{ + Type: crv1alpha1.CredentialTypeSecret, + Secret: &crv1alpha1.ObjectReference{ Name: secret.GetName(), Namespace: secret.GetNamespace(), }, } - case lP.locationType == v1alpha1.LocationTypeAzure && string(secret.StringData[secrets.AzureStorageEnvironment]) == "": // azure case without env (type keypair) - creds = v1alpha1.Credential{ - Type: v1alpha1.CredentialTypeKeyPair, - KeyPair: &v1alpha1.KeyPair{ + case lP.locationType == crv1alpha1.LocationTypeAzure && string(secret.StringData[secrets.AzureStorageEnvironment]) == "": // azure case without env (type keypair) + creds = crv1alpha1.Credential{ + Type: crv1alpha1.CredentialTypeKeyPair, + KeyPair: &crv1alpha1.KeyPair{ IDField: secrets.AzureStorageAccountID, SecretField: secrets.AzureStorageAccountKey, - Secret: v1alpha1.ObjectReference{ + Secret: crv1alpha1.ObjectReference{ Name: secret.GetName(), Namespace: secret.GetNamespace(), }, }, } - case lP.locationType == v1alpha1.LocationTypeGCS: // GCP - creds = v1alpha1.Credential{ - Type: v1alpha1.CredentialTypeKeyPair, - KeyPair: &v1alpha1.KeyPair{ + case lP.locationType == crv1alpha1.LocationTypeGCS: // GCP + creds = crv1alpha1.Credential{ + Type: crv1alpha1.CredentialTypeKeyPair, + KeyPair: &crv1alpha1.KeyPair{ IDField: secrets.GCPProjectID, SecretField: secrets.GCPServiceKey, - Secret: v1alpha1.ObjectReference{ + Secret: crv1alpha1.ObjectReference{ Name: secret.GetName(), Namespace: secret.GetNamespace(), }, }, } default: // All others fall into the AWS key pair format - creds = v1alpha1.Credential{ - Type: v1alpha1.CredentialTypeKeyPair, - KeyPair: &v1alpha1.KeyPair{ + creds = crv1alpha1.Credential{ + Type: crv1alpha1.CredentialTypeKeyPair, + KeyPair: &crv1alpha1.KeyPair{ IDField: secrets.AWSAccessKeyID, SecretField: secrets.AWSSecretAccessKey, - Secret: v1alpha1.ObjectReference{ + Secret: crv1alpha1.ObjectReference{ Name: secret.GetName(), Namespace: secret.GetNamespace(), }, }, } } - return &v1alpha1.Profile{ + return &crv1alpha1.Profile{ ObjectMeta: metav1.ObjectMeta{ Namespace: lP.namespace, GenerateName: lP.profileName, }, - Location: v1alpha1.Location{ + Location: crv1alpha1.Location{ Type: lP.locationType, Bucket: lP.bucket, Endpoint: lP.endpoint, @@ -299,12 +299,12 @@ func constructProfile(lP *locationParams, secret *v1.Secret) *v1alpha1.Profile { } } -func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command) (*v1.Secret, error) { +func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command) (*corev1.Secret, error) { data := make(map[string]string, 2) var roleKey string secretname := "" switch lP.locationType { - case v1alpha1.LocationTypeS3Compliant: + case crv1alpha1.LocationTypeS3Compliant: accessKey, _ := cmd.Flags().GetString(awsAccessKeyFlag) secretKey, _ := cmd.Flags().GetString(awsSecretKeyFlag) roleKey, _ = cmd.Flags().GetString(awsRoleFlag) @@ -312,7 +312,7 @@ func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command data[secrets.AWSSecretAccessKey] = secretKey data[secrets.ConfigRole] = roleKey secretname = "s3" - case v1alpha1.LocationTypeGCS: + case crv1alpha1.LocationTypeGCS: projectID, _ := cmd.Flags().GetString(gcpProjectIDFlag) filePath, _ := cmd.Flags().GetString(gcpServiceKeyFlag) serviceKey, err := getServiceKey(ctx, filePath) @@ -322,7 +322,7 @@ func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command data[secrets.GCPProjectID] = projectID data[secrets.GCPServiceKey] = serviceKey secretname = "gcp" - case v1alpha1.LocationTypeAzure: + case crv1alpha1.LocationTypeAzure: storageAccount, _ := cmd.Flags().GetString(AzureStorageAccountFlag) storageKey, _ := cmd.Flags().GetString(AzureStorageKeyFlag) storageEnv, _ := cmd.Flags().GetString(AzureStorageEnvFlag) @@ -331,7 +331,7 @@ func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command data[secrets.AzureStorageEnvironment] = storageEnv secretname = "azure" } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf(secretFormat, secretname, randString(6)), Namespace: lP.namespace, @@ -339,12 +339,12 @@ func constructSecret(ctx context.Context, lP *locationParams, cmd *cobra.Command StringData: data, } if roleKey != "" { - secret.Type = v1.SecretType(secrets.AWSSecretType) + secret.Type = corev1.SecretType(secrets.AWSSecretType) } return secret, nil } -func createSecret(ctx context.Context, s *v1.Secret, cli kubernetes.Interface) (*v1.Secret, error) { +func createSecret(ctx context.Context, s *corev1.Secret, cli kubernetes.Interface) (*corev1.Secret, error) { secret, err := cli.CoreV1().Secrets(s.GetNamespace()).Create(ctx, s, metav1.CreateOptions{}) if err != nil { return nil, err @@ -353,7 +353,7 @@ func createSecret(ctx context.Context, s *v1.Secret, cli kubernetes.Interface) ( return secret, nil } -func deleteSecret(ctx context.Context, secret *v1.Secret, cli kubernetes.Interface) error { +func deleteSecret(ctx context.Context, secret *corev1.Secret, cli kubernetes.Interface) error { err := cli.CoreV1().Secrets(secret.GetNamespace()).Delete(ctx, secret.GetName(), metav1.DeleteOptions{}) if err == nil { fmt.Printf("secret '%s' deleted\n", secret.GetName()) @@ -361,10 +361,10 @@ func deleteSecret(ctx context.Context, secret *v1.Secret, cli kubernetes.Interfa return err } -func printSecret(secret *v1.Secret) error { +func printSecret(secret *corev1.Secret) error { secret.TypeMeta = metav1.TypeMeta{ Kind: reflect.TypeOf(*secret).Name(), - APIVersion: v1.SchemeGroupVersion.String(), + APIVersion: corev1.SchemeGroupVersion.String(), } secYAML, err := yaml.Marshal(secret) if err != nil { @@ -374,10 +374,10 @@ func printSecret(secret *v1.Secret) error { return nil } -func printProfile(profile *v1alpha1.Profile) error { +func printProfile(profile *crv1alpha1.Profile) error { profile.TypeMeta = metav1.TypeMeta{ - Kind: v1alpha1.ProfileResource.Kind, - APIVersion: v1alpha1.SchemeGroupVersion.String(), + Kind: crv1alpha1.ProfileResource.Kind, + APIVersion: crv1alpha1.SchemeGroupVersion.String(), } profYAML, err := yaml.Marshal(profile) if err != nil { @@ -387,7 +387,7 @@ func printProfile(profile *v1alpha1.Profile) error { return nil } -func createProfile(ctx context.Context, profile *v1alpha1.Profile, crCli versioned.Interface) error { +func createProfile(ctx context.Context, profile *crv1alpha1.Profile, crCli versioned.Interface) error { profile, err := crCli.CrV1alpha1().Profiles(profile.GetNamespace()).Create(ctx, profile, metav1.CreateOptions{}) if err == nil { fmt.Printf("profile '%s' created\n", profile.GetName()) @@ -409,7 +409,7 @@ func performProfileValidation(p *validateParams) error { return validateProfile(ctx, prof, cli, p.schemaValidationOnly, false) } -func validateProfile(ctx context.Context, profile *v1alpha1.Profile, cli kubernetes.Interface, schemaValidationOnly bool, printFailStageOnly bool) error { +func validateProfile(ctx context.Context, profile *crv1alpha1.Profile, cli kubernetes.Interface, schemaValidationOnly bool, printFailStageOnly bool) error { var err error if err = validate.ProfileSchema(profile); err != nil { utils.PrintStage(schemaValidation, utils.Fail) @@ -450,14 +450,14 @@ func validateProfile(ctx context.Context, profile *v1alpha1.Profile, cli kuberne return nil } -func getProfileFromCmd(ctx context.Context, crCli versioned.Interface, p *validateParams) (*v1alpha1.Profile, error) { +func getProfileFromCmd(ctx context.Context, crCli versioned.Interface, p *validateParams) (*crv1alpha1.Profile, error) { if p.name != "" { return crCli.CrV1alpha1().Profiles(p.namespace).Get(ctx, p.name, metav1.GetOptions{}) } return getProfileFromFile(ctx, p.filename) } -func getProfileFromFile(ctx context.Context, filename string) (*v1alpha1.Profile, error) { +func getProfileFromFile(ctx context.Context, filename string) (*crv1alpha1.Profile, error) { var f *os.File var err error @@ -471,7 +471,7 @@ func getProfileFromFile(ctx context.Context, filename string) (*v1alpha1.Profile defer f.Close() } d := k8sYAML.NewYAMLOrJSONDecoder(f, 4096) - prof := &v1alpha1.Profile{} + prof := &crv1alpha1.Profile{} err = d.Decode(prof) if err != nil { return nil, err diff --git a/pkg/kanctl/profile_test.go b/pkg/kanctl/profile_test.go index 5f1a612616..301bcf755b 100644 --- a/pkg/kanctl/profile_test.go +++ b/pkg/kanctl/profile_test.go @@ -1,24 +1,24 @@ package kanctl import ( - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/secrets" check "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func (k *KanctlTestSuite) TestConstructProfile(c *check.C) { for _, tc := range []struct { lp *locationParams - secret *v1.Secret - retCredType v1alpha1.CredentialType + secret *corev1.Secret + retCredType crv1alpha1.CredentialType }{ { lp: &locationParams{ - locationType: v1alpha1.LocationTypeS3Compliant, + locationType: crv1alpha1.LocationTypeS3Compliant, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -27,13 +27,13 @@ func (k *KanctlTestSuite) TestConstructProfile(c *check.C) { secrets.ConfigRole: "role", }, }, - retCredType: v1alpha1.CredentialTypeSecret, + retCredType: crv1alpha1.CredentialTypeSecret, }, { lp: &locationParams{ - locationType: v1alpha1.LocationTypeAzure, + locationType: crv1alpha1.LocationTypeAzure, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -42,13 +42,13 @@ func (k *KanctlTestSuite) TestConstructProfile(c *check.C) { secrets.AzureStorageEnvironment: "env", }, }, - retCredType: v1alpha1.CredentialTypeSecret, + retCredType: crv1alpha1.CredentialTypeSecret, }, { lp: &locationParams{ - locationType: v1alpha1.LocationTypeAzure, + locationType: crv1alpha1.LocationTypeAzure, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -57,44 +57,44 @@ func (k *KanctlTestSuite) TestConstructProfile(c *check.C) { secrets.AzureStorageEnvironment: "", }, }, - retCredType: v1alpha1.CredentialTypeKeyPair, + retCredType: crv1alpha1.CredentialTypeKeyPair, }, { lp: &locationParams{ - locationType: v1alpha1.LocationTypeAzure, + locationType: crv1alpha1.LocationTypeAzure, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", }, StringData: map[string]string{}, }, - retCredType: v1alpha1.CredentialTypeKeyPair, + retCredType: crv1alpha1.CredentialTypeKeyPair, }, { lp: &locationParams{ - locationType: v1alpha1.LocationTypeGCS, + locationType: crv1alpha1.LocationTypeGCS, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", }, }, - retCredType: v1alpha1.CredentialTypeKeyPair, + retCredType: crv1alpha1.CredentialTypeKeyPair, }, { lp: &locationParams{ - locationType: v1alpha1.LocationTypeS3Compliant, + locationType: crv1alpha1.LocationTypeS3Compliant, }, - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", }, }, - retCredType: v1alpha1.CredentialTypeKeyPair, + retCredType: crv1alpha1.CredentialTypeKeyPair, }, } { prof := constructProfile(tc.lp, tc.secret) diff --git a/pkg/kanctl/repositoryserver.go b/pkg/kanctl/repositoryserver.go index a3ac978649..d4bdad7579 100644 --- a/pkg/kanctl/repositoryserver.go +++ b/pkg/kanctl/repositoryserver.go @@ -26,7 +26,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/client/clientset/versioned" "github.com/kanisterio/kanister/pkg/kube" "github.com/kanisterio/kanister/pkg/poll" @@ -194,7 +194,7 @@ func generateRepositoryServerParams(cmd *cobra.Command) (*repositoryServerParams }, nil } -func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParams) (*v1alpha1.RepositoryServer, error) { +func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParams) (*crv1alpha1.RepositoryServer, error) { // Fetch and Validate Secrets ctx := context.Background() config, err := kube.LoadConfig() @@ -230,12 +230,12 @@ func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParam return nil, err } - return &v1alpha1.RepositoryServer{ + return &crv1alpha1.RepositoryServer{ ObjectMeta: metav1.ObjectMeta{ GenerateName: `kopia-repo-server-`, }, - Spec: v1alpha1.RepositoryServerSpec{ - Storage: v1alpha1.Storage{ + Spec: crv1alpha1.RepositoryServerSpec{ + Storage: crv1alpha1.Storage{ SecretRef: corev1.SecretReference{ Name: locationSecret.GetName(), Namespace: locationSecret.GetNamespace(), @@ -245,7 +245,7 @@ func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParam Namespace: locationCredsSecret.GetNamespace(), }, }, - Repository: v1alpha1.Repository{ + Repository: crv1alpha1.Repository{ RootPath: rsParams.prefix, Username: rsParams.repositoryUser, Hostname: defaultRepositoryServerHost, @@ -254,8 +254,8 @@ func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParam Namespace: repositoryPasswordSecret.GetNamespace(), }, }, - Server: v1alpha1.Server{ - UserAccess: v1alpha1.UserAccess{ + Server: crv1alpha1.Server{ + UserAccess: crv1alpha1.UserAccess{ UserAccessSecretRef: corev1.SecretReference{ Name: repositoryServerUserAccessSecret.GetName(), Namespace: repositoryServerUserAccessSecret.GetNamespace(), @@ -275,12 +275,12 @@ func validateSecretsAndConstructRepositoryServer(rsParams *repositoryServerParam }, nil } -func waitForRepositoryServerReady(ctx context.Context, cli *kubernetes.Clientset, crCli *versioned.Clientset, rs *v1alpha1.RepositoryServer) error { +func waitForRepositoryServerReady(ctx context.Context, cli *kubernetes.Clientset, crCli *versioned.Clientset, rs *crv1alpha1.RepositoryServer) error { timeoutCtx, waitCancel := context.WithTimeout(ctx, contextWaitTimeout) defer waitCancel() pollErr := poll.Wait(timeoutCtx, func(ctx context.Context) (bool, error) { repositoryServer, err := crCli.CrV1alpha1().RepositoryServers(rs.GetNamespace()).Get(ctx, rs.GetName(), metav1.GetOptions{}) - if repositoryServer.Status.Progress == v1alpha1.Ready && err == nil { + if repositoryServer.Status.Progress == crv1alpha1.Ready && err == nil { return true, nil } return false, err diff --git a/pkg/kopia/command/storage/secret_utils.go b/pkg/kopia/command/storage/secret_utils.go index 1935f7354b..616b13ebdd 100644 --- a/pkg/kopia/command/storage/secret_utils.go +++ b/pkg/kopia/command/storage/secret_utils.go @@ -20,9 +20,9 @@ import ( "github.com/Azure/go-autorest/autorest/azure" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/secrets" "github.com/kanisterio/kanister/pkg/secrets/repositoryserver" @@ -62,7 +62,7 @@ func locationType(m map[string][]byte) repositoryserver.LocType { // GenerateEnvSpecFromCredentialSecret parses the secret and returns // list of EnvVar based on secret type -func GenerateEnvSpecFromCredentialSecret(s *v1.Secret, assumeRoleDurationS3 time.Duration) ([]v1.EnvVar, error) { +func GenerateEnvSpecFromCredentialSecret(s *corev1.Secret, assumeRoleDurationS3 time.Duration) ([]corev1.EnvVar, error) { if s == nil { return nil, errors.New("Secret cannot be nil") } @@ -78,9 +78,9 @@ func GenerateEnvSpecFromCredentialSecret(s *v1.Secret, assumeRoleDurationS3 time return nil, nil } -func getEnvSpecForAWSCredentialSecret(s *v1.Secret, assumeRoleDuration time.Duration) ([]v1.EnvVar, error) { +func getEnvSpecForAWSCredentialSecret(s *corev1.Secret, assumeRoleDuration time.Duration) ([]corev1.EnvVar, error) { var err error - envVars := []v1.EnvVar{} + envVars := []corev1.EnvVar{} envVars = append( envVars, getEnvVarWithSecretRef(aws.AccessKeyID, s.Name, secrets.AWSAccessKeyID), @@ -96,8 +96,8 @@ func getEnvSpecForAWSCredentialSecret(s *v1.Secret, assumeRoleDuration time.Dura return envVars, nil } -func getEnvSpecForAzureCredentialSecret(s *v1.Secret) ([]v1.EnvVar, error) { - envVars := []v1.EnvVar{} +func getEnvSpecForAzureCredentialSecret(s *corev1.Secret) ([]corev1.EnvVar, error) { + envVars := []corev1.EnvVar{} envVars = append( envVars, getEnvVarWithSecretRef(azureStorageAccountEnv, s.Name, secrets.AzureStorageAccountID), @@ -120,13 +120,13 @@ func getEnvSpecForAzureCredentialSecret(s *v1.Secret) ([]v1.EnvVar, error) { return envVars, nil } -func getEnvVarWithSecretRef(varName, secretName, secretKey string) v1.EnvVar { - return v1.EnvVar{ +func getEnvVarWithSecretRef(varName, secretName, secretKey string) corev1.EnvVar { + return corev1.EnvVar{ Name: varName, - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ Key: secretKey, - LocalObjectReference: v1.LocalObjectReference{ + LocalObjectReference: corev1.LocalObjectReference{ Name: secretName, }, }, @@ -134,8 +134,8 @@ func getEnvVarWithSecretRef(varName, secretName, secretKey string) v1.EnvVar { } } -func getEnvVar(varName, value string) v1.EnvVar { - return v1.EnvVar{ +func getEnvVar(varName, value string) corev1.EnvVar { + return corev1.EnvVar{ Name: varName, Value: value, } @@ -169,7 +169,7 @@ func GetMapForLocationValues( } if locType != "" { m[repositoryserver.TypeKey] = []byte(locType) - if locType == repositoryserver.LocType(v1alpha1.LocationTypeS3Compliant) { + if locType == repositoryserver.LocType(crv1alpha1.LocationTypeS3Compliant) { m[repositoryserver.TypeKey] = []byte(repositoryserver.LocTypeS3) } } diff --git a/pkg/kopia/command/storage/secret_utils_test.go b/pkg/kopia/command/storage/secret_utils_test.go index edeeaa4b7f..857be9f504 100644 --- a/pkg/kopia/command/storage/secret_utils_test.go +++ b/pkg/kopia/command/storage/secret_utils_test.go @@ -19,10 +19,10 @@ import ( "time" "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/secrets" "github.com/kanisterio/kanister/pkg/secrets/repositoryserver" @@ -88,27 +88,27 @@ func (s *StorageUtilsSuite) TestGenerateEnvSpecFromCredentialSecret(c *check.C) locSecretName := "test-secret" for _, tc := range []struct { - secret *v1.Secret - expectedEnvVars []v1.EnvVar + secret *corev1.Secret + expectedEnvVars []corev1.EnvVar check.Checker }{ { - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: locSecretName, }, - Type: v1.SecretType(secrets.AWSSecretType), + Type: corev1.SecretType(secrets.AWSSecretType), Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte(awsAccessKeyId), secrets.AWSSecretAccessKey: []byte(awsSecretAccessKey), }, }, - expectedEnvVars: []v1.EnvVar{ + expectedEnvVars: []corev1.EnvVar{ { Name: aws.AccessKeyID, - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ Name: locSecretName, }, Key: secrets.AWSAccessKeyID, @@ -117,9 +117,9 @@ func (s *StorageUtilsSuite) TestGenerateEnvSpecFromCredentialSecret(c *check.C) }, { Name: aws.SecretAccessKey, - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ Name: locSecretName, }, Key: secrets.AWSSecretAccessKey, @@ -130,23 +130,23 @@ func (s *StorageUtilsSuite) TestGenerateEnvSpecFromCredentialSecret(c *check.C) Checker: check.IsNil, }, { - secret: &v1.Secret{ + secret: &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: locSecretName, }, - Type: v1.SecretType(secrets.AzureSecretType), + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte(azureStorageAccountID), secrets.AzureStorageAccountKey: []byte(azureStorageAccountKey), secrets.AzureStorageEnvironment: []byte(azureStorageEnvironment), }, }, - expectedEnvVars: []v1.EnvVar{ + expectedEnvVars: []corev1.EnvVar{ { Name: azureStorageAccountEnv, - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ Name: locSecretName, }, Key: secrets.AzureStorageAccountID, @@ -155,9 +155,9 @@ func (s *StorageUtilsSuite) TestGenerateEnvSpecFromCredentialSecret(c *check.C) }, { Name: azureStorageKeyEnv, - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ Name: locSecretName, }, Key: secrets.AzureStorageAccountKey, @@ -176,7 +176,7 @@ func (s *StorageUtilsSuite) TestGenerateEnvSpecFromCredentialSecret(c *check.C) Checker: check.NotNil, }, { - secret: &v1.Secret{ + secret: &corev1.Secret{ Type: "Opaque", }, Checker: check.IsNil, @@ -271,7 +271,7 @@ func (s *StorageUtilsSuite) TestGetMapForLocationValues(c *check.C) { }, }, { - locType: repositoryserver.LocType(v1alpha1.LocationTypeS3Compliant), + locType: repositoryserver.LocType(crv1alpha1.LocationTypeS3Compliant), prefix: prefixValue, region: regionValue, bucket: bucketValue, diff --git a/pkg/kube/exec.go b/pkg/kube/exec.go index ca47673c76..fbb49e74f7 100644 --- a/pkg/kube/exec.go +++ b/pkg/kube/exec.go @@ -23,7 +23,7 @@ import ( "github.com/kanisterio/kanister/pkg/format" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" restclient "k8s.io/client-go/rest" @@ -118,7 +118,7 @@ func execStream(kubeCli kubernetes.Interface, config *restclient.Config, options req.Param("container", options.ContainerName) } - req.VersionedParams(&v1.PodExecOptions{ + req.VersionedParams(&corev1.PodExecOptions{ Container: options.ContainerName, Command: options.Command, Stdin: options.Stdin != nil, diff --git a/pkg/kube/exec_test.go b/pkg/kube/exec_test.go index daa6de3285..bf6bd69a9f 100644 --- a/pkg/kube/exec_test.go +++ b/pkg/kube/exec_test.go @@ -24,7 +24,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -32,7 +32,7 @@ import ( type ExecSuite struct { cli kubernetes.Interface namespace string - pod *v1.Pod + pod *corev1.Pod } var _ = Suite(&ExecSuite{}) @@ -42,7 +42,7 @@ func (s *ExecSuite) SetUpSuite(c *C) { var err error s.cli, err = NewClient() c.Assert(err, IsNil) - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "exectest-", }, @@ -50,10 +50,10 @@ func (s *ExecSuite) SetUpSuite(c *C) { ns, err = s.cli.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}) c.Assert(err, IsNil) s.namespace = ns.Name - pod := &v1.Pod{ + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "testpod"}, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "testcontainer", Image: "busybox", @@ -105,7 +105,7 @@ func (s *ExecSuite) TestStderr(c *C) { } func (s *ExecSuite) TestExecWithWriterOptions(c *C) { - c.Assert(s.pod.Status.Phase, Equals, v1.PodRunning) + c.Assert(s.pod.Status.Phase, Equals, corev1.PodRunning) c.Assert(len(s.pod.Status.ContainerStatuses) > 0, Equals, true) var testCases = []struct { @@ -147,7 +147,7 @@ func (s *ExecSuite) TestExecWithWriterOptions(c *C) { func (s *ExecSuite) TestExecEcho(c *C) { cmd := []string{"sh", "-c", "cat -"} - c.Assert(s.pod.Status.Phase, Equals, v1.PodRunning) + c.Assert(s.pod.Status.Phase, Equals, corev1.PodRunning) c.Assert(len(s.pod.Status.ContainerStatuses) > 0, Equals, true) for _, cs := range s.pod.Status.ContainerStatuses { stdout, stderr, err := Exec(s.cli, s.pod.Namespace, s.pod.Name, cs.Name, cmd, bytes.NewBufferString("badabing")) @@ -159,7 +159,7 @@ func (s *ExecSuite) TestExecEcho(c *C) { func (s *ExecSuite) TestExecEchoDefaultContainer(c *C) { cmd := []string{"sh", "-c", "cat -"} - c.Assert(s.pod.Status.Phase, Equals, v1.PodRunning) + c.Assert(s.pod.Status.Phase, Equals, corev1.PodRunning) c.Assert(len(s.pod.Status.ContainerStatuses) > 0, Equals, true) stdout, stderr, err := Exec(s.cli, s.pod.Namespace, s.pod.Name, "", cmd, bytes.NewBufferString("badabing")) c.Assert(err, IsNil) @@ -169,7 +169,7 @@ func (s *ExecSuite) TestExecEchoDefaultContainer(c *C) { func (s *ExecSuite) TestLSWithoutStdIn(c *C) { cmd := []string{"ls", "-l", "/home"} - c.Assert(s.pod.Status.Phase, Equals, v1.PodRunning) + c.Assert(s.pod.Status.Phase, Equals, corev1.PodRunning) c.Assert(len(s.pod.Status.ContainerStatuses) > 0, Equals, true) stdout, stderr, err := Exec(s.cli, s.pod.Namespace, s.pod.Name, "", cmd, nil) c.Assert(err, IsNil) @@ -179,13 +179,13 @@ func (s *ExecSuite) TestLSWithoutStdIn(c *C) { func (s *ExecSuite) TestKopiaCommand(c *C) { ctx := context.Background() - pod := &v1.Pod{ + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "kopia-pod", Namespace: s.namespace, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "kanister-sidecar", Image: "ghcr.io/kanisterio/kanister-tools:0.37.0", diff --git a/pkg/kube/fips_test.go b/pkg/kube/fips_test.go index 488b0ef27f..1ea48bc33e 100644 --- a/pkg/kube/fips_test.go +++ b/pkg/kube/fips_test.go @@ -24,7 +24,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -32,7 +32,7 @@ import ( type FIPSSuite struct { cli kubernetes.Interface namespace string - pod *v1.Pod + pod *corev1.Pod } var _ = Suite(&FIPSSuite{}) @@ -42,7 +42,7 @@ func (s *FIPSSuite) SetUpSuite(c *C) { var err error s.cli, err = NewClient() c.Assert(err, IsNil) - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "fipstest-", }, @@ -50,10 +50,10 @@ func (s *FIPSSuite) SetUpSuite(c *C) { ns, err = s.cli.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}) c.Assert(err, IsNil) s.namespace = ns.Name - pod := &v1.Pod{ + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "testpod"}, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "testcontainer", Image: "ghcr.io/kanisterio/kanister-tools:v9.99.9-dev", diff --git a/pkg/kube/job.go b/pkg/kube/job.go index bd46702190..e8ffff867e 100644 --- a/pkg/kube/job.go +++ b/pkg/kube/job.go @@ -21,7 +21,7 @@ import ( "github.com/gofrs/uuid" "github.com/pkg/errors" batch "k8s.io/api/batch/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -86,26 +86,26 @@ func (job *Job) Create() error { APIVersion: "v1", }, Spec: batch.JobSpec{ - Template: v1.PodTemplateSpec{ + Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Name: defautlJobPodName, Labels: make(map[string]string), }, - Spec: v1.PodSpec{ + Spec: corev1.PodSpec{ ServiceAccountName: job.sa, - Containers: []v1.Container{ + Containers: []corev1.Container{ { Name: defaultJobPodContainer, Image: job.image, Command: job.command, - SecurityContext: &v1.SecurityContext{ + SecurityContext: &corev1.SecurityContext{ Privileged: &falseVal, }, - ImagePullPolicy: v1.PullPolicy(v1.PullIfNotPresent), + ImagePullPolicy: corev1.PullPolicy(corev1.PullIfNotPresent), VolumeMounts: volumeMounts, }, }, - RestartPolicy: v1.RestartPolicyOnFailure, + RestartPolicy: corev1.RestartPolicyOnFailure, Volumes: podVolumes, }, }, @@ -125,7 +125,7 @@ func (job *Job) Create() error { return nil } -func createFilesystemModeVolumeSpecs(vols map[string]string) (volumeMounts []v1.VolumeMount, podVolumes []v1.Volume, error error) { +func createFilesystemModeVolumeSpecs(vols map[string]string) (volumeMounts []corev1.VolumeMount, podVolumes []corev1.Volume, error error) { // Build filesystem mode volume specs for pvc, mountPath := range vols { id, err := uuid.NewV1() @@ -133,12 +133,12 @@ func createFilesystemModeVolumeSpecs(vols map[string]string) (volumeMounts []v1. return nil, nil, err } podVolName := fmt.Sprintf("vol-%s", id.String()) - volumeMounts = append(volumeMounts, v1.VolumeMount{Name: podVolName, MountPath: mountPath}) + volumeMounts = append(volumeMounts, corev1.VolumeMount{Name: podVolName, MountPath: mountPath}) podVolumes = append(podVolumes, - v1.Volume{ + corev1.Volume{ Name: podVolName, - VolumeSource: v1.VolumeSource{ - PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ + VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: pvc, }, }, @@ -148,7 +148,7 @@ func createFilesystemModeVolumeSpecs(vols map[string]string) (volumeMounts []v1. return volumeMounts, podVolumes, nil } -func createBlockModeVolumeSpecs(blockVols map[string]string) (volumeDevices []v1.VolumeDevice, podVolumes []v1.Volume, error error) { +func createBlockModeVolumeSpecs(blockVols map[string]string) (volumeDevices []corev1.VolumeDevice, podVolumes []corev1.Volume, error error) { // Build block mode volume specs for pvc, devicePath := range blockVols { id, err := uuid.NewV1() @@ -156,12 +156,12 @@ func createBlockModeVolumeSpecs(blockVols map[string]string) (volumeDevices []v1 return nil, nil, err } podBlockVolName := fmt.Sprintf("block-%s", id.String()) - volumeDevices = append(volumeDevices, v1.VolumeDevice{Name: podBlockVolName, DevicePath: devicePath}) + volumeDevices = append(volumeDevices, corev1.VolumeDevice{Name: podBlockVolName, DevicePath: devicePath}) podVolumes = append(podVolumes, - v1.Volume{ + corev1.Volume{ Name: podBlockVolName, - VolumeSource: v1.VolumeSource{ - PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ + VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: pvc, }, }, diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index b9b83ef7b9..196964acca 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -26,7 +26,7 @@ import ( json "github.com/json-iterator/go" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" sp "k8s.io/apimachinery/pkg/util/strategicpatch" @@ -66,17 +66,17 @@ type PodOptions struct { // You can still use podOverride to set the pod security context, but these fields will take precedence. // We chose these fields to specify security context instead of just using podOverride because // the merge behaviour of the pods spec is confusing in case of podOverride, and this is more readable. - PodSecurityContext *v1.PodSecurityContext - ContainerSecurityContext *v1.SecurityContext + PodSecurityContext *corev1.PodSecurityContext + ContainerSecurityContext *corev1.SecurityContext PodOverride crv1alpha1.JSONMap - Resources v1.ResourceRequirements - RestartPolicy v1.RestartPolicy + Resources corev1.ResourceRequirements + RestartPolicy corev1.RestartPolicy OwnerReferences []metav1.OwnerReference - EnvironmentVariables []v1.EnvVar - Lifecycle *v1.Lifecycle + EnvironmentVariables []corev1.EnvVar + Lifecycle *corev1.Lifecycle } -func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1.Pod, error) { +func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*corev1.Pod, error) { // If Namespace is not specified, use the controller Namespace. cns, err := GetControllerNamespace() if err != nil { @@ -98,7 +98,7 @@ func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1 } if opts.RestartPolicy == "" { - opts.RestartPolicy = v1.RestartPolicyNever + opts.RestartPolicy = corev1.RestartPolicyNever } volumeMounts, podVolumes, err := createFilesystemModeVolumeSpecs(opts.Volumes) @@ -110,13 +110,13 @@ func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1 return nil, errors.Wrapf(err, "Failed to create raw block volume spec") } podVolumes = append(podVolumes, blockVolumes...) - defaultSpecs := v1.PodSpec{ - Containers: []v1.Container{ + defaultSpecs := corev1.PodSpec{ + Containers: []corev1.Container{ { Name: defaultContainerName, Image: opts.Image, Command: opts.Command, - ImagePullPolicy: v1.PullPolicy(v1.PullIfNotPresent), + ImagePullPolicy: corev1.PullPolicy(corev1.PullIfNotPresent), VolumeMounts: volumeMounts, VolumeDevices: volumeDevices, Resources: opts.Resources, @@ -149,8 +149,8 @@ func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1 return createPodSpec(opts, patchedSpecs, ns), nil } -func createPodSpec(opts *PodOptions, patchedSpecs v1.PodSpec, ns string) *v1.Pod { - pod := &v1.Pod{ +func createPodSpec(opts *PodOptions, patchedSpecs corev1.PodSpec, ns string) *corev1.Pod { + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: opts.GenerateName, Labels: map[string]string{ @@ -203,7 +203,7 @@ func createPodSpec(opts *PodOptions, patchedSpecs v1.PodSpec, ns string) *v1.Pod } // CreatePod creates a pod with a single container based on the specified image -func CreatePod(ctx context.Context, cli kubernetes.Interface, opts *PodOptions) (*v1.Pod, error) { +func CreatePod(ctx context.Context, cli kubernetes.Interface, opts *PodOptions) (*corev1.Pod, error) { pod, err := GetPodObjectFromPodOptions(cli, opts) if err != nil { return nil, errors.Wrapf(err, "Failed to get pod from podOptions. Namespace: %s, NameFmt: %s", opts.Namespace, opts.GenerateName) @@ -217,7 +217,7 @@ func CreatePod(ctx context.Context, cli kubernetes.Interface, opts *PodOptions) } // DeletePod deletes the specified pod -func DeletePod(ctx context.Context, cli kubernetes.Interface, pod *v1.Pod) error { +func DeletePod(ctx context.Context, cli kubernetes.Interface, pod *corev1.Pod) error { if err := cli.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{}); err != nil { log.WithError(err).Print("DeletePod failed") } @@ -225,7 +225,7 @@ func DeletePod(ctx context.Context, cli kubernetes.Interface, pod *v1.Pod) error } func StreamPodLogs(ctx context.Context, cli kubernetes.Interface, namespace, podName, containerName string) (io.ReadCloser, error) { - plo := &v1.PodLogOptions{ + plo := &corev1.PodLogOptions{ Follow: true, Container: containerName, } @@ -234,7 +234,7 @@ func StreamPodLogs(ctx context.Context, cli kubernetes.Interface, namespace, pod // GetPodLogs fetches the logs from the given pod func GetPodLogs(ctx context.Context, cli kubernetes.Interface, namespace, podName, containerName string) (string, error) { - reader, err := cli.CoreV1().Pods(namespace).GetLogs(podName, &v1.PodLogOptions{Container: containerName}).Stream(ctx) + reader, err := cli.CoreV1().Pods(namespace).GetLogs(podName, &corev1.PodLogOptions{Container: containerName}).Stream(ctx) if err != nil { return "", err } @@ -284,7 +284,7 @@ func WaitForPodReady(ctx context.Context, cli kubernetes.Interface, namespace, n } // check for memory or resource issues - if p.Status.Phase == v1.PodPending { + if p.Status.Phase == corev1.PodPending { if p.Status.Reason == "OutOfmemory" || p.Status.Reason == "OutOfcpu" { attachLog = false return false, errors.Errorf("Pod stuck in pending state, reason: %s", p.Status.Reason) @@ -297,7 +297,7 @@ func WaitForPodReady(ctx context.Context, cli kubernetes.Interface, namespace, n return false, err } - return p.Status.Phase != v1.PodPending && p.Status.Phase != "", nil + return p.Status.Phase != corev1.PodPending && p.Status.Phase != "", nil }) if err == nil { @@ -312,7 +312,7 @@ func WaitForPodReady(ctx context.Context, cli kubernetes.Interface, namespace, n return errors.Wrap(err, errorMessage) } -func checkNodesStatus(p *v1.Pod, cli kubernetes.Interface) error { +func checkNodesStatus(p *corev1.Pod, cli kubernetes.Interface) error { n := strings.Split(p.Spec.NodeName, "/") if n[0] != "" { node, err := cli.CoreV1().Nodes().Get(context.TODO(), n[0], metav1.GetOptions{}) @@ -330,7 +330,7 @@ func checkNodesStatus(p *v1.Pod, cli kubernetes.Interface) error { // - if PVC is present then check the status of PVC // - if PVC is pending then check if the PV status is VolumeFailed return error if so. if not then wait for timeout. // - if PVC not present then wait for timeout -func getVolStatus(ctx context.Context, p *v1.Pod, cli kubernetes.Interface, namespace string) error { +func getVolStatus(ctx context.Context, p *corev1.Pod, cli kubernetes.Interface, namespace string) error { for _, vol := range p.Spec.Volumes { if err := checkPVCAndPVStatus(ctx, vol, p, cli, namespace); err != nil { return err @@ -343,7 +343,7 @@ func getVolStatus(ctx context.Context, p *v1.Pod, cli kubernetes.Interface, name // - if PVC is present then check the status of PVC // - if PVC is pending then check if the PV status is VolumeFailed return error if so. if not then wait for timeout. // - if PVC not present then wait for timeout -func checkPVCAndPVStatus(ctx context.Context, vol v1.Volume, p *v1.Pod, cli kubernetes.Interface, namespace string) error { +func checkPVCAndPVStatus(ctx context.Context, vol corev1.Volume, p *corev1.Pod, cli kubernetes.Interface, namespace string) error { if vol.VolumeSource.PersistentVolumeClaim == nil { // wait for timeout return nil @@ -360,9 +360,9 @@ func checkPVCAndPVStatus(ctx context.Context, vol v1.Volume, p *v1.Pod, cli kube } switch pvc.Status.Phase { - case v1.ClaimLost: - return errors.Errorf("PVC %s assoicated with pod %s has status: %s", pvcName, p.Name, v1.ClaimLost) - case v1.ClaimPending: + case corev1.ClaimLost: + return errors.Errorf("PVC %s assoicated with pod %s has status: %s", pvcName, p.Name, corev1.ClaimLost) + case corev1.ClaimPending: pvName := pvc.Spec.VolumeName if pvName == "" { // wait for timeout @@ -377,8 +377,8 @@ func checkPVCAndPVStatus(ctx context.Context, vol v1.Volume, p *v1.Pod, cli kube return errors.Wrapf(err, "Failed to get PV %s", pvName) } } - if pv.Status.Phase == v1.VolumeFailed { - return errors.Errorf("PV %s associated with PVC %s has status: %s message: %s reason: %s namespace: %s", pvName, pvcName, v1.VolumeFailed, pv.Status.Message, pv.Status.Reason, namespace) + if pv.Status.Phase == corev1.VolumeFailed { + return errors.Errorf("PV %s associated with PVC %s has status: %s message: %s reason: %s namespace: %s", pvName, pvcName, corev1.VolumeFailed, pv.Status.Message, pv.Status.Reason, namespace) } } @@ -396,10 +396,10 @@ func WaitForPodCompletion(ctx context.Context, cli kubernetes.Interface, namespa return true, err } containerForLogs = p.Spec.Containers[0].Name - if p.Status.Phase == v1.PodFailed { + if p.Status.Phase == corev1.PodFailed { return false, errors.Errorf("Pod %s failed. Pod status: %s", name, p.Status.String()) } - return p.Status.Phase == v1.PodSucceeded, nil + return p.Status.Phase == corev1.PodSucceeded, nil }) errorMessage := "Pod failed or did not transition into complete state" @@ -410,15 +410,15 @@ func WaitForPodCompletion(ctx context.Context, cli kubernetes.Interface, namespa } // use Strategic Merge to patch default pod specs with the passed specs -func patchDefaultPodSpecs(defaultPodSpecs v1.PodSpec, override crv1alpha1.JSONMap) (v1.PodSpec, error) { +func patchDefaultPodSpecs(defaultPodSpecs corev1.PodSpec, override crv1alpha1.JSONMap) (corev1.PodSpec, error) { // Merge default specs and override specs with StrategicMergePatch mergedPatch, err := strategicMergeJsonPatch(defaultPodSpecs, override) if err != nil { - return v1.PodSpec{}, err + return corev1.PodSpec{}, err } - // Convert merged json to v1.PodSPec object - podSpec := v1.PodSpec{} + // Convert merged json to corev1.PodSPec object + podSpec := corev1.PodSpec{} err = json.Unmarshal(mergedPatch, &podSpec) if err != nil { return podSpec, err @@ -457,7 +457,7 @@ func strategicMergeJsonPatch(original, override interface{}) ([]byte, error) { } // Merge json specs with StrategicMerge - mergedPatch, err := sp.StrategicMergePatch(originalJson, overrideJson, v1.PodSpec{}) + mergedPatch, err := sp.StrategicMergePatch(originalJson, overrideJson, corev1.PodSpec{}) if err != nil { return nil, err } diff --git a/pkg/kube/pod_runner.go b/pkg/kube/pod_runner.go index 72d826c534..8b02ae8839 100644 --- a/pkg/kube/pod_runner.go +++ b/pkg/kube/pod_runner.go @@ -18,7 +18,7 @@ import ( "context" "github.com/pkg/errors" - "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "github.com/kanisterio/kanister/pkg/consts" @@ -28,7 +28,7 @@ import ( // PodRunner allows us to start / stop pod, write file to pod and execute command within it type PodRunner interface { - Run(ctx context.Context, fn func(context.Context, *v1.Pod) (map[string]interface{}, error)) (map[string]interface{}, error) + Run(ctx context.Context, fn func(context.Context, *corev1.Pod) (map[string]interface{}, error)) (map[string]interface{}, error) // RunEx utilizes the PodController interface and forwards it to the functor, simplifying the manipulation with // particular pod from the functor. // TODO: Since significant number of functions are currently using PodRunner, we'll keep Run for now. @@ -50,7 +50,7 @@ func NewPodRunner(cli kubernetes.Interface, options *PodOptions) PodRunner { } // Run will create a new Pod based on PodRunner contents and execute the given function -func (p *podRunner) Run(ctx context.Context, fn func(context.Context, *v1.Pod) (map[string]interface{}, error)) (map[string]interface{}, error) { +func (p *podRunner) Run(ctx context.Context, fn func(context.Context, *corev1.Pod) (map[string]interface{}, error)) (map[string]interface{}, error) { return p.RunEx(ctx, func(innerCtx context.Context, pc PodController) (map[string]interface{}, error) { return fn(innerCtx, pc.Pod()) }) diff --git a/pkg/kube/pod_runner_test.go b/pkg/kube/pod_runner_test.go index 858605491b..7023002a2f 100644 --- a/pkg/kube/pod_runner_test.go +++ b/pkg/kube/pod_runner_test.go @@ -19,7 +19,7 @@ import ( "os" . "gopkg.in/check.v1" - "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/testing" @@ -45,9 +45,9 @@ func (s *PodRunnerTestSuite) TestPodRunnerContextCanceled(c *C) { return false, nil, nil }) cli.PrependReactor("get", "pods", func(action testing.Action) (handled bool, ret runtime.Object, err error) { - p := &v1.Pod{ - Status: v1.PodStatus{ - Phase: v1.PodRunning, + p := &corev1.Pod{ + Status: corev1.PodStatus{ + Phase: corev1.PodRunning, }, } return true, p, nil @@ -80,9 +80,9 @@ func (s *PodRunnerTestSuite) TestPodRunnerForSuccessCase(c *C) { return false, nil, nil }) cli.PrependReactor("get", "pods", func(action testing.Action) (handled bool, ret runtime.Object, err error) { - p := &v1.Pod{ - Status: v1.PodStatus{ - Phase: v1.PodRunning, + p := &corev1.Pod{ + Status: corev1.PodStatus{ + Phase: corev1.PodRunning, }, } return true, p, nil @@ -109,8 +109,8 @@ func (s *PodRunnerTestSuite) TestPodRunnerForSuccessCase(c *C) { cancel() } -func makePodRunnerTestFunc(ch chan struct{}) func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { - return func(ctx context.Context, pod *v1.Pod) (map[string]interface{}, error) { +func makePodRunnerTestFunc(ch chan struct{}) func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { + return func(ctx context.Context, pod *corev1.Pod) (map[string]interface{}, error) { <-ch return nil, nil } diff --git a/pkg/kube/pod_writer_test.go b/pkg/kube/pod_writer_test.go index b6593d8610..082ee917c2 100644 --- a/pkg/kube/pod_writer_test.go +++ b/pkg/kube/pod_writer_test.go @@ -24,7 +24,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -32,7 +32,7 @@ import ( type PodWriteSuite struct { cli kubernetes.Interface namespace string - pod *v1.Pod + pod *corev1.Pod } var _ = Suite(&PodWriteSuite{}) @@ -42,7 +42,7 @@ func (p *PodWriteSuite) SetUpSuite(c *C) { ctx := context.Background() p.cli, err = NewClient() c.Assert(err, IsNil) - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "podwritertest-", }, @@ -50,10 +50,10 @@ func (p *PodWriteSuite) SetUpSuite(c *C) { ns, err = p.cli.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}) c.Assert(err, IsNil) p.namespace = ns.Name - pod := &v1.Pod{ + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "testpod"}, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "testcontainer", Image: "busybox", @@ -80,7 +80,7 @@ func (p *PodWriteSuite) TearDownSuite(c *C) { } func (p *PodWriteSuite) TestPodWriter(c *C) { path := "/tmp/test.txt" - c.Assert(p.pod.Status.Phase, Equals, v1.PodRunning) + c.Assert(p.pod.Status.Phase, Equals, corev1.PodRunning) c.Assert(len(p.pod.Status.ContainerStatuses) > 0, Equals, true) for _, cs := range p.pod.Status.ContainerStatuses { pw := NewPodWriter(p.cli, path, bytes.NewBufferString("badabing")) diff --git a/pkg/kube/snapshot/apis/v1alpha1/types.go b/pkg/kube/snapshot/apis/v1alpha1/types.go index 632ba1d7fc..6cb15190f3 100644 --- a/pkg/kube/snapshot/apis/v1alpha1/types.go +++ b/pkg/kube/snapshot/apis/v1alpha1/types.go @@ -19,7 +19,7 @@ limitations under the License. package v1alpha1 import ( - core_v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" storage "k8s.io/api/storage/v1beta1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -77,7 +77,7 @@ type VolumeSnapshotSpec struct { // Source has the information about where the snapshot is created from. // In Alpha version, only PersistentVolumeClaim is supported as the source. // If not specified, user can create VolumeSnapshotContent and bind it with VolumeSnapshot manually. - Source *core_v1.TypedLocalObjectReference `json:"source" protobuf:"bytes,1,opt,name=source"` + Source *corev1.TypedLocalObjectReference `json:"source" protobuf:"bytes,1,opt,name=source"` // SnapshotContentName binds the VolumeSnapshot object with the VolumeSnapshotContent SnapshotContentName string `json:"snapshotContentName" protobuf:"bytes,2,opt,name=snapshotContentName"` @@ -170,11 +170,11 @@ type VolumeSnapshotContentSpec struct { // VolumeSnapshotRef is part of bi-directional binding between VolumeSnapshot // and VolumeSnapshotContent. It becomes non-nil when bound. - VolumeSnapshotRef *core_v1.ObjectReference `json:"volumeSnapshotRef" protobuf:"bytes,2,opt,name=volumeSnapshotRef"` + VolumeSnapshotRef *corev1.ObjectReference `json:"volumeSnapshotRef" protobuf:"bytes,2,opt,name=volumeSnapshotRef"` // PersistentVolumeRef represents the PersistentVolume that the snapshot has been // taken from. It becomes non-nil when VolumeSnapshot and VolumeSnapshotContent are bound. - PersistentVolumeRef *core_v1.ObjectReference `json:"persistentVolumeRef" protobuf:"bytes,3,opt,name=persistentVolumeRef"` + PersistentVolumeRef *corev1.ObjectReference `json:"persistentVolumeRef" protobuf:"bytes,3,opt,name=persistentVolumeRef"` // Name of the VolumeSnapshotClass used by the VolumeSnapshot. If not specified, a default snapshot class will // be used if it is available. diff --git a/pkg/kube/snapshot/apis/v1beta1/types.go b/pkg/kube/snapshot/apis/v1beta1/types.go index a23c238181..e2094f6431 100644 --- a/pkg/kube/snapshot/apis/v1beta1/types.go +++ b/pkg/kube/snapshot/apis/v1beta1/types.go @@ -19,7 +19,7 @@ limitations under the License. package v1beta1 import ( - core_v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -231,7 +231,7 @@ type VolumeSnapshotContentSpec struct { // VolumeSnapshot object MUST be provided for binding to happen. // This field is immutable after creation. // Required. - VolumeSnapshotRef core_v1.ObjectReference `json:"volumeSnapshotRef" protobuf:"bytes,1,opt,name=volumeSnapshotRef"` + VolumeSnapshotRef corev1.ObjectReference `json:"volumeSnapshotRef" protobuf:"bytes,1,opt,name=volumeSnapshotRef"` // deletionPolicy determines whether this VolumeSnapshotContent and its physical snapshot on // the underlying storage system should be deleted when its bound VolumeSnapshot is deleted. diff --git a/pkg/kube/snapshot/snapshot_alpha.go b/pkg/kube/snapshot/snapshot_alpha.go index 949d8abe6a..f62669c4d4 100644 --- a/pkg/kube/snapshot/snapshot_alpha.go +++ b/pkg/kube/snapshot/snapshot_alpha.go @@ -22,7 +22,6 @@ import ( v1 "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1" "github.com/pkg/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" - k8errors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" pkglabels "k8s.io/apimachinery/pkg/labels" @@ -92,7 +91,7 @@ func (sna *SnapshotAlpha) GetVolumeSnapshotClass(ctx context.Context, annotation // Create creates a VolumeSnapshot and returns it or any error that happened meanwhile. func (sna *SnapshotAlpha) Create(ctx context.Context, name, namespace, pvcName string, snapshotClass *string, waitForReady bool, labels map[string]string) error { if _, err := sna.kubeCli.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, pvcName, metav1.GetOptions{}); err != nil { - if k8errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return errors.Errorf("Failed to find PVC %s, Namespace %s", pvcName, namespace) } return errors.Errorf("Failed to query PVC %s, Namespace %s: %v", pvcName, namespace, err) @@ -224,7 +223,7 @@ func (sna *SnapshotAlpha) Clone(ctx context.Context, name, namespace, cloneName, if err == nil { return errors.Errorf("Target snapshot already exists in target namespace, Volumesnapshot: %s, Namespace: %s", cloneName, cloneNamespace) } - if !k8errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return errors.Errorf("Failed to query target Volumesnapshot: %s, Namespace: %s: %v", cloneName, cloneNamespace, err) } diff --git a/pkg/kube/snapshot/snapshot_beta.go b/pkg/kube/snapshot/snapshot_beta.go index 3f6369d3a7..cc05597aed 100644 --- a/pkg/kube/snapshot/snapshot_beta.go +++ b/pkg/kube/snapshot/snapshot_beta.go @@ -21,7 +21,6 @@ import ( v1 "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1" "github.com/pkg/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" - k8errors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" pkglabels "k8s.io/apimachinery/pkg/labels" @@ -96,7 +95,7 @@ func createSnapshot( labels map[string]string, ) error { if _, err := kubeCli.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, volumeName, metav1.GetOptions{}); err != nil { - if k8errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { return errors.Errorf("Failed to find PVC %s, Namespace %s", volumeName, namespace) } return errors.Wrapf(err, "Failed to query PVC %s, Namespace %s", volumeName, namespace) @@ -198,7 +197,7 @@ func (sna *SnapshotBeta) Clone(ctx context.Context, name, namespace, cloneName, if err == nil { return errors.Errorf("Target snapshot already exists in target namespace, Volumesnapshot: %s, Namespace: %s", cloneName, cloneNamespace) } - if !k8errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return errors.Errorf("Failed to query target Volumesnapshot: %s, Namespace: %s: %v", cloneName, cloneNamespace, err) } diff --git a/pkg/kube/snapshot/snapshot_stable.go b/pkg/kube/snapshot/snapshot_stable.go index 4d410b98d6..69b1dfd999 100644 --- a/pkg/kube/snapshot/snapshot_stable.go +++ b/pkg/kube/snapshot/snapshot_stable.go @@ -20,7 +20,6 @@ import ( v1 "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1" "github.com/pkg/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" - k8errors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/uuid" @@ -103,7 +102,7 @@ func (sna *SnapshotStable) Clone(ctx context.Context, name, namespace, cloneName if err == nil { return errors.Errorf("Target snapshot already exists in target namespace, Volumesnapshot: %s, Namespace: %s", cloneName, cloneNamespace) } - if !k8errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return errors.Errorf("Failed to query target Volumesnapshot: %s, Namespace: %s: %v", cloneName, cloneNamespace, err) } diff --git a/pkg/kube/snapshot/snapshot_test.go b/pkg/kube/snapshot/snapshot_test.go index ed1e6530ef..a66d214432 100644 --- a/pkg/kube/snapshot/snapshot_test.go +++ b/pkg/kube/snapshot/snapshot_test.go @@ -26,9 +26,8 @@ import ( snapv1 "github.com/kubernetes-csi/external-snapshotter/client/v4/apis/volumesnapshot/v1" . "gopkg.in/check.v1" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/core/v1" scv1 "k8s.io/api/storage/v1" - k8errors "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -871,7 +870,7 @@ func (tc snapshotClassTC) testGetSnapshotClass(c *C, dynCli dynamic.Interface, f func findSnapshotClassName(c *C, ctx context.Context, dynCli dynamic.Interface, gvr schema.GroupVersionResource, object interface{}) (string, string) { // Find alpha VolumeSnapshotClass name us, err := dynCli.Resource(gvr).List(ctx, metav1.ListOptions{}) - if err != nil && !k8errors.IsNotFound(err) { + if err != nil && !apierrors.IsNotFound(err) { c.Logf("Failed to query VolumeSnapshotClass, skipping test. Error: %v", err) c.Fail() } @@ -1198,8 +1197,8 @@ func (s *SnapshotLocalTestSuite) TestLabels(c *C) { } } -func fakePVC(name, namespace string) *v1.PersistentVolumeClaim { - return &v1.PersistentVolumeClaim{ +func fakePVC(name, namespace string) *corev1.PersistentVolumeClaim { + return &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, diff --git a/pkg/kube/statefulset_test.go b/pkg/kube/statefulset_test.go index 9f3d24ee4b..56c89ccd20 100644 --- a/pkg/kube/statefulset_test.go +++ b/pkg/kube/statefulset_test.go @@ -23,7 +23,7 @@ import ( "strings" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -40,7 +40,7 @@ func (s *StatefulSetSuite) SetUpSuite(c *C) { cli, err := NewClient() c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "statefulsettest-", }, diff --git a/pkg/kube/utils.go b/pkg/kube/utils.go index 5eee2ababe..282338b0d8 100644 --- a/pkg/kube/utils.go +++ b/pkg/kube/utils.go @@ -19,7 +19,7 @@ import ( "fmt" osversioned "github.com/openshift/client-go/apps/clientset/versioned" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" ) @@ -107,11 +107,11 @@ func GetPodContainerFromStatefulSet(ctx context.Context, cli kubernetes.Interfac // As of kubernetes 1.17 the "failure.domain" annotation // has been deprecated in favor of the "topology" annotation -func GetZoneFromNode(node v1.Node) string { +func GetZoneFromNode(node corev1.Node) string { return GetZoneFromLabels(node.Labels) } -func GetZoneFromPV(pv v1.PersistentVolume) string { +func GetZoneFromPV(pv corev1.PersistentVolume) string { return GetZoneFromLabels(pv.Labels) } @@ -124,11 +124,11 @@ func GetZoneFromLabels(labels map[string]string) string { return "" } -func GetRegionFromNode(node v1.Node) string { +func GetRegionFromNode(node corev1.Node) string { return GetRegionFromLabels(node.Labels) } -func GetRegionFromPV(pv v1.PersistentVolume) string { +func GetRegionFromPV(pv corev1.PersistentVolume) string { return GetRegionFromLabels(pv.Labels) } @@ -143,7 +143,7 @@ func GetRegionFromLabels(labels map[string]string) string { // IsNodeSchedulable returns true if it doesn't have "unschedulable" field set // Derived from "k8s.io/kubernetes/test/e2e/framework/node" -func IsNodeSchedulable(node *v1.Node) bool { +func IsNodeSchedulable(node *corev1.Node) bool { if node == nil { return false } @@ -152,9 +152,9 @@ func IsNodeSchedulable(node *v1.Node) bool { // IsNodeReady returns true if it's Ready condition is set to true // Derived from "k8s.io/kubernetes/test/e2e/framework/node" -func IsNodeReady(node *v1.Node) bool { +func IsNodeReady(node *corev1.Node) bool { for _, cond := range node.Status.Conditions { - if cond.Type == v1.NodeReady && cond.Status == v1.ConditionTrue { + if cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue { return true } } diff --git a/pkg/kube/volume/volume.go b/pkg/kube/volume/volume.go index b3092297b3..b9a5268d85 100644 --- a/pkg/kube/volume/volume.go +++ b/pkg/kube/volume/volume.go @@ -23,7 +23,7 @@ import ( "time" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -56,8 +56,8 @@ func CreatePVC( sizeInBytes int64, targetVolID string, annotations map[string]string, - accessmodes []v1.PersistentVolumeAccessMode, - volumemode *v1.PersistentVolumeMode, + accessmodes []corev1.PersistentVolumeAccessMode, + volumemode *corev1.PersistentVolumeMode, ) (string, error) { sizeFmt := fmt.Sprintf("%d", sizeInBytes) size, err := resource.ParseQuantity(sizeFmt) @@ -66,18 +66,18 @@ func CreatePVC( return "", errors.Wrapf(err, "Unable to parse sizeFmt %s", sizeFmt) } if len(accessmodes) == 0 { - accessmodes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} + accessmodes = []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce} } - pvc := v1.PersistentVolumeClaim{ + pvc := corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Annotations: annotations, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: accessmodes, VolumeMode: volumemode, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): size, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): size, }, }, }, @@ -124,8 +124,8 @@ type CreatePVCFromSnapshotArgs struct { RestoreSize string Labels map[string]string Annotations map[string]string - VolumeMode *v1.PersistentVolumeMode - AccessModes []v1.PersistentVolumeAccessMode + VolumeMode *corev1.PersistentVolumeMode + AccessModes []corev1.PersistentVolumeAccessMode } // CreatePVCFromSnapshot will restore a volume and returns the resulting @@ -137,26 +137,26 @@ func CreatePVCFromSnapshot(ctx context.Context, args *CreatePVCFromSnapshotArgs) } if len(args.AccessModes) == 0 { - args.AccessModes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} + args.AccessModes = []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce} } snapshotKind := "VolumeSnapshot" snapshotAPIGroup := "snapshot.storage.k8s.io" - pvc := &v1.PersistentVolumeClaim{ + pvc := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Labels: args.Labels, Annotations: args.Annotations, }, - Spec: v1.PersistentVolumeClaimSpec{ + Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: args.AccessModes, VolumeMode: args.VolumeMode, - DataSource: &v1.TypedLocalObjectReference{ + DataSource: &corev1.TypedLocalObjectReference{ APIGroup: &snapshotAPIGroup, Kind: snapshotKind, Name: args.SnapshotName, }, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceStorage: *storageSize, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: *storageSize, }, }, }, @@ -224,8 +224,8 @@ func CreatePV( vol *blockstorage.Volume, volType blockstorage.Type, annotations map[string]string, - accessmodes []v1.PersistentVolumeAccessMode, - volumemode *v1.PersistentVolumeMode, + accessmodes []corev1.PersistentVolumeAccessMode, + volumemode *corev1.PersistentVolumeMode, ) (string, error) { sizeFmt := fmt.Sprintf("%d", vol.SizeInBytes) size, err := resource.ParseQuantity(sizeFmt) @@ -243,33 +243,33 @@ func CreatePV( } if len(accessmodes) == 0 { - accessmodes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce} + accessmodes = []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce} } - pv := v1.PersistentVolume{ + pv := corev1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanister-pv-", Labels: matchLabels, Annotations: annotations, }, - Spec: v1.PersistentVolumeSpec{ - Capacity: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): size, + Spec: corev1.PersistentVolumeSpec{ + Capacity: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): size, }, AccessModes: accessmodes, VolumeMode: volumemode, - PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, + PersistentVolumeReclaimPolicy: corev1.PersistentVolumeReclaimDelete, }, } switch volType { case blockstorage.TypeEBS: - pv.Spec.PersistentVolumeSource.AWSElasticBlockStore = &v1.AWSElasticBlockStoreVolumeSource{ + pv.Spec.PersistentVolumeSource.AWSElasticBlockStore = &corev1.AWSElasticBlockStoreVolumeSource{ VolumeID: vol.ID, } pv.ObjectMeta.Labels[kube.FDZoneLabelName] = vol.Az pv.ObjectMeta.Labels[kube.FDRegionLabelName] = zoneToRegion(vol.Az) case blockstorage.TypeGPD: - pv.Spec.PersistentVolumeSource.GCEPersistentDisk = &v1.GCEPersistentDiskVolumeSource{ + pv.Spec.PersistentVolumeSource.GCEPersistentDisk = &corev1.GCEPersistentDiskVolumeSource{ PDName: vol.ID, } pv.ObjectMeta.Labels[kube.FDZoneLabelName] = vol.Az diff --git a/pkg/kube/volume/volume_test.go b/pkg/kube/volume/volume_test.go index f3564bec47..cfadac7485 100644 --- a/pkg/kube/volume/volume_test.go +++ b/pkg/kube/volume/volume_test.go @@ -22,7 +22,7 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -46,15 +46,15 @@ func (s *TestVolSuite) TestCreatePVC(c *C) { targetVolID := "testVolID" annotations := map[string]string{"a1": "foo"} cli := fake.NewSimpleClientset() - pvcName, err := CreatePVC(ctx, cli, ns, NoPVCNameSpecified, pvcSize, targetVolID, annotations, []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, nil) + pvcName, err := CreatePVC(ctx, cli, ns, NoPVCNameSpecified, pvcSize, targetVolID, annotations, []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, nil) c.Assert(err, IsNil) pvc, err := cli.CoreV1().PersistentVolumeClaims(ns).Get(ctx, pvcName, metav1.GetOptions{}) c.Assert(err, IsNil) c.Assert(len(pvc.Spec.AccessModes) >= 1, Equals, true) accessMode := pvc.Spec.AccessModes[0] - c.Assert(accessMode, Equals, v1.ReadWriteOnce) - capacity, ok := pvc.Spec.Resources.Requests[v1.ResourceStorage] + c.Assert(accessMode, Equals, corev1.ReadWriteOnce) + capacity, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage] c.Assert(ok, Equals, true) c.Assert(capacity.Value() >= int64(pvcSize), Equals, true) eq := reflect.DeepEqual(annotations, pvc.ObjectMeta.Annotations) @@ -63,13 +63,13 @@ func (s *TestVolSuite) TestCreatePVC(c *C) { label := pvc.Spec.Selector.MatchLabels[pvMatchLabelName] c.Assert(label, Equals, filepath.Base(targetVolID)) - volumeMode := v1.PersistentVolumeBlock + volumeMode := corev1.PersistentVolumeBlock _, err = CreatePVC(ctx, cli, ns, "pvc2", pvcSize, targetVolID, annotations, nil, &volumeMode) c.Assert(err, IsNil) pvc2, err := cli.CoreV1().PersistentVolumeClaims(ns).Get(ctx, "pvc2", metav1.GetOptions{}) c.Assert(err, IsNil) c.Assert(len(pvc2.Spec.AccessModes) >= 1, Equals, true) - c.Assert(*pvc2.Spec.VolumeMode, Equals, v1.PersistentVolumeBlock) + c.Assert(*pvc2.Spec.VolumeMode, Equals, corev1.PersistentVolumeBlock) c.Assert(pvc2.GetAnnotations(), NotNil) c.Assert(pvc2.GetAnnotations()["a1"], Equals, "foo") } diff --git a/pkg/kube/workload.go b/pkg/kube/workload.go index f4c7eba93d..bf08210cf4 100644 --- a/pkg/kube/workload.go +++ b/pkg/kube/workload.go @@ -22,7 +22,7 @@ import ( "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -44,8 +44,8 @@ const ( ) // CreateConfigMap creates a configmap set from a yaml spec. -func CreateConfigMap(ctx context.Context, cli kubernetes.Interface, namespace string, spec string) (*v1.ConfigMap, error) { - cm := &v1.ConfigMap{} +func CreateConfigMap(ctx context.Context, cli kubernetes.Interface, namespace string, spec string) (*corev1.ConfigMap, error) { + cm := &corev1.ConfigMap{} d := serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer() if _, _, err := d.Decode([]byte(spec), nil, cm); err != nil { return nil, err @@ -100,7 +100,7 @@ func StatefulSetReady(ctx context.Context, kubeCli kubernetes.Interface, namespa } // StatefulSetPods returns list of running and notrunning pods created by the deployment. -func StatefulSetPods(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]v1.Pod, []v1.Pod, error) { +func StatefulSetPods(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]corev1.Pod, []corev1.Pod, error) { ss, err := kubeCli.AppsV1().StatefulSets(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, nil, errors.Wrapf(err, "could not get StatefulSet{Namespace: %s, Name: %s}", namespace, name) @@ -160,7 +160,7 @@ func DeploymentConfigReady(ctx context.Context, osCli osversioned.Interface, cli // are not. To handle that we are not considering `Completed` pods to be NotRunning pods here failedPodsCount := 0 for _, v := range notRunningPods { - if v.Status.Phase == v1.PodSucceeded { + if v.Status.Phase == corev1.PodSucceeded { continue } failedPodsCount++ @@ -229,7 +229,7 @@ func DeploymentReady(ctx context.Context, kubeCli kubernetes.Interface, namespac } // DeploymentConfigPods return list of running and not running pod created by this/name deployment config -func DeploymentConfigPods(ctx context.Context, osCli osversioned.Interface, kubeCli kubernetes.Interface, namespace, name string) ([]v1.Pod, []v1.Pod, error) { +func DeploymentConfigPods(ctx context.Context, osCli osversioned.Interface, kubeCli kubernetes.Interface, namespace, name string) ([]corev1.Pod, []corev1.Pod, error) { depConf, err := osCli.AppsV1().DeploymentConfigs(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, nil, errors.Wrapf(err, "could not get DeploymentConfig{Namespace: %s, Name: %s}", namespace, name) @@ -243,7 +243,7 @@ func DeploymentConfigPods(ctx context.Context, osCli osversioned.Interface, kube } // DeploymentPods returns list of running and notrunning pods created by the deployment. -func DeploymentPods(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]v1.Pod, []v1.Pod, error) { +func DeploymentPods(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]corev1.Pod, []corev1.Pod, error) { d, err := kubeCli.AppsV1().Deployments(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, nil, errors.Wrapf(err, "could not get Deployment{Namespace: %s, Name: %s}", namespace, name) @@ -286,7 +286,7 @@ func WaitOnDeploymentConfigReady(ctx context.Context, osCli osversioned.Interfac } // FetchReplicationController fetches the replication controller that has owner with UID provided uid -func FetchReplicationController(cli kubernetes.Interface, namespace string, uid types.UID, revision string) (*v1.ReplicationController, error) { +func FetchReplicationController(cli kubernetes.Interface, namespace string, uid types.UID, revision string) (*corev1.ReplicationController, error) { repCtrls, err := cli.CoreV1().ReplicationControllers(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { return nil, errors.Wrapf(err, "Could not list ReplicationControllers") @@ -338,7 +338,7 @@ func FetchReplicaSet(cli kubernetes.Interface, namespace string, uid types.UID, // FetchPods fetches the pods matching the specified owner UID and splits them // into 2 groups (running/not-running) -func FetchPods(cli kubernetes.Interface, namespace string, uid types.UID) (runningPods []v1.Pod, notRunningPods []v1.Pod, err error) { +func FetchPods(cli kubernetes.Interface, namespace string, uid types.UID) (runningPods []corev1.Pod, notRunningPods []corev1.Pod, err error) { pods, err := cli.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{}) if err != nil { return nil, nil, errors.Wrap(err, "Could not list Pods") @@ -348,7 +348,7 @@ func FetchPods(cli kubernetes.Interface, namespace string, uid types.UID) (runni pod.OwnerReferences[0].UID != uid { continue } - if pod.Status.Phase != v1.PodRunning { + if pod.Status.Phase != corev1.PodRunning { notRunningPods = append(notRunningPods, pod) continue } @@ -419,7 +419,7 @@ func DeploymentVolumes(cli kubernetes.Interface, d *appsv1.Deployment) (volNameT } // PodContainers returns list of containers specified by the pod -func PodContainers(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]v1.Container, error) { +func PodContainers(ctx context.Context, kubeCli kubernetes.Interface, namespace string, name string) ([]corev1.Container, error) { p, err := kubeCli.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{}) if err != nil { return nil, errors.Wrapf(err, "could not get Pod{Namespace: %s, Name: %s}", namespace, name) @@ -449,7 +449,7 @@ func getOrdinal(pod string) int { } // StatefulSetVolumes returns the PVCs referenced by a pod in this statefulset as a [pod spec volume name]->[PVC name] map -func StatefulSetVolumes(cli kubernetes.Interface, sset *appsv1.StatefulSet, pod *v1.Pod) (volNameToPvc map[string]string) { +func StatefulSetVolumes(cli kubernetes.Interface, sset *appsv1.StatefulSet, pod *corev1.Pod) (volNameToPvc map[string]string) { ordinal := getOrdinal(pod.Name) if ordinal == -1 { // Pod not created through the statefulset? @@ -482,7 +482,7 @@ func StatefulSetVolumes(cli kubernetes.Interface, sset *appsv1.StatefulSet, pod // DeploymentConfigVolumes returns the PVCs references by a pod in this deployment config as a [pod spec volume name]-> [PVC name] map // will mostly be used for the applications running in open shift clusters -func DeploymentConfigVolumes(osCli osversioned.Interface, depConfig *osAppsv1.DeploymentConfig, pod *v1.Pod) (volNameToPvc map[string]string) { +func DeploymentConfigVolumes(osCli osversioned.Interface, depConfig *osAppsv1.DeploymentConfig, pod *corev1.Pod) (volNameToPvc map[string]string) { volNameToPvc = make(map[string]string) for _, v := range depConfig.Spec.Template.Spec.Volumes { if v.PersistentVolumeClaim == nil { diff --git a/pkg/kube/workload_ready_test.go b/pkg/kube/workload_ready_test.go index d2b32d21bd..e0f8d41e8f 100644 --- a/pkg/kube/workload_ready_test.go +++ b/pkg/kube/workload_ready_test.go @@ -6,7 +6,7 @@ import ( . "gopkg.in/check.v1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -28,7 +28,7 @@ type cliParams struct { statusAvailableReplicas int32 generation int64 observedGeneration int64 - podStatus v1.PodPhase + podStatus corev1.PodPhase } // These tests can be used to force the various error states @@ -138,13 +138,13 @@ func getCli(cp cliParams) kubernetes.Interface { ObservedGeneration: cp.observedGeneration, }, }, - &v1.Pod{ + &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "pod", Namespace: cp.namespace, OwnerReferences: []metav1.OwnerReference{{UID: pUID}}, }, - Status: v1.PodStatus{ + Status: corev1.PodStatus{ Phase: cp.podStatus, }, }, diff --git a/pkg/kube/workload_test.go b/pkg/kube/workload_test.go index 132fa5bd99..f58050520e 100644 --- a/pkg/kube/workload_test.go +++ b/pkg/kube/workload_test.go @@ -6,7 +6,7 @@ import ( osapps "github.com/openshift/api/apps/v1" osversioned "github.com/openshift/client-go/apps/clientset/versioned" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -31,7 +31,7 @@ func (s *WorkloadSuite) TestScaleDeploymentConfig(c *C) { } // Create a test namespace - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "dc-scale-test-", }, @@ -66,14 +66,14 @@ func newDeploymentConfig() *osapps.DeploymentConfig { Selector: map[string]string{ "app": "test", }, - Template: &v1.PodTemplateSpec{ + Template: &corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "test", }, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Image: "alpine", Name: "container", diff --git a/pkg/location/location_test.go b/pkg/location/location_test.go index ec19d9f2c9..eb11778b96 100644 --- a/pkg/location/location_test.go +++ b/pkg/location/location_test.go @@ -25,7 +25,7 @@ import ( "time" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/blockstorage" @@ -223,8 +223,8 @@ func (s *LocationSuite) TestGetAzureSecret(c *C) { ID: "id", Secret: "secret", }, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("said"), secrets.AzureStorageAccountKey: []byte("sakey"), @@ -245,8 +245,8 @@ func (s *LocationSuite) TestGetAzureSecret(c *C) { ID: "id", Secret: "secret", }, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("said"), secrets.AzureStorageAccountKey: []byte("sakey"), @@ -268,8 +268,8 @@ func (s *LocationSuite) TestGetAzureSecret(c *C) { ID: "id", Secret: "secret", }, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("said"), secrets.AzureStorageEnvironment: []byte("env"), @@ -290,8 +290,8 @@ func (s *LocationSuite) TestGetAzureSecret(c *C) { ID: "id", Secret: "secret", }, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("said"), secrets.AzureStorageAccountKey: []byte("sakey"), diff --git a/pkg/param/param.go b/pkg/param/param.go index 6c4c4755b8..b0af81a5df 100644 --- a/pkg/param/param.go +++ b/pkg/param/param.go @@ -23,7 +23,7 @@ import ( osversioned "github.com/openshift/client-go/apps/clientset/versioned" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" @@ -50,8 +50,8 @@ type TemplateParams struct { PVC *PVCParams Namespace *NamespaceParams ArtifactsIn map[string]crv1alpha1.Artifact - ConfigMaps map[string]v1.ConfigMap - Secrets map[string]v1.Secret + ConfigMaps map[string]corev1.ConfigMap + Secrets map[string]corev1.Secret Time string Profile *Profile RepositoryServer *RepositoryServer @@ -122,7 +122,7 @@ const ( type Credential struct { Type CredentialType KeyPair *KeyPair - Secret *v1.Secret + Secret *corev1.Secret KopiaServerSecret *KopiaServerCreds } @@ -154,13 +154,13 @@ type RepositoryServer struct { } type RepositoryServerCredentials struct { - ServerTLS v1.Secret - ServerUserAccess v1.Secret + ServerTLS corev1.Secret + ServerUserAccess corev1.Secret } // Phase represents a Blueprint phase and contains the phase output type Phase struct { - Secrets map[string]v1.Secret + Secrets map[string]corev1.Secret Output map[string]interface{} } @@ -387,7 +387,7 @@ func fetchSecretCredential(ctx context.Context, cli kubernetes.Interface, sr *cr }, nil } -func secretFromSecretRef(ctx context.Context, cli kubernetes.Interface, ref v1.SecretReference) (*v1.Secret, error) { +func secretFromSecretRef(ctx context.Context, cli kubernetes.Interface, ref corev1.SecretReference) (*corev1.Secret, error) { secret, err := cli.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { return nil, errors.Wrap(err, fmt.Sprintf("Error fetching secret %s from namespace %s", ref.Name, ref.Namespace)) @@ -406,8 +406,8 @@ func filterByKind(refs map[string]crv1alpha1.ObjectReference, kind string) map[s return filtered } -func fetchSecrets(ctx context.Context, cli kubernetes.Interface, refs map[string]crv1alpha1.ObjectReference) (map[string]v1.Secret, error) { - secrets := make(map[string]v1.Secret, len(refs)) +func fetchSecrets(ctx context.Context, cli kubernetes.Interface, refs map[string]crv1alpha1.ObjectReference) (map[string]corev1.Secret, error) { + secrets := make(map[string]corev1.Secret, len(refs)) for name, ref := range refs { s, err := cli.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { @@ -418,8 +418,8 @@ func fetchSecrets(ctx context.Context, cli kubernetes.Interface, refs map[string return secrets, nil } -func fetchConfigMaps(ctx context.Context, cli kubernetes.Interface, refs map[string]crv1alpha1.ObjectReference) (map[string]v1.ConfigMap, error) { - configs := make(map[string]v1.ConfigMap, len(refs)) +func fetchConfigMaps(ctx context.Context, cli kubernetes.Interface, refs map[string]crv1alpha1.ObjectReference) (map[string]corev1.ConfigMap, error) { + configs := make(map[string]corev1.ConfigMap, len(refs)) for name, ref := range refs { c, err := cli.CoreV1().ConfigMaps(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) if err != nil { @@ -530,7 +530,7 @@ func fetchDeploymentParams(ctx context.Context, cli kubernetes.Interface, namesp return dp, nil } -func containerNames(pod v1.Pod) []string { +func containerNames(pod corev1.Pod) []string { cs := make([]string, 0, len(pod.Status.ContainerStatuses)) for _, c := range pod.Status.ContainerStatuses { cs = append(cs, c.Name) @@ -538,7 +538,7 @@ func containerNames(pod v1.Pod) []string { return cs } -func volumes(pod v1.Pod, volToPvc map[string]string) map[string]string { +func volumes(pod corev1.Pod, volToPvc map[string]string) map[string]string { pvcToMountPath := make(map[string]string) for _, c := range pod.Spec.Containers { for _, v := range c.VolumeMounts { diff --git a/pkg/param/param_test.go b/pkg/param/param_test.go index a86371c47b..be76297ccc 100644 --- a/pkg/param/param_test.go +++ b/pkg/param/param_test.go @@ -26,7 +26,7 @@ import ( "github.com/Masterminds/sprig" . "gopkg.in/check.v1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -61,7 +61,7 @@ func (s *ParamsSuite) SetUpSuite(c *C) { cli, err := kube.NewClient() c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterparamstest-", }, @@ -73,15 +73,15 @@ func (s *ParamsSuite) SetUpSuite(c *C) { } func (s *ParamsSuite) SetUpTest(c *C) { - pvc := &v1.PersistentVolumeClaim{ + pvc := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanisterparamtest-", }, - Spec: v1.PersistentVolumeClaimSpec{ - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("1Gi"), }, }, }, @@ -359,7 +359,7 @@ func (s *ParamsSuite) testNewTemplateParams(ctx context.Context, c *C, dynCli dy c.Assert(err, IsNil) c.Assert(cm, NotNil) - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "secret-name", Namespace: s.namespace, @@ -464,19 +464,19 @@ func (s *ParamsSuite) testNewTemplateParams(ctx context.Context, c *C, dynCli dy func (s *ParamsSuite) TestfetchKVSecretCredential(c *C) { ctx := context.Background() for _, tc := range []struct { - secret *v1.Secret + secret *corev1.Secret kvs *crv1alpha1.KeyPair checker Checker cred *Credential }{ { - secret: &v1.Secret{}, + secret: &corev1.Secret{}, kvs: &crv1alpha1.KeyPair{}, cred: nil, checker: NotNil, }, { - secret: &v1.Secret{ + secret: &corev1.Secret{ Data: map[string][]byte{ "myKey": []byte("foo"), "myValue": []byte("bar"), @@ -512,14 +512,14 @@ func (s *ParamsSuite) TestProfile(c *C) { Labels: map[string]string{"app": "fake-app"}, }, } - pod := &v1.Pod{ + pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "podName", Namespace: s.namespace, Labels: map[string]string{"app": "fake-app"}, }, } - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "secretName", Namespace: s.namespace, @@ -608,7 +608,7 @@ func (s *ParamsSuite) TestProfile(c *C) { func (s *ParamsSuite) TestParamsWithoutProfile(c *C) { ctx := context.Background() - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "secret-name", Namespace: s.namespace, @@ -653,7 +653,7 @@ func (s *ParamsSuite) TestParamsWithoutProfile(c *C) { func (s *ParamsSuite) TestPhaseParams(c *C) { ctx := context.Background() - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "secret-name", Namespace: s.namespace, @@ -733,7 +733,7 @@ func (s *ParamsSuite) TestPhaseParams(c *C) { func (s *ParamsSuite) TestRenderingPhaseParams(c *C) { ctx := context.Background() - secret := &v1.Secret{ + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "secret-dfss", Namespace: "ns1", @@ -791,14 +791,14 @@ func newDeploymentConfig() *osapps.DeploymentConfig { Selector: map[string]string{ "app": "test", }, - Template: &v1.PodTemplateSpec{ + Template: &corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "test", }, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Image: "alpine", Name: "container", diff --git a/pkg/reconcile/reconcile_test.go b/pkg/reconcile/reconcile_test.go index 96c7100eb8..657e410e6c 100644 --- a/pkg/reconcile/reconcile_test.go +++ b/pkg/reconcile/reconcile_test.go @@ -20,7 +20,7 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -55,7 +55,7 @@ func (s *ReconcileSuite) SetUpSuite(c *C) { s.crCli = crCli // Create Namespace - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "reconciletest-", }, diff --git a/pkg/resource/resource_test.go b/pkg/resource/resource_test.go index 54ad5410e7..fc7959d42c 100644 --- a/pkg/resource/resource_test.go +++ b/pkg/resource/resource_test.go @@ -19,7 +19,7 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -42,7 +42,7 @@ func (s *ResourceSuite) SetUpSuite(c *C) { cli, err := kube.NewClient() c.Assert(err, IsNil) s.cli = cli - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanistercontrollertest-", }, diff --git a/pkg/restic/restic.go b/pkg/restic/restic.go index 116e214165..996a85cadf 100644 --- a/pkg/restic/restic.go +++ b/pkg/restic/restic.go @@ -23,7 +23,7 @@ import ( "strings" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" @@ -235,7 +235,7 @@ func resticS3CredentialArgs(creds param.Credential) ([]string, error) { } } -func resticS3CredentialSecretArgs(secret *v1.Secret) ([]string, error) { +func resticS3CredentialSecretArgs(secret *corev1.Secret) ([]string, error) { creds, err := secrets.ExtractAWSCredentials(context.Background(), secret, aws.AssumeRoleDurationDefault) if err != nil { return nil, err diff --git a/pkg/restic/restic_test.go b/pkg/restic/restic_test.go index 123deb3a3c..7154316418 100644 --- a/pkg/restic/restic_test.go +++ b/pkg/restic/restic_test.go @@ -18,9 +18,9 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/config" "github.com/kanisterio/kanister/pkg/param" "github.com/kanisterio/kanister/pkg/secrets" @@ -72,8 +72,8 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }{ { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint", }, Credential: param.Credential{ @@ -96,8 +96,8 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint/", // Remove trailing slash }, Credential: param.Credential{ @@ -120,8 +120,8 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint/////////", // Also remove all of the trailing slashes }, Credential: param.Credential{ @@ -144,13 +144,13 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint", // Also remove all of the trailing slashes }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ + Secret: &corev1.Secret{ Type: "secrets.kanister.io/aws", Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte("id"), @@ -171,13 +171,13 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeAzure, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeAzure, }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("id"), secrets.AzureStorageAccountKey: []byte("secret"), @@ -197,13 +197,13 @@ func (s *ResticDataSuite) TestResticArgs(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeAzure, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeAzure, }, Credential: param.Credential{ Type: param.CredentialTypeKeyPair, - Secret: &v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + Secret: &corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), Data: map[string][]byte{ secrets.AzureStorageAccountID: []byte("id"), secrets.AzureStorageAccountKey: []byte("secret"), @@ -239,13 +239,13 @@ func (s *ResticDataSuite) TestResticArgsWithAWSRole(c *C) { }{ { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint", // Also remove all of the trailing slashes }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ + Secret: &corev1.Secret{ Type: "secrets.kanister.io/aws", Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte(config.GetEnvOrSkip(c, "AWS_ACCESS_KEY_ID")), @@ -259,13 +259,13 @@ func (s *ResticDataSuite) TestResticArgsWithAWSRole(c *C) { }, { profile: ¶m.Profile{ - Location: v1alpha1.Location{ - Type: v1alpha1.LocationTypeS3Compliant, + Location: crv1alpha1.Location{ + Type: crv1alpha1.LocationTypeS3Compliant, Endpoint: "endpoint", // Also remove all of the trailing slashes }, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ + Secret: &corev1.Secret{ Type: "secrets.kanister.io/aws", Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte(config.GetEnvOrSkip(c, "AWS_ACCESS_KEY_ID")), diff --git a/pkg/secrets/aws.go b/pkg/secrets/aws.go index d469d71628..9692c0c25b 100644 --- a/pkg/secrets/aws.go +++ b/pkg/secrets/aws.go @@ -20,7 +20,7 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/field" @@ -53,7 +53,7 @@ const ( // // Optional field: // - session_token -func ValidateAWSCredentials(secret *v1.Secret) error { +func ValidateAWSCredentials(secret *corev1.Secret) error { if string(secret.Type) != AWSSecretType { return errors.Wrapf(secerrors.ErrValidate, secerrors.IncompatibleSecretTypeErrorMsg, AWSSecretType, secret.Namespace, secret.Name) } @@ -91,7 +91,7 @@ func ValidateAWSCredentials(secret *v1.Secret) error { // of the IAM role - The setting can be viewed using instructions here // https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session. // The IAM role's max duration setting can be modified between 1h to 12h. -func ExtractAWSCredentials(ctx context.Context, secret *v1.Secret, assumeRoleDuration time.Duration) (*credentials.Value, error) { +func ExtractAWSCredentials(ctx context.Context, secret *corev1.Secret, assumeRoleDuration time.Duration) (*credentials.Value, error) { if err := ValidateAWSCredentials(secret); err != nil { return nil, err } diff --git a/pkg/secrets/aws_test.go b/pkg/secrets/aws_test.go index 3cf704a80a..a355f06302 100644 --- a/pkg/secrets/aws_test.go +++ b/pkg/secrets/aws_test.go @@ -19,7 +19,7 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/config" @@ -31,13 +31,13 @@ var _ = Suite(&AWSSecretSuite{}) func (s *AWSSecretSuite) TestExtractAWSCredentials(c *C) { tcs := []struct { - secret *v1.Secret + secret *corev1.Secret expected *credentials.Value errChecker Checker }{ { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSAccessKeyID: []byte("key_id"), AWSSecretAccessKey: []byte("secret_key"), @@ -51,15 +51,15 @@ func (s *AWSSecretSuite) TestExtractAWSCredentials(c *C) { errChecker: IsNil, }, { - secret: &v1.Secret{ + secret: &corev1.Secret{ Type: "Opaque", }, expected: nil, errChecker: NotNil, }, { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSSecretAccessKey: []byte("secret_key"), }, @@ -68,8 +68,8 @@ func (s *AWSSecretSuite) TestExtractAWSCredentials(c *C) { errChecker: NotNil, }, { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSAccessKeyID: []byte("key_id"), }, @@ -78,8 +78,8 @@ func (s *AWSSecretSuite) TestExtractAWSCredentials(c *C) { errChecker: NotNil, }, { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSAccessKeyID: []byte("key_id"), AWSSecretAccessKey: []byte("secret_key"), @@ -99,12 +99,12 @@ func (s *AWSSecretSuite) TestExtractAWSCredentials(c *C) { func (s *AWSSecretSuite) TestExtractAWSCredentialsWithSessionToken(c *C) { for _, tc := range []struct { - secret *v1.Secret + secret *corev1.Secret output Checker }{ { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSAccessKeyID: []byte(config.GetEnvOrSkip(c, "AWS_ACCESS_KEY_ID")), AWSSecretAccessKey: []byte(config.GetEnvOrSkip(c, "AWS_SECRET_ACCESS_KEY")), @@ -114,8 +114,8 @@ func (s *AWSSecretSuite) TestExtractAWSCredentialsWithSessionToken(c *C) { output: IsNil, }, { - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AWSAccessKeyID: []byte(config.GetEnvOrSkip(c, "AWS_ACCESS_KEY_ID")), AWSSecretAccessKey: []byte(config.GetEnvOrSkip(c, "AWS_SECRET_ACCESS_KEY")), diff --git a/pkg/secrets/azure.go b/pkg/secrets/azure.go index 4a1ca013c8..f03a0dddce 100644 --- a/pkg/secrets/azure.go +++ b/pkg/secrets/azure.go @@ -16,7 +16,7 @@ package secrets import ( "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "github.com/kanisterio/kanister/pkg/objectstore" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -44,7 +44,7 @@ const ( // // Optional field: // - azure_storage_environment -func ValidateAzureCredentials(secret *v1.Secret) error { +func ValidateAzureCredentials(secret *corev1.Secret) error { if string(secret.Type) != AzureSecretType { return errors.Wrapf(secerrors.ErrValidate, secerrors.IncompatibleSecretTypeErrorMsg, AzureSecretType, secret.Namespace, secret.Name) } @@ -73,7 +73,7 @@ func ValidateAzureCredentials(secret *v1.Secret) error { // // If the type of the secret is not "secrets.kanister.io/azure", it returns an error. // If the required types are not available in the secrets, it returns an error. -func ExtractAzureCredentials(secret *v1.Secret) (*objectstore.SecretAzure, error) { +func ExtractAzureCredentials(secret *corev1.Secret) (*objectstore.SecretAzure, error) { if err := ValidateAzureCredentials(secret); err != nil { return nil, err } diff --git a/pkg/secrets/azure_test.go b/pkg/secrets/azure_test.go index 5eeb7f35f2..75d528f15d 100644 --- a/pkg/secrets/azure_test.go +++ b/pkg/secrets/azure_test.go @@ -17,7 +17,7 @@ package secrets import ( "github.com/kanisterio/kanister/pkg/objectstore" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" ) type AzureSecretSuite struct{} @@ -26,13 +26,13 @@ var _ = Suite(&AzureSecretSuite{}) func (s *AzureSecretSuite) TestExtractAzureCredentials(c *C) { for i, tc := range []struct { - secret *v1.Secret + secret *corev1.Secret expected *objectstore.SecretAzure errChecker Checker }{ { - secret: &v1.Secret{ - Type: v1.SecretType(AzureSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AzureSecretType), Data: map[string][]byte{ AzureStorageAccountID: []byte("key_id"), AzureStorageAccountKey: []byte("secret_key"), @@ -47,8 +47,8 @@ func (s *AzureSecretSuite) TestExtractAzureCredentials(c *C) { errChecker: IsNil, }, { // bad type - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), Data: map[string][]byte{ AzureStorageAccountID: []byte("key_id"), AzureStorageAccountKey: []byte("secret_key"), @@ -59,8 +59,8 @@ func (s *AzureSecretSuite) TestExtractAzureCredentials(c *C) { errChecker: NotNil, }, { // missing field - secret: &v1.Secret{ - Type: v1.SecretType(AzureSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AzureSecretType), Data: map[string][]byte{ AzureStorageAccountID: []byte("key_id"), AzureStorageEnvironment: []byte("env"), @@ -70,8 +70,8 @@ func (s *AzureSecretSuite) TestExtractAzureCredentials(c *C) { errChecker: NotNil, }, { // additional field - secret: &v1.Secret{ - Type: v1.SecretType(AzureSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AzureSecretType), Data: map[string][]byte{ AzureStorageAccountID: []byte("key_id"), AzureStorageAccountKey: []byte("secret_key"), diff --git a/pkg/secrets/gcp.go b/pkg/secrets/gcp.go index b30ecda4cd..f9758e5ea0 100644 --- a/pkg/secrets/gcp.go +++ b/pkg/secrets/gcp.go @@ -16,7 +16,7 @@ package secrets import ( "github.com/pkg/errors" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" ) @@ -35,7 +35,7 @@ const ( // ValidateGCPCredentials function is to verify the schema of GCP secrets // that need to be provided for kopia commands -func ValidateGCPCredentials(secret *v1.Secret) error { +func ValidateGCPCredentials(secret *corev1.Secret) error { // Required fields for the secret are // - GCPProjectID // - GCPServiceAccountJsonKey diff --git a/pkg/secrets/gcp_test.go b/pkg/secrets/gcp_test.go index 0db18a01dd..d8bcd48127 100644 --- a/pkg/secrets/gcp_test.go +++ b/pkg/secrets/gcp_test.go @@ -20,7 +20,7 @@ import ( secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -32,13 +32,13 @@ func (s *GCPSecretSuite) TestValidateGCPCredentials(c *C) { serviceAccountJson := make([]byte, base64.StdEncoding.EncodedLen(len([]byte("service_account_json")))) base64.StdEncoding.Encode(serviceAccountJson, []byte("service_account_json")) for i, tc := range []struct { - secret *v1.Secret + secret *corev1.Secret errChecker Checker expectedErr error }{ { - secret: &v1.Secret{ - Type: v1.SecretType(GCPSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(GCPSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -52,8 +52,8 @@ func (s *GCPSecretSuite) TestValidateGCPCredentials(c *C) { expectedErr: nil, }, { // Incompatible secret type - secret: &v1.Secret{ - Type: v1.SecretType(AWSSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(AWSSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -67,8 +67,8 @@ func (s *GCPSecretSuite) TestValidateGCPCredentials(c *C) { expectedErr: errors.Wrapf(secerrors.ErrValidate, secerrors.IncompatibleSecretTypeErrorMsg, GCPSecretType, "ns", "sec"), }, { // missing field - GCPServiceKey - secret: &v1.Secret{ - Type: v1.SecretType(GCPSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(GCPSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -81,8 +81,8 @@ func (s *GCPSecretSuite) TestValidateGCPCredentials(c *C) { errChecker: NotNil, }, { // missing field - GCPProjectID - secret: &v1.Secret{ - Type: v1.SecretType(GCPSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(GCPSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -95,8 +95,8 @@ func (s *GCPSecretSuite) TestValidateGCPCredentials(c *C) { errChecker: NotNil, }, { // secret is Empty - secret: &v1.Secret{ - Type: v1.SecretType(GCPSecretType), + secret: &corev1.Secret{ + Type: corev1.SecretType(GCPSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/aws_secrets_test.go b/pkg/secrets/repositoryserver/aws_secrets_test.go index 5e5847d47b..8cb1e9cc56 100644 --- a/pkg/secrets/repositoryserver/aws_secrets_test.go +++ b/pkg/secrets/repositoryserver/aws_secrets_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *AWSSecretCredsSuite) TestValidateRepoServerAWSCredentials(c *C) { expectedError error }{ { // Valid AWS Secret - secret: NewAWSLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeS3), + secret: NewAWSLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeS3), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -48,8 +48,8 @@ func (s *AWSSecretCredsSuite) TestValidateRepoServerAWSCredentials(c *C) { errChecker: IsNil, }, { // Missing required field - Region Key - secret: NewAWSLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeS3), + secret: NewAWSLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeS3), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -62,8 +62,8 @@ func (s *AWSSecretCredsSuite) TestValidateRepoServerAWSCredentials(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, RegionKey, "ns", "sec"), }, { // Missing required field - Bucket Key - secret: NewAWSLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeS3), + secret: NewAWSLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeS3), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -76,8 +76,8 @@ func (s *AWSSecretCredsSuite) TestValidateRepoServerAWSCredentials(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, BucketKey, "ns", "sec"), }, { // Empty Secret - secret: NewAWSLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeS3), + secret: NewAWSLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeS3), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/azure_secrets_test.go b/pkg/secrets/repositoryserver/azure_secrets_test.go index cc70e243a3..985b06db4d 100644 --- a/pkg/secrets/repositoryserver/azure_secrets_test.go +++ b/pkg/secrets/repositoryserver/azure_secrets_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *AzureSecretCredsSuite) TestValidateRepoServerAzureCredentials(c *C) { expectedError error }{ { // Valid Azure Secret - secret: NewAzureLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeAzure), + secret: NewAzureLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeAzure), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -48,8 +48,8 @@ func (s *AzureSecretCredsSuite) TestValidateRepoServerAzureCredentials(c *C) { errChecker: IsNil, }, { // Missing required field - Bucket Key - secret: NewAzureLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeAzure), + secret: NewAzureLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeAzure), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -62,8 +62,8 @@ func (s *AzureSecretCredsSuite) TestValidateRepoServerAzureCredentials(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, BucketKey, "ns", "sec"), }, { // Empty Secret - secret: NewAzureLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeAzure), + secret: NewAzureLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeAzure), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/gcp_secrets_test.go b/pkg/secrets/repositoryserver/gcp_secrets_test.go index 2ba1afa758..01dbe80f6d 100644 --- a/pkg/secrets/repositoryserver/gcp_secrets_test.go +++ b/pkg/secrets/repositoryserver/gcp_secrets_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepoServerGCPCredentials(c *C) { expectedError error }{ { // Valid GCP Secret - secret: NewGCPLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeGCS), + secret: NewGCPLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeGCS), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -48,8 +48,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepoServerGCPCredentials(c *C) { errChecker: IsNil, }, { // Missing required field - Bucket Key - secret: NewGCPLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeGCS), + secret: NewGCPLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeGCS), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -62,8 +62,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepoServerGCPCredentials(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, BucketKey, "ns", "sec"), }, { // Empty Secret - secret: NewGCPLocation(&v1.Secret{ - Type: v1.SecretType(LocTypeGCS), + secret: NewGCPLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypeGCS), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/repository_password_test.go b/pkg/secrets/repositoryserver/repository_password_test.go index 6298eb459e..d0c76107b4 100644 --- a/pkg/secrets/repositoryserver/repository_password_test.go +++ b/pkg/secrets/repositoryserver/repository_password_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryPassword(c *C) { expectedError error }{ { // Valid Repository Password Secret - secret: NewRepoPassword(&v1.Secret{ - Type: v1.SecretType(RepositoryPasswordSecret), + secret: NewRepoPassword(&corev1.Secret{ + Type: corev1.SecretType(RepositoryPasswordSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -47,8 +47,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryPassword(c *C) { errChecker: IsNil, }, { // Missing required field - Repo Password Key - secret: NewRepoPassword(&v1.Secret{ - Type: v1.SecretType(RepositoryPasswordSecret), + secret: NewRepoPassword(&corev1.Secret{ + Type: corev1.SecretType(RepositoryPasswordSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -61,8 +61,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryPassword(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, RepoPasswordKey, "ns", "sec"), }, { // Secret should contain only 1 key value pair - secret: NewRepoPassword(&v1.Secret{ - Type: v1.SecretType(RepositoryPasswordSecret), + secret: NewRepoPassword(&corev1.Secret{ + Type: corev1.SecretType(RepositoryPasswordSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -76,8 +76,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryPassword(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.UnknownFieldErrorMsg, "ns", "sec"), }, { // Empty Secret - secret: NewRepoPassword(&v1.Secret{ - Type: v1.SecretType(RepositoryPasswordSecret), + secret: NewRepoPassword(&corev1.Secret{ + Type: corev1.SecretType(RepositoryPasswordSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/repository_server_admin_credentials_test.go b/pkg/secrets/repositoryserver/repository_server_admin_credentials_test.go index a6a8e5b4d3..ad4799453b 100644 --- a/pkg/secrets/repositoryserver/repository_server_admin_credentials_test.go +++ b/pkg/secrets/repositoryserver/repository_server_admin_credentials_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryServerAdminCredentials(c *C) expectedError error }{ { // Valid Repository Server Admin Credentials Secret - secret: NewRepositoryServerAdminCredentials(&v1.Secret{ - Type: v1.SecretType(AdminCredentialsSecret), + secret: NewRepositoryServerAdminCredentials(&corev1.Secret{ + Type: corev1.SecretType(AdminCredentialsSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -48,8 +48,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryServerAdminCredentials(c *C) errChecker: IsNil, }, { // Missing required field - AdminUsernameKey - secret: NewRepositoryServerAdminCredentials(&v1.Secret{ - Type: v1.SecretType(AdminCredentialsSecret), + secret: NewRepositoryServerAdminCredentials(&corev1.Secret{ + Type: corev1.SecretType(AdminCredentialsSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -63,8 +63,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryServerAdminCredentials(c *C) expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, AdminUsernameKey, "ns", "sec"), }, { // Missing required field - AdminPasswordKey - secret: NewRepositoryServerAdminCredentials(&v1.Secret{ - Type: v1.SecretType(AdminCredentialsSecret), + secret: NewRepositoryServerAdminCredentials(&corev1.Secret{ + Type: corev1.SecretType(AdminCredentialsSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -78,8 +78,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryServerAdminCredentials(c *C) expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, AdminPasswordKey, "ns", "sec"), }, { // Secret should contain only 2 key value pairs - secret: NewRepositoryServerAdminCredentials(&v1.Secret{ - Type: v1.SecretType(AdminCredentialsSecret), + secret: NewRepositoryServerAdminCredentials(&corev1.Secret{ + Type: corev1.SecretType(AdminCredentialsSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -94,8 +94,8 @@ func (s *GCPSecretCredsSuite) TestValidateRepositoryServerAdminCredentials(c *C) expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.UnknownFieldErrorMsg, "ns", "sec"), }, { // Empty Secret - secret: NewRepositoryServerAdminCredentials(&v1.Secret{ - Type: v1.SecretType(AdminCredentialsSecret), + secret: NewRepositoryServerAdminCredentials(&corev1.Secret{ + Type: corev1.SecretType(AdminCredentialsSecret), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/repositoryserver/s3compliant_secrets_test.go b/pkg/secrets/repositoryserver/s3compliant_secrets_test.go index 2e8d81568a..29b14450d3 100644 --- a/pkg/secrets/repositoryserver/s3compliant_secrets_test.go +++ b/pkg/secrets/repositoryserver/s3compliant_secrets_test.go @@ -17,7 +17,7 @@ package repositoryserver import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -34,8 +34,8 @@ func (s *S3CompliantSecretTestSuite) TestValidateRepoServerS3CompliantCredential expectedError error }{ { // Valid S3 Compatible Secret - secret: NewS3CompliantLocation(&v1.Secret{ - Type: v1.SecretType(LocTypes3Compliant), + secret: NewS3CompliantLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypes3Compliant), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -49,8 +49,8 @@ func (s *S3CompliantSecretTestSuite) TestValidateRepoServerS3CompliantCredential errChecker: IsNil, }, { // Missing required field - Bucket Key - secret: NewS3CompliantLocation(&v1.Secret{ - Type: v1.SecretType(LocTypes3Compliant), + secret: NewS3CompliantLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypes3Compliant), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -64,8 +64,8 @@ func (s *S3CompliantSecretTestSuite) TestValidateRepoServerS3CompliantCredential expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, BucketKey, "ns", "sec"), }, { // Missing required field - Region Key - secret: NewS3CompliantLocation(&v1.Secret{ - Type: v1.SecretType(LocTypes3Compliant), + secret: NewS3CompliantLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypes3Compliant), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -79,8 +79,8 @@ func (s *S3CompliantSecretTestSuite) TestValidateRepoServerS3CompliantCredential expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, RegionKey, "ns", "sec"), }, { // Missing required field - Endpoint Key - secret: NewS3CompliantLocation(&v1.Secret{ - Type: v1.SecretType(LocTypes3Compliant), + secret: NewS3CompliantLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypes3Compliant), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -94,8 +94,8 @@ func (s *S3CompliantSecretTestSuite) TestValidateRepoServerS3CompliantCredential expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, EndpointKey, "ns", "sec"), }, { // Empty Secret - secret: NewS3CompliantLocation(&v1.Secret{ - Type: v1.SecretType(LocTypes3Compliant), + secret: NewS3CompliantLocation(&corev1.Secret{ + Type: corev1.SecretType(LocTypes3Compliant), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/secrets/secrets_test.go b/pkg/secrets/secrets_test.go index ddc54b8d6e..6ff2e30fd9 100644 --- a/pkg/secrets/secrets_test.go +++ b/pkg/secrets/secrets_test.go @@ -19,7 +19,7 @@ import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" secerrors "github.com/kanisterio/kanister/pkg/secrets/errors" @@ -35,14 +35,14 @@ var _ = Suite(&SecretUtilsSuite{}) func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { for i, tc := range []struct { - secret *v1.Secret + secret *corev1.Secret errChecker Checker locationSecretChecker Checker expectedError error }{ { // Valid secret type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), Data: map[string][]byte{ reposerver.TypeKey: []byte(reposerver.LocTypeGCS), }, @@ -52,8 +52,8 @@ func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { expectedError: nil, }, { // Valid secret type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), Data: map[string][]byte{ reposerver.TypeKey: []byte(reposerver.LocTypeAzure), }, @@ -63,8 +63,8 @@ func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { expectedError: nil, }, { // Valid secret type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), Data: map[string][]byte{ reposerver.TypeKey: []byte(reposerver.LocTypeS3), }, @@ -74,8 +74,8 @@ func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { expectedError: nil, }, { // Valid secret type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), Data: map[string][]byte{ reposerver.TypeKey: []byte(reposerver.LocTypeFilestore), }, @@ -85,8 +85,8 @@ func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { expectedError: nil, }, { // Missing location type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", @@ -97,8 +97,8 @@ func (s *SecretUtilsSuite) TestGetLocationSecret(c *C) { expectedError: errors.Wrapf(secerrors.ErrValidate, secerrors.MissingRequiredFieldErrorMsg, reposerver.TypeKey, "ns", "sec"), }, { // Unsupported location type - secret: &v1.Secret{ - Type: v1.SecretType(repositoryserver.Location), + secret: &corev1.Secret{ + Type: corev1.SecretType(repositoryserver.Location), ObjectMeta: metav1.ObjectMeta{ Name: "sec", Namespace: "ns", diff --git a/pkg/testing/e2e_test.go b/pkg/testing/e2e_test.go index ab32e072d4..4f0d7c7282 100644 --- a/pkg/testing/e2e_test.go +++ b/pkg/testing/e2e_test.go @@ -23,7 +23,7 @@ import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -56,7 +56,7 @@ func (s *E2ESuite) SetUpSuite(c *C) { c.Assert(err, IsNil) // Create a new test namespace - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "e2e-test-", }, @@ -182,7 +182,7 @@ func (s *E2ESuite) TestKubeTask(c *C) { c.Assert(err, IsNil) // Create test Profile and secret - sec := &v1.Secret{ + sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-secret-", }, diff --git a/pkg/testing/integration_test.go b/pkg/testing/integration_test.go index f7272d1959..260cf78132 100644 --- a/pkg/testing/integration_test.go +++ b/pkg/testing/integration_test.go @@ -25,7 +25,7 @@ import ( "github.com/pkg/errors" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/rand" @@ -58,7 +58,7 @@ type kanisterKontroller struct { context context.Context cancel context.CancelFunc kubeCli *kubernetes.Clientset - serviceAccount *v1.ServiceAccount + serviceAccount *corev1.ServiceAccount clusterRole *rbacv1.ClusterRole clusterRoleBinding *rbacv1.ClusterRoleBinding } @@ -139,7 +139,7 @@ const ( ) type secretProfile struct { - secret *v1.Secret + secret *corev1.Secret profile *crv1alpha1.Profile } @@ -435,7 +435,7 @@ func restoreActionSetSpecs(from *crv1alpha1.ActionSet, action string) (*crv1alph func createNamespace(cli kubernetes.Interface, name string) error { // Create Namespace - ns := &v1.Namespace{ + ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, @@ -473,8 +473,8 @@ func pingAppAndWait(ctx context.Context, a app.DatabaseApp) error { return err } -func getServiceAccount(namespace, name string) *v1.ServiceAccount { - return &v1.ServiceAccount{ +func getServiceAccount(namespace, name string) *corev1.ServiceAccount { + return &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, @@ -501,7 +501,7 @@ func getClusterRole(namespace string) *rbacv1.ClusterRole { } } -func getClusterRoleBinding(sa *v1.ServiceAccount, role *rbacv1.ClusterRole) *rbacv1.ClusterRoleBinding { +func getClusterRoleBinding(sa *corev1.ServiceAccount, role *rbacv1.ClusterRole) *rbacv1.ClusterRoleBinding { return &rbacv1.ClusterRoleBinding{ TypeMeta: metav1.TypeMeta{ Kind: "ClusterRoleBinding", diff --git a/pkg/testutil/fixture.go b/pkg/testutil/fixture.go index e710a2a1a0..5652a61c58 100644 --- a/pkg/testutil/fixture.go +++ b/pkg/testutil/fixture.go @@ -22,7 +22,7 @@ import ( "golang.org/x/oauth2/google" compute "google.golang.org/api/compute/v1" "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" awsconfig "github.com/kanisterio/kanister/pkg/aws" @@ -127,7 +127,7 @@ func s3ProfileWithSecretCredential(location crv1alpha1.Location, accessKeyID, se Location: location, Credential: param.Credential{ Type: param.CredentialTypeSecret, - Secret: &v1.Secret{ + Secret: &corev1.Secret{ Type: "secrets.kanister.io/aws", Data: map[string][]byte{ secrets.AWSAccessKeyID: []byte(accessKeyID), diff --git a/pkg/testutil/testutil.go b/pkg/testutil/testutil.go index 3ec9d3871c..f9d2c8ff03 100644 --- a/pkg/testutil/testutil.go +++ b/pkg/testutil/testutil.go @@ -31,12 +31,11 @@ import ( compute "google.golang.org/api/compute/v1" "gopkg.in/check.v1" appsv1 "k8s.io/api/apps/v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" awsconfig "github.com/kanisterio/kanister/pkg/aws" "github.com/kanisterio/kanister/pkg/blockstorage" @@ -55,16 +54,16 @@ const ( ) // NewTestPVC function returns a pointer to a new PVC test object -func NewTestPVC() *v1.PersistentVolumeClaim { - return &v1.PersistentVolumeClaim{ +func NewTestPVC() *corev1.PersistentVolumeClaim { + return &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanistercontrollertest", }, - Spec: v1.PersistentVolumeClaimSpec{ - AccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): resource.MustParse("1Gi"), + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceName(corev1.ResourceStorage): resource.MustParse("1Gi"), }, }, }, @@ -72,8 +71,8 @@ func NewTestPVC() *v1.PersistentVolumeClaim { } // NewTestNamespace function returns a pointer to a new Namespace test object -func NewTestNamespace() *v1.Namespace { - return &v1.Namespace{ +func NewTestNamespace() *corev1.Namespace { + return &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "kanistercontrollertest-", }, @@ -109,21 +108,21 @@ func NewTestStatefulSet(replicas int32) *appsv1.StatefulSet { } } -func newTestPodTemplateSpec() v1.PodTemplateSpec { - return v1.PodTemplateSpec{ +func newTestPodTemplateSpec() corev1.PodTemplateSpec { + return corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "fake-app", }, }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "test-container", Image: consts.LatestKanisterToolsImage, Command: []string{"tail"}, Args: []string{"-f", "/dev/null"}, - ImagePullPolicy: v1.PullAlways, + ImagePullPolicy: corev1.PullAlways, }, }, }, @@ -133,8 +132,8 @@ func newTestPodTemplateSpec() v1.PodTemplateSpec { const TestProfileName = "test-profile" // NewTestProfileSecret function returns a pointer to a new Secret test object. -func NewTestProfileSecret() *v1.Secret { - return &v1.Secret{ +func NewTestProfileSecret() *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-secret-", }, @@ -146,8 +145,8 @@ func NewTestProfileSecret() *v1.Secret { } // NewTestProfileSecretWithRole function returns a pointer to a new Secret test object with role. -func NewTestProfileSecretWithRole(role string) *v1.Secret { - return &v1.Secret{ +func NewTestProfileSecretWithRole(role string) *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-secret-", }, @@ -186,7 +185,7 @@ func NewTestProfile(namespace string, secretName string) *crv1alpha1.Profile { // NewSecretProfileFromLocation figures out Provider type from the location type and // returns a pointer to Secret and Profile -func NewSecretProfileFromLocation(location crv1alpha1.Location) (*v1.Secret, *crv1alpha1.Profile, error) { +func NewSecretProfileFromLocation(location crv1alpha1.Location) (*corev1.Secret, *crv1alpha1.Profile, error) { var key, val string data := make(map[string]string) @@ -217,8 +216,8 @@ func NewSecretProfileFromLocation(location crv1alpha1.Location) (*v1.Secret, *cr } // NewProfileSecret function returns a pointer to a new Secret test object. -func NewProfileSecret(data map[string]string) *v1.Secret { - return &v1.Secret{ +func NewProfileSecret(data map[string]string) *corev1.Secret { + return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-secret-", }, @@ -303,8 +302,8 @@ func NewTestActionSet(namespace, blueprintName, poKind, poName, poNamespace, ver } // NewTestConfigMap function returns a pointer to a new ConfigMap test object -func NewTestConfigMap() *v1.ConfigMap { - cm := &v1.ConfigMap{ +func NewTestConfigMap() *corev1.ConfigMap { + cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ GenerateName: "test-configmap-", }, @@ -359,8 +358,8 @@ func BlueprintWithConfigMap(bp *crv1alpha1.Blueprint) *crv1alpha1.Blueprint { return bp } -func CreateSecret(cli kubernetes.Interface, namespace, name string, secrettype v1.SecretType, data map[string][]byte) (se *v1.Secret, err error) { - secret := &v1.Secret{ +func CreateSecret(cli kubernetes.Interface, namespace, name string, secrettype corev1.SecretType, data map[string][]byte) (se *corev1.Secret, err error) { + secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ GenerateName: name, }, @@ -469,7 +468,7 @@ func GetDefaultS3CompliantStorageLocation() map[string][]byte { } } -func CreateTestKopiaRepository(cli kubernetes.Interface, rs *v1alpha1.RepositoryServer, storageLocation map[string][]byte) error { +func CreateTestKopiaRepository(cli kubernetes.Interface, rs *crv1alpha1.RepositoryServer, storageLocation map[string][]byte) error { contentCacheMB, metadataCacheMB := command.GetGeneralCacheSizeSettings() commandArgs := command.RepositoryCommandArgs{ @@ -503,10 +502,10 @@ func GetTestKopiaRepositoryServerCR(namespace string) crv1alpha1.RepositoryServe }, Spec: crv1alpha1.RepositoryServerSpec{ Storage: crv1alpha1.Storage{ - SecretRef: v1.SecretReference{ + SecretRef: corev1.SecretReference{ Namespace: namespace, }, - CredentialSecretRef: v1.SecretReference{ + CredentialSecretRef: corev1.SecretReference{ Namespace: namespace, }, }, @@ -514,21 +513,21 @@ func GetTestKopiaRepositoryServerCR(namespace string) crv1alpha1.RepositoryServe RootPath: KopiaRepositoryPath, Username: KopiaRepositoryUser, Hostname: KopiaRepositoryServerHost, - PasswordSecretRef: v1.SecretReference{ + PasswordSecretRef: corev1.SecretReference{ Namespace: namespace, }, }, Server: crv1alpha1.Server{ UserAccess: crv1alpha1.UserAccess{ - UserAccessSecretRef: v1.SecretReference{ + UserAccessSecretRef: corev1.SecretReference{ Namespace: namespace, }, Username: KopiaRepositoryServerAccessUser, }, - AdminSecretRef: v1.SecretReference{ + AdminSecretRef: corev1.SecretReference{ Namespace: namespace, }, - TLSSecretRef: v1.SecretReference{ + TLSSecretRef: corev1.SecretReference{ Namespace: namespace, }, }, diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index f7c8df979a..b6f7e086d2 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -19,7 +19,7 @@ import ( "testing" . "gopkg.in/check.v1" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" @@ -622,8 +622,8 @@ func (s *ValidateSuite) TestOsSecretFromProfile(c *C) { }, }, pType: objectstore.ProviderTypeAzure, - cli: fake.NewSimpleClientset(&v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + cli: fake.NewSimpleClientset(&corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "secname", Namespace: "secnamespace", @@ -659,8 +659,8 @@ func (s *ValidateSuite) TestOsSecretFromProfile(c *C) { }, }, pType: objectstore.ProviderTypeAzure, - cli: fake.NewSimpleClientset(&v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + cli: fake.NewSimpleClientset(&corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "secname", Namespace: "secnamespace", @@ -696,8 +696,8 @@ func (s *ValidateSuite) TestOsSecretFromProfile(c *C) { }, }, pType: objectstore.ProviderTypeAzure, - cli: fake.NewSimpleClientset(&v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + cli: fake.NewSimpleClientset(&corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "secname", Namespace: "secnamespace", @@ -726,8 +726,8 @@ func (s *ValidateSuite) TestOsSecretFromProfile(c *C) { }, }, pType: objectstore.ProviderTypeAzure, - cli: fake.NewSimpleClientset(&v1.Secret{ - Type: v1.SecretType(secrets.AzureSecretType), + cli: fake.NewSimpleClientset(&corev1.Secret{ + Type: corev1.SecretType(secrets.AzureSecretType), ObjectMeta: metav1.ObjectMeta{ Name: "secname", Namespace: "secnamespace", From 2f1bbe47de5f88cbceb4042833b01b6f80a397ef Mon Sep 17 00:00:00 2001 From: Ankit Date: Tue, 3 Oct 2023 10:45:40 +0530 Subject: [PATCH 09/17] Update new lint misses, add TODO for lint disables --- .../repositoryserver/repositoryserver_controller_test.go | 2 +- pkg/kube/volume/volume.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index 546501ead3..3040b8e9de 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -233,7 +233,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerImmutability(c *C) { repoServerCRCreated, err := s.crCli.RepositoryServers(s.repoServerControllerNamespace).Create(ctx, &repoServerCR, metav1.CreateOptions{}) c.Assert(err, IsNil) - //Update the repository server CR's Immutable field. + // Update the repository server CR's Immutable field. patch := []patchStringValue{{ Op: "replace", Path: "/spec/repository/rootPath", diff --git a/pkg/kube/volume/volume.go b/pkg/kube/volume/volume.go index 178f4e857a..08dc56fdd8 100644 --- a/pkg/kube/volume/volume.go +++ b/pkg/kube/volume/volume.go @@ -320,6 +320,9 @@ func labelSelector(labels map[string]string) string { // zoneToRegion removes -latter or just last latter from provided zone. func zoneToRegion(zone string) string { + // TODO: gocritic rule below suggests to use regexp.MustCompile but it + // panics if regex cannot be compiled. We should add proper test before + // enabling this below so that no change to this regex results in a panic r, _ := regexp.Compile("-?[a-z]$") //nolint:gocritic return r.ReplaceAllString(zone, "") } From 41933d9b1c873354586003f5ae40343fac071c99 Mon Sep 17 00:00:00 2001 From: Ankit Date: Tue, 3 Oct 2023 11:16:42 +0530 Subject: [PATCH 10/17] Merge master, resolve conflicts --- cmd/reposervercontroller/main.go | 3 +-- pkg/controllers/repositoryserver/repository.go | 10 +++++----- .../repositoryserver_controller_test.go | 9 ++++----- pkg/kube/pod_controller_processor.go | 6 +++--- pkg/param/param.go | 5 ++--- pkg/validatingwebhook/repositoryserver_handler.go | 6 +++--- 6 files changed, 18 insertions(+), 21 deletions(-) diff --git a/cmd/reposervercontroller/main.go b/cmd/reposervercontroller/main.go index 1efb30b57c..22a8a8bd73 100644 --- a/cmd/reposervercontroller/main.go +++ b/cmd/reposervercontroller/main.go @@ -33,7 +33,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/controllers/repositoryserver" "github.com/kanisterio/kanister/pkg/log" @@ -140,7 +139,7 @@ func main() { if k8sserverVersion.Major == "1" && minorVersion < minorK8sVersion { if validatingwebhook.IsCACertMounted() { hookServer := mgr.GetWebhookServer() - webhook := admission.WithCustomValidator(&v1alpha1.RepositoryServer{}, &validatingwebhook.RepositoryServerValidator{}) + webhook := admission.WithCustomValidator(&crv1alpha1.RepositoryServer{}, &validatingwebhook.RepositoryServerValidator{}) hookServer.Register(whHandlePath, webhook) hookServer.CertDir = validatingwebhook.WHCertsDir hookServer.Port = webhookServerPort diff --git a/pkg/controllers/repositoryserver/repository.go b/pkg/controllers/repositoryserver/repository.go index 48abb99426..4279ceb941 100644 --- a/pkg/controllers/repositoryserver/repository.go +++ b/pkg/controllers/repositoryserver/repository.go @@ -15,7 +15,7 @@ package repositoryserver import ( - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/kopia/command" "github.com/kanisterio/kanister/pkg/kopia/repository" reposerver "github.com/kanisterio/kanister/pkg/secrets/repositoryserver" @@ -49,8 +49,8 @@ func (h *RepoServerHandler) connectToKopiaRepository() error { ) } -func (h *RepoServerHandler) getRepositoryConfiguration() v1alpha1.Configuration { - configuration := v1alpha1.Configuration{ +func (h *RepoServerHandler) getRepositoryConfiguration() crv1alpha1.Configuration { + configuration := crv1alpha1.Configuration{ ConfigFilePath: command.DefaultConfigFilePath, LogDirectory: command.DefaultLogDirectory, CacheDirectory: command.DefaultCacheDirectory, @@ -68,9 +68,9 @@ func (h *RepoServerHandler) getRepositoryConfiguration() v1alpha1.Configuration return configuration } -func (h *RepoServerHandler) getRepositoryCacheSettings() v1alpha1.CacheSizeSettings { +func (h *RepoServerHandler) getRepositoryCacheSettings() crv1alpha1.CacheSizeSettings { defaultContentCacheMB, defaultMetadataCacheMB := command.GetGeneralCacheSizeSettings() - cacheSizeSettings := v1alpha1.CacheSizeSettings{ + cacheSizeSettings := crv1alpha1.CacheSizeSettings{ Metadata: &defaultMetadataCacheMB, Content: &defaultContentCacheMB, } diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index c47f468298..eede251e6b 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -37,7 +37,6 @@ import ( k8sscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crclientv1alpha1 "github.com/kanisterio/kanister/pkg/client/clientset/versioned/typed/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/consts" @@ -346,7 +345,7 @@ func (s *RepoServerControllerSuite) TestInvalidRepositoryPassword(c *C) { state, err := s.waitOnRepositoryServerState(c, repoServerCRCreated.Name) c.Assert(err, NotNil) - c.Assert(state, Equals, v1alpha1.Failed) + c.Assert(state, Equals, crv1alpha1.Failed) err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Delete(context.Background(), repoServerCRCreated.Name, metav1.DeleteOptions{}) c.Assert(err, IsNil) @@ -371,7 +370,7 @@ func (s *RepoServerControllerSuite) TestInvalidStorageLocation(c *C) { state, err := s.waitOnRepositoryServerState(c, repoServerCRCreated.Name) c.Assert(err, NotNil) - c.Assert(state, Equals, v1alpha1.Failed) + c.Assert(state, Equals, crv1alpha1.Failed) err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Delete(context.Background(), repoServerCRCreated.Name, metav1.DeleteOptions{}) c.Assert(err, IsNil) @@ -396,7 +395,7 @@ func (s *RepoServerControllerSuite) TestInvalidStorageLocationCredentials(c *C) state, err := s.waitOnRepositoryServerState(c, repoServerCRCreated.Name) c.Assert(err, NotNil) - c.Assert(state, Equals, v1alpha1.Failed) + c.Assert(state, Equals, crv1alpha1.Failed) err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Delete(context.Background(), repoServerCRCreated.Name, metav1.DeleteOptions{}) c.Assert(err, IsNil) @@ -482,7 +481,7 @@ func (s *RepoServerControllerSuite) waitForRepoServerInfoUpdateInCR(repoServerNa return err } -func (s *RepoServerControllerSuite) waitOnRepositoryServerState(c *C, reposerverName string) (v1alpha1.RepositoryServerProgress, error) { +func (s *RepoServerControllerSuite) waitOnRepositoryServerState(c *C, reposerverName string) (crv1alpha1.RepositoryServerProgress, error) { ctxTimeout := 5 * time.Minute ctx, cancel := context.WithTimeout(context.Background(), ctxTimeout) defer cancel() diff --git a/pkg/kube/pod_controller_processor.go b/pkg/kube/pod_controller_processor.go index 054364fd32..34a7ff9cd6 100644 --- a/pkg/kube/pod_controller_processor.go +++ b/pkg/kube/pod_controller_processor.go @@ -16,7 +16,7 @@ package kube import ( "context" - "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) @@ -24,7 +24,7 @@ import ( // PodControllerProcessor is an interface wrapping kubernetes API invocation // it is purposed to be replaced by fake implementation in tests type PodControllerProcessor interface { - CreatePod(ctx context.Context, options *PodOptions) (*v1.Pod, error) + CreatePod(ctx context.Context, options *PodOptions) (*corev1.Pod, error) WaitForPodReady(ctx context.Context, namespace, podName string) error WaitForPodCompletion(ctx context.Context, namespace, podName string) error DeletePod(ctx context.Context, namespace string, podName string, opts metav1.DeleteOptions) error @@ -34,7 +34,7 @@ type podControllerProcessor struct { cli kubernetes.Interface } -func (p *podControllerProcessor) CreatePod(ctx context.Context, options *PodOptions) (*v1.Pod, error) { +func (p *podControllerProcessor) CreatePod(ctx context.Context, options *PodOptions) (*corev1.Pod, error) { return CreatePod(ctx, p.cli, options) } diff --git a/pkg/param/param.go b/pkg/param/param.go index c717beb86c..d48eb14ce9 100644 --- a/pkg/param/param.go +++ b/pkg/param/param.go @@ -29,7 +29,6 @@ import ( "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/kanisterio/kanister/pkg/client/clientset/versioned" "github.com/kanisterio/kanister/pkg/kopia/command" @@ -315,9 +314,9 @@ func fetchRepositoryServer(ctx context.Context, cli kubernetes.Interface, crCli }, nil } -func getKopiaRepositoryCacheSize(rs *crv1alpha1.RepositoryServer) v1alpha1.CacheSizeSettings { +func getKopiaRepositoryCacheSize(rs *crv1alpha1.RepositoryServer) crv1alpha1.CacheSizeSettings { defaultContentCacheMB, defaultMetadataCacheMB := command.GetGeneralCacheSizeSettings() - cacheSizeSettings := v1alpha1.CacheSizeSettings{ + cacheSizeSettings := crv1alpha1.CacheSizeSettings{ Metadata: &defaultMetadataCacheMB, Content: &defaultContentCacheMB, } diff --git a/pkg/validatingwebhook/repositoryserver_handler.go b/pkg/validatingwebhook/repositoryserver_handler.go index 9c8a1a6fb3..16356d78fc 100644 --- a/pkg/validatingwebhook/repositoryserver_handler.go +++ b/pkg/validatingwebhook/repositoryserver_handler.go @@ -18,7 +18,7 @@ import ( "context" "fmt" - "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -38,8 +38,8 @@ func (r *RepositoryServerValidator) ValidateCreate(ctx context.Context, obj runt // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *RepositoryServerValidator) ValidateUpdate(ctx context.Context, old runtime.Object, new runtime.Object) error { - oldrs, ook := old.(*v1alpha1.RepositoryServer) - newrs, nok := new.(*v1alpha1.RepositoryServer) + oldrs, ook := old.(*crv1alpha1.RepositoryServer) + newrs, nok := new.(*crv1alpha1.RepositoryServer) if !ook || !nok { return errors.New("Either updated object or the old object is not of type RepositoryServer.cr.kanister.io") } From 612154bb003a637bd550f014798eca8b868ce831 Mon Sep 17 00:00:00 2001 From: Ankit Date: Wed, 29 Nov 2023 14:53:56 +0530 Subject: [PATCH 11/17] Apply linter to new changes --- pkg/progress/action.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/progress/action.go b/pkg/progress/action.go index 3cea9fcb41..9a0ac8d31a 100644 --- a/pkg/progress/action.go +++ b/pkg/progress/action.go @@ -186,7 +186,7 @@ func SetActionSetPercentCompleted(actionSet *crv1alpha1.ActionSet) error { totalPhases++ } } - actionProgress = actionProgress / totalPhases + actionProgress /= totalPhases // Update LastTransitionTime only if there is a change in action PercentCompleted if strconv.Itoa(actionProgress) == actionSet.Status.Progress.PercentCompleted { From 7a3945a8ddc69f8b23e3abfdabbbe14d5f5d4ec3 Mon Sep 17 00:00:00 2001 From: Ankit Date: Wed, 29 Nov 2023 16:11:25 +0530 Subject: [PATCH 12/17] Fix merge issues --- pkg/function/export_rds_snapshot_location.go | 15 ++++++++++- pkg/function/restore_rds_snapshot.go | 15 ++++++++++- pkg/function/scale_workload.go | 26 ++++++++++++-------- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/pkg/function/export_rds_snapshot_location.go b/pkg/function/export_rds_snapshot_location.go index 37be7c5a9d..3110f3e137 100644 --- a/pkg/function/export_rds_snapshot_location.go +++ b/pkg/function/export_rds_snapshot_location.go @@ -247,7 +247,20 @@ func (d *exportRDSSnapshotToLocationFunc) ExecutionProgress() (crv1alpha1.PhaseP }, nil } -func execDumpCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction, namespace, dbEndpoint, username, password string, databases []string, backupPrefix, backupID string, profile *param.Profile, dbEngineVersion string) (map[string]interface{}, error) { +func execDumpCommand( + ctx context.Context, + dbEngine RDSDBEngine, + action RDSAction, + namespace, + dbEndpoint, + username, + password string, + databases []string, + backupPrefix, + backupID string, + profile *param.Profile, + dbEngineVersion string, +) (map[string]interface{}, error) { // Trim "\n" from creds username = strings.TrimSpace(username) password = strings.TrimSpace(password) diff --git a/pkg/function/restore_rds_snapshot.go b/pkg/function/restore_rds_snapshot.go index a9e496cfec..c52099b17b 100644 --- a/pkg/function/restore_rds_snapshot.go +++ b/pkg/function/restore_rds_snapshot.go @@ -164,7 +164,20 @@ func (r *restoreRDSSnapshotFunc) ExecutionProgress() (crv1alpha1.PhaseProgress, }, nil } -func restoreRDSSnapshot(ctx context.Context, namespace, instanceID, subnetGroup, snapshotID, backupArtifactPrefix, backupID, username, password string, dbEngine RDSDBEngine, sgIDs []string, profile *param.Profile) (map[string]interface{}, error) { +func restoreRDSSnapshot( + ctx context.Context, + namespace, + instanceID, + subnetGroup, + snapshotID, + backupArtifactPrefix, + backupID, + username, + password string, + dbEngine RDSDBEngine, + sgIDs []string, + profile *param.Profile, +) (map[string]interface{}, error) { // Validate profile if err := ValidateProfile(profile); err != nil { return nil, errors.Wrap(err, "Error validating profile") diff --git a/pkg/function/scale_workload.go b/pkg/function/scale_workload.go index b28e19842c..9139057de7 100644 --- a/pkg/function/scale_workload.go +++ b/pkg/function/scale_workload.go @@ -63,9 +63,7 @@ func (s *scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, a s.progressPercent = progress.StartedPercent defer func() { s.progressPercent = progress.CompletedPercent }() - var namespace, kind, name string - var replicas int32 - namespace, kind, name, replicas, waitForReady, err := getArgs(tp, args) + scaleArgs, err := getArgs(tp, args) if err != nil { return nil, err } @@ -78,19 +76,19 @@ func (s *scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, a if err != nil { return nil, errors.Wrapf(err, "Failed to create Kubernetes client") } - switch strings.ToLower(scaleWorkloadArgs.kind) { + switch strings.ToLower(scaleArgs.kind) { case param.StatefulSetKind: - return nil, kube.ScaleStatefulSet(ctx, cli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) + return nil, kube.ScaleStatefulSet(ctx, cli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) case param.DeploymentKind: - return nil, kube.ScaleDeployment(ctx, cli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) + return nil, kube.ScaleDeployment(ctx, cli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) case param.DeploymentConfigKind: osCli, err := osversioned.NewForConfig(cfg) if err != nil { return nil, errors.Wrapf(err, "Failed to create OpenShift client") } - return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, scaleWorkloadArgs.namespace, scaleWorkloadArgs.name, scaleWorkloadArgs.replicas, scaleWorkloadArgs.waitForReady) + return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) } - return nil, errors.New("Workload type not supported " + scaleWorkloadArgs.kind) + return nil, errors.New("Workload type not supported " + scaleArgs.kind) } func (*scaleWorkloadFunc) RequiredArgs() []string { @@ -115,7 +113,15 @@ func (s *scaleWorkloadFunc) ExecutionProgress() (crv1alpha1.PhaseProgress, error }, nil } -func getArgs(tp param.TemplateParams, args map[string]interface{}) (namespace, kind, name string, replicas int32, waitForReady bool, err error) { +type scaleArgs struct { + namespace string + kind string + name string + replicas int32 + waitForReady bool +} + +func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleArgs, error) { var rep interface{} waitForReady := true err := Arg(args, ScaleWorkloadReplicas, &rep) @@ -180,7 +186,7 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (namespace, k if err != nil { return nil, err } - return &scaleWorkloadArgs{ + return &scaleArgs{ namespace: namespace, name: name, kind: kind, From d5227545e5a90c4951f083d99b8fdf33e377fdb6 Mon Sep 17 00:00:00 2001 From: Ankit Date: Mon, 4 Dec 2023 11:34:56 +0530 Subject: [PATCH 13/17] Add missing newlint --- .golangci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index e1847359c1..3259c19d13 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -59,4 +59,4 @@ linters-settings: - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 alias: metav1 - pkg: github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1 - alias: crv1alpha1 \ No newline at end of file + alias: crv1alpha1 From fded60ec87f82907fd0637b1859b2e2d1593d70a Mon Sep 17 00:00:00 2001 From: Ankit Date: Mon, 4 Dec 2023 17:43:24 +0530 Subject: [PATCH 14/17] Add explanation for ignoring dupl linter --- pkg/app/cockroachdb.go | 2 +- pkg/app/couchbase.go | 2 +- pkg/app/mariadb.go | 2 +- pkg/app/mysql.go | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/app/cockroachdb.go b/pkg/app/cockroachdb.go index cd967f3bd5..66fdec7496 100644 --- a/pkg/app/cockroachdb.go +++ b/pkg/app/cockroachdb.go @@ -57,7 +57,7 @@ func (c *CockroachDB) Init(context.Context) error { return err } -func (c *CockroachDB) Install(ctx context.Context, namespace string) error { //nolint:dupl +func (c *CockroachDB) Install(ctx context.Context, namespace string) error { //nolint:dupl // Not a duplicate, common code already extracted log.Info().Print("Installing cockroachdb cluster helm chart.", field.M{"app": c.name}) c.namespace = namespace diff --git a/pkg/app/couchbase.go b/pkg/app/couchbase.go index 0040e156ad..0f0ed3d16a 100644 --- a/pkg/app/couchbase.go +++ b/pkg/app/couchbase.go @@ -80,7 +80,7 @@ func (cb *CouchbaseDB) Init(ctx context.Context) error { return err } -func (cb *CouchbaseDB) Install(ctx context.Context, ns string) error { //nolint:dupl +func (cb *CouchbaseDB) Install(ctx context.Context, ns string) error { //nolint:dupl // Not a duplicate, common code already extracted log.Info().Print("Installing couchbase operator and cluster helm chart.", field.M{"app": cb.name}) cb.namespace = ns diff --git a/pkg/app/mariadb.go b/pkg/app/mariadb.go index f17bf18a9d..d76a6accbc 100644 --- a/pkg/app/mariadb.go +++ b/pkg/app/mariadb.go @@ -74,7 +74,7 @@ func (m *MariaDB) Init(context.Context) error { return nil } -func (m *MariaDB) Install(ctx context.Context, namespace string) error { //nolint:dupl +func (m *MariaDB) Install(ctx context.Context, namespace string) error { //nolint:dupl // Not a duplicate, common code already extracted m.namespace = namespace cli, err := helm.NewCliClient() if err != nil { diff --git a/pkg/app/mysql.go b/pkg/app/mysql.go index bba3260794..70dee51694 100644 --- a/pkg/app/mysql.go +++ b/pkg/app/mysql.go @@ -83,7 +83,7 @@ func (mdb *MysqlDB) Init(ctx context.Context) error { return nil } -func (mdb *MysqlDB) Install(ctx context.Context, namespace string) error { //nolint:dupl +func (mdb *MysqlDB) Install(ctx context.Context, namespace string) error { //nolint:dupl // Not a duplicate, common code already extracted mdb.namespace = namespace cli, err := helm.NewCliClient() if err != nil { From 5e97339c0cd8b12de2814510eac3a9855c07c6d8 Mon Sep 17 00:00:00 2001 From: Ankit Date: Mon, 18 Dec 2023 11:49:14 +0530 Subject: [PATCH 15/17] Address review comments --- pkg/function/scale_workload.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pkg/function/scale_workload.go b/pkg/function/scale_workload.go index 9139057de7..ba9c1dbb12 100644 --- a/pkg/function/scale_workload.go +++ b/pkg/function/scale_workload.go @@ -129,10 +129,8 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleArgs, return nil, err } - var ( - namespace, kind, name string - replicas int32 - ) + var namespace, kind, name string + var replicas int32 switch val := rep.(type) { case int: From da05972531b985f5e6472859ccc3988b460babba Mon Sep 17 00:00:00 2001 From: Ankit Date: Tue, 19 Dec 2023 10:43:30 +0530 Subject: [PATCH 16/17] Address review comments - move args --- pkg/function/scale_test.go | 13 ++++---- pkg/function/scale_workload.go | 56 ++++++++++++++++------------------ 2 files changed, 33 insertions(+), 36 deletions(-) diff --git a/pkg/function/scale_test.go b/pkg/function/scale_test.go index 887767e0ab..aef6f23821 100644 --- a/pkg/function/scale_test.go +++ b/pkg/function/scale_test.go @@ -315,15 +315,16 @@ func (s *ScaleSuite) TestGetArgs(c *C) { check: IsNil, }, } { - scaleWorkloadArgs, err := getArgs(tc.tp, tc.args) + s := scaleWorkloadFunc{} + err := s.setArgs(tc.tp, tc.args) c.Assert(err, tc.check) if err != nil { continue } - c.Assert(scaleWorkloadArgs.namespace, Equals, tc.wantNamespace) - c.Assert(scaleWorkloadArgs.name, Equals, tc.wantName) - c.Assert(scaleWorkloadArgs.kind, Equals, tc.wantKind) - c.Assert(scaleWorkloadArgs.replicas, Equals, tc.wantReplicas) - c.Assert(scaleWorkloadArgs.waitForReady, Equals, tc.wantWaitForReady) + c.Assert(s.namespace, Equals, tc.wantNamespace) + c.Assert(s.name, Equals, tc.wantName) + c.Assert(s.kind, Equals, tc.wantKind) + c.Assert(s.replicas, Equals, tc.wantReplicas) + c.Assert(s.waitForReady, Equals, tc.wantWaitForReady) } } diff --git a/pkg/function/scale_workload.go b/pkg/function/scale_workload.go index ba9c1dbb12..819e771759 100644 --- a/pkg/function/scale_workload.go +++ b/pkg/function/scale_workload.go @@ -52,6 +52,11 @@ var ( type scaleWorkloadFunc struct { progressPercent string + namespace string + kind string + name string + replicas int32 + waitForReady bool } func (*scaleWorkloadFunc) Name() string { @@ -63,7 +68,7 @@ func (s *scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, a s.progressPercent = progress.StartedPercent defer func() { s.progressPercent = progress.CompletedPercent }() - scaleArgs, err := getArgs(tp, args) + err := s.setArgs(tp, args) if err != nil { return nil, err } @@ -76,19 +81,19 @@ func (s *scaleWorkloadFunc) Exec(ctx context.Context, tp param.TemplateParams, a if err != nil { return nil, errors.Wrapf(err, "Failed to create Kubernetes client") } - switch strings.ToLower(scaleArgs.kind) { + switch strings.ToLower(s.kind) { case param.StatefulSetKind: - return nil, kube.ScaleStatefulSet(ctx, cli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) + return nil, kube.ScaleStatefulSet(ctx, cli, s.namespace, s.name, s.replicas, s.waitForReady) case param.DeploymentKind: - return nil, kube.ScaleDeployment(ctx, cli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) + return nil, kube.ScaleDeployment(ctx, cli, s.namespace, s.name, s.replicas, s.waitForReady) case param.DeploymentConfigKind: osCli, err := osversioned.NewForConfig(cfg) if err != nil { return nil, errors.Wrapf(err, "Failed to create OpenShift client") } - return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, scaleArgs.namespace, scaleArgs.name, scaleArgs.replicas, scaleArgs.waitForReady) + return nil, kube.ScaleDeploymentConfig(ctx, cli, osCli, s.namespace, s.name, s.replicas, s.waitForReady) } - return nil, errors.New("Workload type not supported " + scaleArgs.kind) + return nil, errors.New("Workload type not supported " + s.kind) } func (*scaleWorkloadFunc) RequiredArgs() []string { @@ -113,20 +118,12 @@ func (s *scaleWorkloadFunc) ExecutionProgress() (crv1alpha1.PhaseProgress, error }, nil } -type scaleArgs struct { - namespace string - kind string - name string - replicas int32 - waitForReady bool -} - -func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleArgs, error) { +func (s *scaleWorkloadFunc) setArgs(tp param.TemplateParams, args map[string]interface{}) error { var rep interface{} waitForReady := true err := Arg(args, ScaleWorkloadReplicas, &rep) if err != nil { - return nil, err + return err } var namespace, kind, name string @@ -142,11 +139,11 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleArgs, case string: var v int if v, err = strconv.Atoi(val); err != nil { - return nil, errors.Wrapf(err, "Cannot convert %s to int ", val) + return errors.Wrapf(err, "Cannot convert %s to int ", val) } replicas = int32(v) default: - return nil, errors.Errorf("Invalid arg type %T for Arg %s ", rep, ScaleWorkloadReplicas) + return errors.Errorf("Invalid arg type %T for Arg %s ", rep, ScaleWorkloadReplicas) } // Populate default values for optional arguments from template parameters switch { @@ -164,31 +161,30 @@ func getArgs(tp param.TemplateParams, args map[string]interface{}) (*scaleArgs, namespace = tp.DeploymentConfig.Namespace default: if !ArgExists(args, ScaleWorkloadNamespaceArg) || !ArgExists(args, ScaleWorkloadNameArg) || !ArgExists(args, ScaleWorkloadKindArg) { - return nil, errors.New("Workload information not available via defaults or namespace/name/kind parameters") + return errors.New("Workload information not available via defaults or namespace/name/kind parameters") } } err = OptArg(args, ScaleWorkloadNamespaceArg, &namespace, namespace) if err != nil { - return nil, err + return err } err = OptArg(args, ScaleWorkloadNameArg, &name, name) if err != nil { - return nil, err + return err } err = OptArg(args, ScaleWorkloadKindArg, &kind, kind) if err != nil { - return nil, err + return err } err = OptArg(args, ScaleWorkloadWaitArg, &waitForReady, waitForReady) if err != nil { - return nil, err + return err } - return &scaleArgs{ - namespace: namespace, - name: name, - kind: kind, - replicas: replicas, - waitForReady: waitForReady, - }, nil + s.kind = kind + s.name = name + s.namespace = namespace + s.replicas = replicas + s.waitForReady = waitForReady + return nil } From 446c4379fa8b67a3aa01a63106032f4f1d6199d6 Mon Sep 17 00:00:00 2001 From: Ankit Date: Tue, 19 Dec 2023 11:19:32 +0530 Subject: [PATCH 17/17] Temporarily disable depguard linter, lint fix --- .golangci.yml | 2 +- pkg/kopia/command/parse_command_output.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 65d7f5a57a..571f30eb08 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,7 +17,7 @@ linters: - lll - nakedret - asciicheck - - depguard + # - depguard # Disabling temporarily due to https://github.com/golangci/golangci-lint/issues/3906 - dogsled - dupl - exportloopref diff --git a/pkg/kopia/command/parse_command_output.go b/pkg/kopia/command/parse_command_output.go index bc0f93f466..0f510abd0d 100644 --- a/pkg/kopia/command/parse_command_output.go +++ b/pkg/kopia/command/parse_command_output.go @@ -58,7 +58,7 @@ func SnapshotIDsFromSnapshot(output string) (snapID, rootID string, err error) { if len(match) > 0 && len(match[0]) > 2 { snapID = match[0][2] rootID = match[0][1] - return + return snapID, rootID, nil } } return snapID, rootID, errors.New("Failed to find Root ID from output")