diff --git a/.github/workflows/e2e-test-kind.yaml b/.github/workflows/e2e-test-kind.yaml index 538ddbddc0..c38d7c2c40 100644 --- a/.github/workflows/e2e-test-kind.yaml +++ b/.github/workflows/e2e-test-kind.yaml @@ -10,6 +10,8 @@ jobs: # Build the Velero CLI and image once for all Kubernetes versions, and cache it so the fan-out workers can get it. build: runs-on: ubuntu-latest + outputs: + minio-dockerfile-sha: ${{ steps.minio-version.outputs.dockerfile_sha }} steps: - name: Check out the code uses: actions/checkout@v4 @@ -43,6 +45,26 @@ jobs: run: | IMAGE=velero VERSION=pr-test make container docker save velero:pr-test -o ./velero.tar + # Check and build MinIO image once for all e2e tests + - name: Check Bitnami MinIO Dockerfile version + id: minio-version + run: | + DOCKERFILE_SHA=$(curl -s https://api.github.com/repos/bitnami/containers/commits?path=bitnami/minio/2025/debian-12/Dockerfile\&per_page=1 | jq -r '.[0].sha') + echo "dockerfile_sha=${DOCKERFILE_SHA}" >> $GITHUB_OUTPUT + - name: Cache MinIO Image + uses: actions/cache@v4 + id: minio-cache + with: + path: ./minio-image.tar + key: minio-bitnami-${{ steps.minio-version.outputs.dockerfile_sha }} + - name: Build MinIO Image from Bitnami Dockerfile + if: steps.minio-cache.outputs.cache-hit != 'true' + run: | + echo "Building MinIO image from Bitnami Dockerfile..." + git clone --depth 1 https://github.com/bitnami/containers.git /tmp/bitnami-containers + cd /tmp/bitnami-containers/bitnami/minio/2025/debian-12 + docker build -t bitnami/minio:local . + docker save bitnami/minio:local > ${{ github.workspace }}/minio-image.tar # Run E2E test against all Kubernetes versions on kind run-e2e-test: needs: build @@ -71,9 +93,20 @@ jobs: uses: actions/setup-go@v5 with: go-version-file: 'go.mod' + # Fetch the pre-built MinIO image from the build job + - name: Fetch built MinIO Image + uses: actions/cache@v4 + id: minio-cache + with: + path: ./minio-image.tar + key: minio-bitnami-${{ needs.build.outputs.minio-dockerfile-sha }} + - name: Load MinIO Image + run: | + echo "Loading MinIO image..." + docker load < ./minio-image.tar - name: Install MinIO - run: - docker run -d --rm -p 9000:9000 -e "MINIO_ACCESS_KEY=minio" -e "MINIO_SECRET_KEY=minio123" -e "MINIO_DEFAULT_BUCKETS=bucket,additional-bucket" bitnami/minio:2021.6.17-debian-10-r7 + run: | + docker run -d --rm -p 9000:9000 -e "MINIO_ROOT_USER=minio" -e "MINIO_ROOT_PASSWORD=minio123" -e "MINIO_DEFAULT_BUCKETS=bucket,additional-bucket" bitnami/minio:local - uses: engineerd/setup-kind@v0.5.0 with: version: "v0.21.0" diff --git a/.golangci.yaml b/.golangci.yaml index 191187d9ee..93e7aa4fbd 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -27,7 +27,6 @@ run: # If false (default) - golangci-lint acquires file lock on start. allow-parallel-runners: false - # output configuration options output: # colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number" @@ -43,12 +42,23 @@ output: # all available settings of specific linters linters-settings: + + depguard: + rules: + main: + deny: + # specify an error message to output when a denylisted package is used + - pkg: github.com/sirupsen/logrus + desc: "logging is allowed only by logutils.Log" + dogsled: # checks assignments with too many blank identifiers; default is 2 max-blank-identifiers: 2 + dupl: # tokens count to trigger issue, 150 by default threshold: 100 + errcheck: # report about not checking of errors in type assertions: `a := b.(MyStruct)`; # default is false: such cases aren't reported by default. @@ -66,25 +76,31 @@ linters-settings: # path to a file containing a list of functions to exclude from checking # see https://github.com/kisielk/errcheck#excluding-functions for details # exclude: /path/to/file.txt + exhaustive: # indicates that switch statements are to be considered exhaustive if a # 'default' case is present, even if all enum members aren't listed in the # switch default-signifies-exhaustive: false + funlen: lines: 60 statements: 40 + gocognit: # minimal code complexity to report, 30 by default (but we recommend 10-20) min-complexity: 10 + nestif: # minimal complexity of if statements to report, 5 by default min-complexity: 4 + goconst: # minimal length of string constant, 3 by default min-len: 3 # minimal occurrences count to trigger, 3 by default min-occurrences: 5 + gocritic: # Which checks should be enabled; can't be combined with 'disabled-checks'; # See https://go-critic.github.io/overview#checks-overview @@ -109,9 +125,15 @@ linters-settings: paramsOnly: true # rangeValCopy: # sizeThreshold: 32 + gocyclo: # minimal code complexity to report, 30 by default (but we recommend 10-20) min-complexity: 10 + + godot: + # check all top-level comments, not only declarations + check-all: false + godox: # report any comments starting with keywords, this is useful for TODO or FIXME comments that # might be left in the code accidentally and should be resolved before merging @@ -119,38 +141,20 @@ linters-settings: - NOTE - OPTIMIZE # marks code that should be optimized before merging - HACK # marks hack-arounds that should be removed before merging + gofmt: # simplify code: gofmt with `-s` option, true by default simplify: true + goimports: # put imports beginning with prefix after 3rd-party packages; # it's a comma-separated list of prefixes local-prefixes: github.com/org/project - golint: - # minimal confidence for issues, default is 0.8 - min-confidence: 0.8 - gomnd: - # the list of enabled checks, see https://github.com/tommy-muehle/go-mnd/#checks for description. - checks: argument,case,condition,operation,return,assign - gomodguard: - allowed: - modules: # List of allowed modules - # - gopkg.in/yaml.v2 - domains: # List of allowed module domains - # - golang.org - blocked: - modules: # List of blocked modules - # - github.com/uudashr/go-module: # Blocked module - # recommendations: # Recommended modules that should be used instead (Optional) - # - golang.org/x/mod - # reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional) - versions: # List of blocked module version constraints - # - github.com/mitchellh/go-homedir: # Blocked module with version constraint - # version: "< 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons - # reason: "testing if blocked version constraint works." # Reason why the version constraint exists. (Optional) + gosec: excludes: - G115 + govet: # report about shadowed variables # check-shadowing: true @@ -171,23 +175,14 @@ linters-settings: disable: - shadow disable-all: false - depguard: - list-type: blacklist # Velero.io word list : ignore - include-go-root: false - packages: - - github.com/sirupsen/logrus - packages-with-error-message: - # specify an error message to output when a denylisted package is used - - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" + lll: # max line length, lines longer will be reported. Default is 120. # '\t' is counted as 1 character by default, and can be changed with the tab-width option line-length: 120 # tab width in spaces. Default to 1. tab-width: 1 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true + misspell: # Correct spellings using locale preferences for US or UK. # Default is to use a neutral variety of English. @@ -195,9 +190,11 @@ linters-settings: locale: US ignore-words: - someword + nakedret: # make an issue if func has more lines of code than this setting and it has naked returns; default is 30 max-func-lines: 30 + prealloc: # XXX: we don't recommend using this linter before doing performance profiling. # For most programs usage of prealloc will be a premature optimization. @@ -207,25 +204,74 @@ linters-settings: simple: true range-loops: true # Report preallocation suggestions on range loops, true by default for-loops: false # Report preallocation suggestions on for loops, false by default + nolintlint: # Enable to ensure that nolint directives are all used. Default is true. allow-unused: false - # Disable to ensure that nolint directives don't have a leading space. Default is true. - allow-leading-space: true # Exclude following linters from requiring an explanation. Default is []. allow-no-explanation: [] # Enable to require an explanation of nonzero length after each nolint directive. Default is false. require-explanation: true # Enable to require nolint directives to mention the specific linter being suppressed. Default is false. require-specific: true + + perfsprint: + strconcat: false + sprintf1: false + errorf: false + int-conversion: true + revive: rules: + - name: blank-imports + disabled: true + - name: context-as-argument + disabled: true + - name: context-keys-type + - name: dot-imports + disabled: true + - name: early-return + disabled: true + arguments: + - "preserveScope" + - name: empty-block + disabled: true + - name: error-naming + disabled: true + - name: error-return + disabled: true + - name: error-strings + disabled: true + - name: errorf + disabled: true + - name: increment-decrement + - name: indent-error-flow + disabled: true + - name: range + - name: receiver-naming + disabled: true + - name: redefines-builtin-id + disabled: true + - name: superfluous-else + disabled: true + arguments: + - "preserveScope" + - name: time-naming - name: unexported-return disabled: true + - name: unnecessary-stmt + - name: unreachable-code + - name: unused-parameter + disabled: true + - name: use-any + - name: var-declaration + - name: var-naming + disabled: true rowserrcheck: packages: - github.com/jmoiron/sqlx + testifylint: # TODO: enable them all disable: @@ -233,6 +279,7 @@ linters-settings: - float-compare - require-error enable-all: true + testpackage: # regexp pattern to skip files skip-regexp: (export|internal)_test\.go @@ -242,15 +289,11 @@ linters-settings: # if it's called for subdir of a project it can't find external interfaces. All text editor integrations # with golangci-lint call it on a directory with the changed file. check-exported: false - unused: - # treat code as a program (not a library) and report unused exported identifiers; default is false. - # XXX: if you enable this setting, unused will report a lot of false-positives in text editors: - # if it's called for subdir of a project it can't find funcs usages. All text editor integrations - # with golangci-lint call it on a directory with the changed file. - check-exported: false + whitespace: multi-if: false # Enforces newlines (or comments) after every multi-line if statement multi-func: false # Enforces newlines (or comments) after every multi-line function signature + wsl: # If true append is only allowed to be cuddled if appending value is # matching variables, fields or types on line above. Default is true. @@ -278,7 +321,7 @@ linters: - asciicheck - bidichk - bodyclose - # - copyloopvar + - copyloopvar - dogsled - durationcheck - dupword @@ -301,6 +344,7 @@ linters: - nilerr - noctx - nolintlint + - perfsprint - revive # - staticcheck - stylecheck @@ -314,17 +358,22 @@ linters: - whitespace fast: false - issues: - exclude-dirs-use-default: true - uniq-by-line: true + # which dirs to skip: issues from them won't be reported; + # can use regexp here: generated.*, regexp is applied on full path; + # default value is empty list, but default dirs are skipped independently + # from this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work + # on Windows. + exclude-dirs: + - pkg/plugin/generated/* + exclude-rules: - linters: - staticcheck text: "DefaultVolumesToRestic" # No need to report deprecate for DefaultVolumesToRestic. - path: ".*_test.go$" linters: - - dupword - errcheck - goconst - gosec @@ -335,7 +384,6 @@ issues: - unused - path: test/ linters: - - dupword - errcheck - goconst - gosec @@ -344,6 +392,14 @@ issues: - stylecheck - unparam - unused + - path: ".*data_upload_controller_test.go$" + linters: + - dupword + text: "type" + - path: ".*config_test.go$" + linters: + - dupword + text: "bucket" # The list of ids of default excludes to include or disable. By default it's empty. include: @@ -355,17 +411,8 @@ issues: # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. max-same-issues: 0 - # Show only new issues created after git revision `REV` - # new-from-rev: origin/main - - # which dirs to skip: issues from them won't be reported; - # can use regexp here: generated.*, regexp is applied on full path; - # default value is empty list, but default dirs are skipped independently - # from this option's value (see skip-dirs-use-default). - # "/" will be replaced by current OS file path separator to properly work - # on Windows. - exclude-dirs: - - pkg/plugin/generated/* + # make issues output unique by line, default is true + uniq-by-line: true severity: # Default value is empty string. diff --git a/hack/build-image/Dockerfile b/hack/build-image/Dockerfile index e1c615b62a..e32b412712 100644 --- a/hack/build-image/Dockerfile +++ b/hack/build-image/Dockerfile @@ -21,9 +21,10 @@ ENV GO111MODULE=on ENV GOPROXY=${GOPROXY} # kubebuilder test bundle is separated from kubebuilder. Need to setup it for CI test. -RUN curl -sSLo envtest-bins.tar.gz https://go.kubebuilder.io/test-tools/1.22.1/linux/$(go env GOARCH) && \ - mkdir /usr/local/kubebuilder && \ - tar -C /usr/local/kubebuilder --strip-components=1 -zvxf envtest-bins.tar.gz +# Use setup-envtest to download envtest binaries (GCS tarball URL is no longer valid). +RUN go install sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.0.0-20250308055145-5fe7bb3edc86 && \ + setup-envtest use --bin-dir /usr/local/kubebuilder/bin 1.31.x && \ + ln -sf /usr/local/kubebuilder/bin/k8s/1.31.*/* /usr/local/kubebuilder/bin/ RUN wget --quiet https://github.com/kubernetes-sigs/kubebuilder/releases/download/v3.2.0/kubebuilder_linux_$(go env GOARCH) && \ mv kubebuilder_linux_$(go env GOARCH) /usr/local/kubebuilder/bin/kubebuilder && \ diff --git a/internal/delete/actions/csi/volumesnapshot_action.go b/internal/delete/actions/csi/volumesnapshot_action.go index bc6d9a2be8..73f60b06e2 100644 --- a/internal/delete/actions/csi/volumesnapshot_action.go +++ b/internal/delete/actions/csi/volumesnapshot_action.go @@ -106,7 +106,7 @@ func (p *volumeSnapshotDeleteItemAction) Execute( } func NewVolumeSnapshotDeleteItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, errors.WithStack(err) diff --git a/internal/delete/actions/csi/volumesnapshotcontent_action.go b/internal/delete/actions/csi/volumesnapshotcontent_action.go index 0ff0bb68db..a3e76437a9 100644 --- a/internal/delete/actions/csi/volumesnapshotcontent_action.go +++ b/internal/delete/actions/csi/volumesnapshotcontent_action.go @@ -112,7 +112,7 @@ func (p *volumeSnapshotContentDeleteItemAction) Execute( func NewVolumeSnapshotContentDeleteItemAction( f client.Factory, ) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, err diff --git a/internal/delete/delete_item_action_handler_test.go b/internal/delete/delete_item_action_handler_test.go index 8bd1206020..a71de864d4 100644 --- a/internal/delete/delete_item_action_handler_test.go +++ b/internal/delete/delete_item_action_handler_test.go @@ -230,7 +230,7 @@ func (h *harness) addResource(t *testing.T, resource *test.APIResource) { } // recordResourcesAction is a delete item action that can be configured to run -// for specific resources/namespaces and simply record the items that is is +// for specific resources/namespaces and simply record the items that is // executed for. type recordResourcesAction struct { selector velero.ResourceSelector diff --git a/internal/hook/wait_exec_hook_handler.go b/internal/hook/wait_exec_hook_handler.go index 5c68816375..9e090a9227 100644 --- a/internal/hook/wait_exec_hook_handler.go +++ b/internal/hook/wait_exec_hook_handler.go @@ -116,7 +116,7 @@ func (e *DefaultWaitExecHookHandler) HandleHooks( // not yet been observed to be running. It relies on the Informer not to be called concurrently. // When a container is observed running and its hooks are executed, the container is deleted // from the byContainer map. When the map is empty the watch is ended. - handler := func(newObj interface{}) { + handler := func(newObj any) { newPod, ok := newObj.(*v1.Pod) if !ok { return @@ -217,10 +217,10 @@ func (e *DefaultWaitExecHookHandler) HandleHooks( _, podWatcher := cache.NewInformer(lw, pod, 0, cache.ResourceEventHandlerFuncs{ AddFunc: handler, - UpdateFunc: func(_, newObj interface{}) { + UpdateFunc: func(_, newObj any) { handler(newObj) }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { err := fmt.Errorf("pod %s deleted before all hooks were executed", kube.NamespaceAndName(pod)) log.Error(err) cancel() diff --git a/internal/resourcemodifiers/resource_modifiers_test.go b/internal/resourcemodifiers/resource_modifiers_test.go index d6aad99fc8..5ecd3bc0e4 100644 --- a/internal/resourcemodifiers/resource_modifiers_test.go +++ b/internal/resourcemodifiers/resource_modifiers_test.go @@ -429,69 +429,69 @@ func TestGetResourceModifiersFromConfig(t *testing.T) { func TestResourceModifiers_ApplyResourceModifierRules(t *testing.T) { pvcStandardSc := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "PersistentVolumeClaim", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-pvc", "namespace": "foo", }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "storageClassName": "standard", }, }, } pvcPremiumSc := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "PersistentVolumeClaim", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-pvc", "namespace": "foo", }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "storageClassName": "premium", }, }, } pvcGoldSc := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "PersistentVolumeClaim", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-pvc", "namespace": "foo", }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "storageClassName": "gold", }, }, } deployNginxOneReplica := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "apps/v1", "kind": "Deployment", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-deployment", "namespace": "foo", - "labels": map[string]interface{}{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "replicas": int64(1), - "template": map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": map[string]interface{}{ + "template": map[string]any{ + "metadata": map[string]any{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ - "containers": []interface{}{ - map[string]interface{}{ + "spec": map[string]any{ + "containers": []any{ + map[string]any{ "name": "nginx", "image": "nginx:latest", }, @@ -502,27 +502,27 @@ func TestResourceModifiers_ApplyResourceModifierRules(t *testing.T) { }, } deployNginxTwoReplica := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "apps/v1", "kind": "Deployment", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-deployment", "namespace": "foo", - "labels": map[string]interface{}{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "replicas": int64(2), - "template": map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": map[string]interface{}{ + "template": map[string]any{ + "metadata": map[string]any{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ - "containers": []interface{}{ - map[string]interface{}{ + "spec": map[string]any{ + "containers": []any{ + map[string]any{ "name": "nginx", "image": "nginx:latest", }, @@ -533,31 +533,31 @@ func TestResourceModifiers_ApplyResourceModifierRules(t *testing.T) { }, } deployNginxMysql := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "apps/v1", "kind": "Deployment", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-deployment", "namespace": "foo", - "labels": map[string]interface{}{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "replicas": int64(1), - "template": map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": map[string]interface{}{ + "template": map[string]any{ + "metadata": map[string]any{ + "labels": map[string]any{ "app": "nginx", }, }, - "spec": map[string]interface{}{ - "containers": []interface{}{ - map[string]interface{}{ + "spec": map[string]any{ + "containers": []any{ + map[string]any{ "name": "nginx", "image": "nginx:latest", }, - map[string]interface{}{ + map[string]any{ "name": "mysql", "image": "mysql:latest", }, @@ -568,19 +568,19 @@ func TestResourceModifiers_ApplyResourceModifierRules(t *testing.T) { }, } cmTrue := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "ConfigMap", - "data": map[string]interface{}{ + "data": map[string]any{ "test": "true", }, }, } cmFalse := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "v1", "kind": "ConfigMap", - "data": map[string]interface{}{ + "data": map[string]any{ "test": "false", }, }, diff --git a/internal/resourcemodifiers/strategic_merge_patch.go b/internal/resourcemodifiers/strategic_merge_patch.go index 8d3fe4c511..380ff3ad46 100644 --- a/internal/resourcemodifiers/strategic_merge_patch.go +++ b/internal/resourcemodifiers/strategic_merge_patch.go @@ -53,7 +53,7 @@ func (p *StrategicMergePatcher) Patch(u *unstructured.Unstructured, _ logrus.Fie // strategicPatchObject applies a strategic merge patch of `patchBytes` to // `originalObject` and stores the result in `objToUpdate`. -// It additionally returns the map[string]interface{} representation of the +// It additionally returns the map[string]any representation of the // `originalObject` and `patchBytes`. // NOTE: Both `originalObject` and `objToUpdate` are supposed to be versioned. func strategicPatchObject( @@ -67,7 +67,7 @@ func strategicPatchObject( return err } - patchMap := make(map[string]interface{}) + patchMap := make(map[string]any) var strictErrs []error strictErrs, err = kubejson.UnmarshalStrict(patchBytes, &patchMap) if err != nil { @@ -84,8 +84,8 @@ func strategicPatchObject( // and stores the result in . // NOTE: must be a versioned object. func applyPatchToObject( - originalMap map[string]interface{}, - patchMap map[string]interface{}, + originalMap map[string]any, + patchMap map[string]any, objToUpdate runtime.Object, schemaReferenceObj runtime.Object, strictErrs []error, @@ -117,14 +117,9 @@ func applyPatchToObject( }) } } else if len(strictErrs) > 0 { - switch { - //case validationDirective == metav1.FieldValidationWarn: - // addStrictDecodingWarnings(requestContext, strictErrs) - default: - return apierrors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ - field.Invalid(field.NewPath("patch"), fmt.Sprintf("%+v", patchMap), runtime.NewStrictDecodingError(strictErrs).Error()), - }) - } + return apierrors.NewInvalid(schema.GroupKind{}, "", field.ErrorList{ + field.Invalid(field.NewPath("patch"), fmt.Sprintf("%+v", patchMap), runtime.NewStrictDecodingError(strictErrs).Error()), + }) } return nil diff --git a/internal/resourcepolicies/resource_policies.go b/internal/resourcepolicies/resource_policies.go index 40f3fae24d..532c8722d0 100644 --- a/internal/resourcepolicies/resource_policies.go +++ b/internal/resourcepolicies/resource_policies.go @@ -46,14 +46,14 @@ type Action struct { // Type defined specific type of action, currently only support 'skip' Type VolumeActionType `yaml:"type"` // Parameters defined map of parameters when executing a specific action - Parameters map[string]interface{} `yaml:"parameters,omitempty"` + Parameters map[string]any `yaml:"parameters,omitempty"` } // volumePolicy defined policy to conditions to match Volumes and related action to handle matched Volumes type VolumePolicy struct { // Conditions defined list of conditions to match Volumes - Conditions map[string]interface{} `yaml:"conditions"` - Action Action `yaml:"action"` + Conditions map[string]any `yaml:"conditions"` + Action Action `yaml:"action"` } // resourcePolicies currently defined slice of volume policies to handle backup @@ -122,7 +122,7 @@ func (p *Policies) match(res *structuredVolume) *Action { return nil } -func (p *Policies) GetMatchAction(res interface{}) (*Action, error) { +func (p *Policies) GetMatchAction(res any) (*Action, error) { volume := &structuredVolume{} switch obj := res.(type) { case *v1.PersistentVolume: diff --git a/internal/resourcepolicies/resource_policies_test.go b/internal/resourcepolicies/resource_policies_test.go index 4fd705731e..3d80768659 100644 --- a/internal/resourcepolicies/resource_policies_test.go +++ b/internal/resourcepolicies/resource_policies_test.go @@ -126,32 +126,32 @@ func TestGetResourceMatchedAction(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, }, { Action: Action{Type: "snapshot"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "10,100Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, }, { Action: Action{Type: "fs-backup"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -241,7 +241,7 @@ func TestGetResourcePoliciesFromConfig(t *testing.T) { Version: "v1", VolumePolicies: []VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", }, Action: Action{ diff --git a/internal/resourcepolicies/volume_resources.go b/internal/resourcepolicies/volume_resources.go index fd1b8182ac..2101205a41 100644 --- a/internal/resourcepolicies/volume_resources.go +++ b/internal/resourcepolicies/volume_resources.go @@ -208,9 +208,9 @@ func (c *capacity) isInRange(y resource.Quantity) bool { return false } -// unmarshalVolConditions parse map[string]interface{} into volumeConditions format +// unmarshalVolConditions parse map[string]any into volumeConditions format // and validate key fields of the map. -func unmarshalVolConditions(con map[string]interface{}) (*volumeConditions, error) { +func unmarshalVolConditions(con map[string]any) (*volumeConditions, error) { volConditons := &volumeConditions{} buffer := new(bytes.Buffer) err := yaml.NewEncoder(buffer).Encode(con) diff --git a/internal/resourcepolicies/volume_resources_test.go b/internal/resourcepolicies/volume_resources_test.go index 4d5d7a743a..1bd5e1e7f3 100644 --- a/internal/resourcepolicies/volume_resources_test.go +++ b/internal/resourcepolicies/volume_resources_test.go @@ -48,7 +48,7 @@ func TestParseCapacity(t *testing.T) { } for _, test := range tests { - test := test // capture range variable + // capture range variable t.Run(test.input, func(t *testing.T) { actual, actualErr := parseCapacity(test.input) if test.expected != emptyCapacity { @@ -79,7 +79,7 @@ func TestCapacityIsInRange(t *testing.T) { } for _, test := range tests { - test := test // capture range variable + // capture range variable t.Run(fmt.Sprintf("%v with %v", test.capacity, test.quantity), func(t *testing.T) { t.Parallel() @@ -232,12 +232,12 @@ func TestCSIConditionMatch(t *testing.T) { func TestUnmarshalVolumeConditions(t *testing.T) { testCases := []struct { name string - input map[string]interface{} + input map[string]any expectedError string }{ { name: "Valid input", - input: map[string]interface{}{ + input: map[string]any{ "capacity": "1Gi,10Gi", "storageClass": []string{ "gp2", @@ -251,28 +251,28 @@ func TestUnmarshalVolumeConditions(t *testing.T) { }, { name: "Invalid input: invalid capacity filed name", - input: map[string]interface{}{ + input: map[string]any{ "Capacity": "1Gi,10Gi", }, expectedError: "field Capacity not found", }, { name: "Invalid input: invalid storage class format", - input: map[string]interface{}{ + input: map[string]any{ "storageClass": "ebs-sc", }, expectedError: "str `ebs-sc` into []string", }, { name: "Invalid input: invalid csi format", - input: map[string]interface{}{ + input: map[string]any{ "csi": "csi.driver", }, expectedError: "str `csi.driver` into resourcepolicies.csiVolumeSource", }, { name: "Invalid input: unknown field", - input: map[string]interface{}{ + input: map[string]any{ "unknown": "foo", }, expectedError: "field unknown not found in type", diff --git a/internal/resourcepolicies/volume_resources_validator.go b/internal/resourcepolicies/volume_resources_validator.go index cf9a40c0fc..915ea30c8d 100644 --- a/internal/resourcepolicies/volume_resources_validator.go +++ b/internal/resourcepolicies/volume_resources_validator.go @@ -73,7 +73,7 @@ func (c *csiCondition) validate() error { } // decodeStruct restric validate the keys in decoded mappings to exist as fields in the struct being decoded into -func decodeStruct(r io.Reader, s interface{}) error { +func decodeStruct(r io.Reader, s any) error { dec := yaml.NewDecoder(r) dec.KnownFields(true) return dec.Decode(s) diff --git a/internal/resourcepolicies/volume_resources_validator_test.go b/internal/resourcepolicies/volume_resources_validator_test.go index 1cbc6d7325..c04ae0f0f6 100644 --- a/internal/resourcepolicies/volume_resources_validator_test.go +++ b/internal/resourcepolicies/volume_resources_validator_test.go @@ -94,12 +94,12 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "unknown": "", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -115,11 +115,11 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "10Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -135,11 +135,11 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": "ebs-sc", - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -155,7 +155,7 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, "csi": "aws.efs.csi.driver", @@ -172,10 +172,10 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -191,10 +191,10 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "unsupported"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), }, @@ -210,7 +210,7 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, "nfs": "aws.efs.csi.driver", @@ -227,15 +227,15 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "skip"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), - "nfs": interface{}( - map[string]interface{}{ + "nfs": any( + map[string]any{ "server": "192.168.20.90", "path": "/mnt/data/", }), @@ -252,15 +252,15 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "snapshot"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), - "nfs": interface{}( - map[string]interface{}{ + "nfs": any( + map[string]any{ "server": "192.168.20.90", "path": "/mnt/data/", }), @@ -277,15 +277,15 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: "fs-backup"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "capacity": "0,10Gi", "storageClass": []string{"gp2", "ebs-sc"}, - "csi": interface{}( - map[string]interface{}{ + "csi": any( + map[string]any{ "driver": "aws.efs.csi.driver", }), - "nfs": interface{}( - map[string]interface{}{ + "nfs": any( + map[string]any{ "server": "192.168.20.90", "path": "/mnt/data/", }), @@ -302,15 +302,15 @@ func TestValidate(t *testing.T) { VolumePolicies: []VolumePolicy{ { Action: Action{Type: Snapshot}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2"}, }, }, { Action: Action{Type: FSBackup}, - Conditions: map[string]interface{}{ - "nfs": interface{}( - map[string]interface{}{ + Conditions: map[string]any{ + "nfs": any( + map[string]any{ "server": "192.168.20.90", "path": "/mnt/data/", }), diff --git a/internal/restartabletest/restartable_delegate.go b/internal/restartabletest/restartable_delegate.go index e97d5fc7c0..d9308572e0 100644 --- a/internal/restartabletest/restartable_delegate.go +++ b/internal/restartabletest/restartable_delegate.go @@ -46,7 +46,7 @@ func (rp *MockRestartableProcess) ResetIfNeeded() error { return args.Error(0) } -func (rp *MockRestartableProcess) GetByKindAndName(key process.KindAndName) (interface{}, error) { +func (rp *MockRestartableProcess) GetByKindAndName(key process.KindAndName) (any, error) { args := rp.Called(key) return args.Get(0), args.Error(1) } @@ -57,21 +57,21 @@ func (rp *MockRestartableProcess) Stop() { type RestartableDelegateTest struct { Function string - Inputs []interface{} - ExpectedErrorOutputs []interface{} - ExpectedDelegateOutputs []interface{} + Inputs []any + ExpectedErrorOutputs []any + ExpectedDelegateOutputs []any } type Mockable interface { Test(t mock.TestingT) - On(method string, args ...interface{}) *mock.Call + On(method string, args ...any) *mock.Call AssertExpectations(t mock.TestingT) bool } func RunRestartableDelegateTests( t *testing.T, kind common.PluginKind, - newRestartable func(key process.KindAndName, p process.RestartableProcess) interface{}, + newRestartable func(key process.KindAndName, p process.RestartableProcess) any, newMock func() Mockable, tests ...RestartableDelegateTest, ) { @@ -92,7 +92,7 @@ func RunRestartableDelegateTests( method := reflect.ValueOf(r).MethodByName(tc.Function) require.NotEmpty(t, method) - // Convert the test case inputs ([]interface{}) to []reflect.Value + // Convert the test case inputs ([]any) to []reflect.Value var inputValues []reflect.Value for i := range tc.Inputs { inputValues = append(inputValues, reflect.ValueOf(tc.Inputs[i])) @@ -102,7 +102,7 @@ func RunRestartableDelegateTests( actual := method.Call(inputValues) // This Function asserts that the actual outputs match the expected outputs - checkOutputs := func(expected []interface{}, actual []reflect.Value) { + checkOutputs := func(expected []any, actual []reflect.Value) { require.Equal(t, len(expected), len(actual)) for i := range actual { diff --git a/internal/volume/volumes_information.go b/internal/volume/volumes_information.go index 7d793425c4..516407241d 100644 --- a/internal/volume/volumes_information.go +++ b/internal/volume/volumes_information.go @@ -836,7 +836,7 @@ func (t *RestoreVolumeInfoTracker) Result() []*RestoreVolumeInfo { continue } pvcNS, pvcName := n[0], n[1] - var restoreSize int64 = 0 + var restoreSize int64 if csiSnapshot.Status != nil && csiSnapshot.Status.RestoreSize != nil { restoreSize = csiSnapshot.Status.RestoreSize.Value() } diff --git a/internal/volumehelper/volume_policy_helper.go b/internal/volumehelper/volume_policy_helper.go index 5d39972729..b0315d6c50 100644 --- a/internal/volumehelper/volume_policy_helper.go +++ b/internal/volumehelper/volume_policy_helper.go @@ -143,7 +143,7 @@ func (v volumeHelperImpl) ShouldPerformFSBackup(volume corev1api.Volume, pod cor } if v.volumePolicy != nil { - var resource interface{} + var resource any resource = &volume if volume.VolumeSource.PersistentVolumeClaim != nil { pvc, err := kubeutil.GetPVCForPodVolume(&volume, &pod, v.client) diff --git a/internal/volumehelper/volume_policy_helper_test.go b/internal/volumehelper/volume_policy_helper_test.go index 375825e22e..4c6db87b99 100644 --- a/internal/volumehelper/volume_policy_helper_test.go +++ b/internal/volumehelper/volume_policy_helper_test.go @@ -57,7 +57,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -78,7 +78,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -99,7 +99,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -121,7 +121,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -152,7 +152,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -186,7 +186,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -220,7 +220,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -253,7 +253,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -314,7 +314,7 @@ func TestVolumeHelperImpl_ShouldPerformSnapshot(t *testing.T) { fakeClient.Create(context.Background(), tc.pod) } - var p *resourcepolicies.Policies = nil + var p *resourcepolicies.Policies if tc.resourcePolicies != nil { p = &resourcepolicies.Policies{} err := p.BuildPolicy(tc.resourcePolicies) @@ -465,7 +465,7 @@ func TestVolumeHelperImpl_ShouldIncludeVolumeInBackup(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -540,7 +540,7 @@ func TestVolumeHelperImpl_ShouldPerformFSBackup(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -566,7 +566,7 @@ func TestVolumeHelperImpl_ShouldPerformFSBackup(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "volumeTypes": []string{"emptyDir"}, }, Action: resourcepolicies.Action{ @@ -600,7 +600,7 @@ func TestVolumeHelperImpl_ShouldPerformFSBackup(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2-csi"}, }, Action: resourcepolicies.Action{ @@ -635,7 +635,7 @@ func TestVolumeHelperImpl_ShouldPerformFSBackup(t *testing.T) { Version: "v1", VolumePolicies: []resourcepolicies.VolumePolicy{ { - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp3-csi"}, }, Action: resourcepolicies.Action{ @@ -679,7 +679,7 @@ func TestVolumeHelperImpl_ShouldPerformFSBackup(t *testing.T) { fakeClient.Create(context.Background(), tc.pod) } - var p *resourcepolicies.Policies = nil + var p *resourcepolicies.Policies if tc.resourcePolicies != nil { p = &resourcepolicies.Policies{} err := p.BuildPolicy(tc.resourcePolicies) diff --git a/pkg/backup/actions/backup_pv_action_test.go b/pkg/backup/actions/backup_pv_action_test.go index b66021132d..e2c19f14aa 100644 --- a/pkg/backup/actions/backup_pv_action_test.go +++ b/pkg/backup/actions/backup_pv_action_test.go @@ -36,9 +36,9 @@ import ( func TestBackupPVAction(t *testing.T) { pvc := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "spec": map[string]interface{}{}, - "status": map[string]interface{}{}, + Object: map[string]any{ + "spec": map[string]any{}, + "status": map[string]any{}, }, } @@ -54,7 +54,7 @@ func TestBackupPVAction(t *testing.T) { // empty spec.volumeName should result in no error // and no additional items - pvc.Object["spec"].(map[string]interface{})["volumeName"] = "" + pvc.Object["spec"].(map[string]any)["volumeName"] = "" _, additional, err = a.Execute(pvc, backup) assert.NoError(t, err) assert.Empty(t, additional) @@ -116,28 +116,28 @@ func TestBackupPVAction(t *testing.T) { // non-empty spec.volumeName when status.phase is empty // should result in no error and no additional items - pvc.Object["spec"].(map[string]interface{})["volumeName"] = "myVolume" + pvc.Object["spec"].(map[string]any)["volumeName"] = "myVolume" _, additional, err = a.Execute(pvc, backup) require.NoError(t, err) require.Empty(t, additional) // non-empty spec.volumeName when status.phase is 'Pending' // should result in no error and no additional items - pvc.Object["status"].(map[string]interface{})["phase"] = corev1api.ClaimPending + pvc.Object["status"].(map[string]any)["phase"] = corev1api.ClaimPending _, additional, err = a.Execute(pvc, backup) require.NoError(t, err) require.Empty(t, additional) // non-empty spec.volumeName when status.phase is 'Lost' // should result in no error and no additional items - pvc.Object["status"].(map[string]interface{})["phase"] = corev1api.ClaimLost + pvc.Object["status"].(map[string]any)["phase"] = corev1api.ClaimLost _, additional, err = a.Execute(pvc, backup) require.NoError(t, err) require.Empty(t, additional) // non-empty spec.volumeName when status.phase is 'Bound' // should result in no error and one additional item for the PV - pvc.Object["status"].(map[string]interface{})["phase"] = corev1api.ClaimBound + pvc.Object["status"].(map[string]any)["phase"] = corev1api.ClaimBound _, additional, err = a.Execute(pvc, backup) require.NoError(t, err) require.Len(t, additional, 1) @@ -145,7 +145,7 @@ func TestBackupPVAction(t *testing.T) { // empty spec.volumeName when status.phase is 'Bound' should // result in no error and no additional items - pvc.Object["spec"].(map[string]interface{})["volumeName"] = "" + pvc.Object["spec"].(map[string]any)["volumeName"] = "" _, additional, err = a.Execute(pvc, backup) assert.NoError(t, err) assert.Empty(t, additional) diff --git a/pkg/backup/actions/csi/pvc_action.go b/pkg/backup/actions/csi/pvc_action.go index a078a23089..ffe31d90ac 100644 --- a/pkg/backup/actions/csi/pvc_action.go +++ b/pkg/backup/actions/csi/pvc_action.go @@ -19,6 +19,7 @@ package csi import ( "context" "fmt" + "strconv" snapshotv1api "github.com/kubernetes-csi/external-snapshotter/client/v7/apis/volumesnapshot/v1" "github.com/pkg/errors" @@ -484,9 +485,7 @@ func newDataUpload( if backup.Spec.UploaderConfig != nil && backup.Spec.UploaderConfig.ParallelFilesUpload > 0 { dataUpload.Spec.DataMoverConfig = make(map[string]string) - dataUpload.Spec.DataMoverConfig[uploaderUtil.ParallelFilesUpload] = fmt.Sprintf( - "%d", backup.Spec.UploaderConfig.ParallelFilesUpload, - ) + dataUpload.Spec.DataMoverConfig[uploaderUtil.ParallelFilesUpload] = strconv.Itoa(backup.Spec.UploaderConfig.ParallelFilesUpload) } return dataUpload @@ -553,7 +552,7 @@ func cancelDataUpload( } func NewPvcBackupItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, errors.WithStack(err) diff --git a/pkg/backup/actions/csi/volumesnapshot_action.go b/pkg/backup/actions/csi/volumesnapshot_action.go index 8be46ea40c..728280fb86 100644 --- a/pkg/backup/actions/csi/volumesnapshot_action.go +++ b/pkg/backup/actions/csi/volumesnapshot_action.go @@ -372,7 +372,7 @@ func (p *volumeSnapshotBackupItemAction) Cancel( func NewVolumeSnapshotBackupItemAction( f client.Factory, ) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, errors.WithStack(err) diff --git a/pkg/backup/actions/csi/volumesnapshotclass_action.go b/pkg/backup/actions/csi/volumesnapshotclass_action.go index f67c5d718a..83b2b1c795 100644 --- a/pkg/backup/actions/csi/volumesnapshotclass_action.go +++ b/pkg/backup/actions/csi/volumesnapshotclass_action.go @@ -119,6 +119,6 @@ func (p *volumeSnapshotClassBackupItemAction) Cancel( // NewVolumeSnapshotClassBackupItemAction returns a // VolumeSnapshotClassBackupItemAction instance. -func NewVolumeSnapshotClassBackupItemAction(logger logrus.FieldLogger) (interface{}, error) { +func NewVolumeSnapshotClassBackupItemAction(logger logrus.FieldLogger) (any, error) { return &volumeSnapshotClassBackupItemAction{log: logger}, nil } diff --git a/pkg/backup/actions/csi/volumesnapshotcontent_action.go b/pkg/backup/actions/csi/volumesnapshotcontent_action.go index f40f0787dd..ccdcc9df00 100644 --- a/pkg/backup/actions/csi/volumesnapshotcontent_action.go +++ b/pkg/backup/actions/csi/volumesnapshotcontent_action.go @@ -136,6 +136,6 @@ func (p *volumeSnapshotContentBackupItemAction) Cancel( // VolumeSnapshotContentBackupItemAction instance. func NewVolumeSnapshotContentBackupItemAction( logger logrus.FieldLogger, -) (interface{}, error) { +) (any, error) { return &volumeSnapshotContentBackupItemAction{log: logger}, nil } diff --git a/pkg/backup/actions/remap_crd_version_action_test.go b/pkg/backup/actions/remap_crd_version_action_test.go index f5bf5542db..cd7296be18 100644 --- a/pkg/backup/actions/remap_crd_version_action_test.go +++ b/pkg/backup/actions/remap_crd_version_action_test.go @@ -208,7 +208,7 @@ func TestRemapCRDVersionActionData(t *testing.T) { // For ElasticSearch and Kibana, problems manifested when additionalPrinterColumns was moved from the top-level spec down to the // versions slice. if test.expectAdditionalColumns { - _, ok := item.UnstructuredContent()["spec"].(map[string]interface{})["additionalPrinterColumns"] + _, ok := item.UnstructuredContent()["spec"].(map[string]any)["additionalPrinterColumns"] assert.True(t, ok) } diff --git a/pkg/backup/backup.go b/pkg/backup/backup.go index fb4fe8f496..e8befe3775 100644 --- a/pkg/backup/backup.go +++ b/pkg/backup/backup.go @@ -338,7 +338,7 @@ func (kb *kubernetesBackupper) BackupWithResolvers( } backupRequest.Status.Progress = &velerov1api.BackupProgress{TotalItems: len(items)} - var resourcePolicy *resourcepolicies.Policies = nil + var resourcePolicy *resourcepolicies.Policies if backupRequest.ResPolicies != nil { resourcePolicy = backupRequest.ResPolicies } @@ -432,7 +432,7 @@ func (kb *kubernetesBackupper) BackupWithResolvers( var itemBlock *BackupItemBlock for i := range items { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "progress": "", "resource": items[i].groupResource.String(), "namespace": items[i].namespace, @@ -492,7 +492,7 @@ func (kb *kubernetesBackupper) BackupWithResolvers( itemsBackedUp: len(backupRequest.BackedUpItems), } - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "progress": "", "resource": items[i].groupResource.String(), "namespace": items[i].namespace, @@ -959,7 +959,7 @@ func (kb *kubernetesBackupper) FinalizeBackup( unstructuredDataUploads := make([]unstructured.Unstructured, 0) for i, item := range items { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "progress": "", "resource": item.groupResource.String(), "namespace": item.namespace, @@ -1001,7 +1001,7 @@ func (kb *kubernetesBackupper) FinalizeBackup( // how many items we know of that are remaining" totalItems := len(backupRequest.BackedUpItems) + (len(items) - (i + 1)) - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "progress": "", "resource": item.groupResource.String(), "namespace": item.namespace, diff --git a/pkg/backup/backup_test.go b/pkg/backup/backup_test.go index fef91d4b0c..752b0186ee 100644 --- a/pkg/backup/backup_test.go +++ b/pkg/backup/backup_test.go @@ -1355,7 +1355,7 @@ func TestBackupItemActionsForSkippedPV(t *testing.T) { VolumePolicies: []resourcepolicies.VolumePolicy{ { Action: resourcepolicies.Action{Type: "snapshot"}, - Conditions: map[string]interface{}{ + Conditions: map[string]any{ "storageClass": []string{"gp2"}, }, }, @@ -1837,7 +1837,7 @@ func TestBackupActionModifications(t *testing.T) { }, actions: []biav2.BackupItemAction{ modifyingActionGetter(func(item *unstructured.Unstructured) { - item.Object["spec"].(map[string]interface{})["nodeName"] = "foo" + item.Object["spec"].(map[string]any)["nodeName"] = "foo" }), }, want: map[string]unstructuredObject{ @@ -4249,7 +4249,7 @@ func defaultBackup() *builder.BackupBuilder { return builder.ForBackup(velerov1.DefaultNamespace, "backup-1").DefaultVolumesToFsBackup(false) } -func toUnstructuredOrFail(t *testing.T, obj interface{}) map[string]interface{} { +func toUnstructuredOrFail(t *testing.T, obj any) map[string]any { t.Helper() res, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) @@ -4285,7 +4285,7 @@ func assertTarballContents(t *testing.T, backupFile io.Reader, items ...string) } // unstructuredObject is a type alias to improve readability. -type unstructuredObject map[string]interface{} +type unstructuredObject map[string]any // assertTarballFileContents verifies that the gzipped tarball stored in the provided // backupFile contains the files specified as keys in 'want', and for each of those diff --git a/pkg/backup/item_backupper.go b/pkg/backup/item_backupper.go index 374a319666..01a7444fdf 100644 --- a/pkg/backup/item_backupper.go +++ b/pkg/backup/item_backupper.go @@ -159,7 +159,7 @@ func (ib *itemBackupper) backupItemInternal(logger logrus.FieldLogger, obj runti namespace := metadata.GetNamespace() name := metadata.GetName() - log := logger.WithFields(map[string]interface{}{ + log := logger.WithFields(map[string]any{ "name": name, "resource": groupResource.String(), "namespace": namespace, @@ -218,7 +218,7 @@ func (ib *itemBackupper) backupItemInternal(logger logrus.FieldLogger, obj runti ib.podVolumeSnapshotTracker.Track(pod, volume.Name) if found, pvcName := ib.podVolumeSnapshotTracker.TakenForPodVolume(pod, volume.Name); found { - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "podVolume": volume, "pvcName": pvcName, }).Info("Pod volume uses a persistent volume claim which has already been backed up from another pod, skipping.") diff --git a/pkg/client/config.go b/pkg/client/config.go index 7546a0ac4c..687c303e7b 100644 --- a/pkg/client/config.go +++ b/pkg/client/config.go @@ -33,9 +33,9 @@ const ( ConfigKeyColorized = "colorized" ) -// VeleroConfig is a map of strings to interface{} for deserializing Velero client config options. +// VeleroConfig is a map of strings to any for deserializing Velero client config options. // The alias is a way to attach type-asserting convenience methods. -type VeleroConfig map[string]interface{} +type VeleroConfig map[string]any // LoadConfig loads the Velero client configuration file and returns it as a VeleroConfig. If the // file does not exist, an empty map is returned. diff --git a/pkg/client/factory_test.go b/pkg/client/factory_test.go index 316808c327..e7ca1d153f 100644 --- a/pkg/client/factory_test.go +++ b/pkg/client/factory_test.go @@ -36,14 +36,14 @@ func TestFactory(t *testing.T) { // Env variable should set the namespace if no config or argument are used os.Setenv("VELERO_NAMESPACE", "env-velero") - f := NewFactory("velero", make(map[string]interface{})) + f := NewFactory("velero", make(map[string]any)) assert.Equal(t, "env-velero", f.Namespace()) os.Unsetenv("VELERO_NAMESPACE") // Argument should change the namespace - f = NewFactory("velero", make(map[string]interface{})) + f = NewFactory("velero", make(map[string]any)) s := "flag-velero" flags := new(flag.FlagSet) @@ -55,7 +55,7 @@ func TestFactory(t *testing.T) { // An argument overrides the env variable if both are set. os.Setenv("VELERO_NAMESPACE", "env-velero") - f = NewFactory("velero", make(map[string]interface{})) + f = NewFactory("velero", make(map[string]any)) flags = new(flag.FlagSet) f.BindFlags(flags) diff --git a/pkg/cmd/cli/backup/create.go b/pkg/cmd/cli/backup/create.go index fc98ad17cf..c104786360 100644 --- a/pkg/cmd/cli/backup/create.go +++ b/pkg/cmd/cli/backup/create.go @@ -254,7 +254,7 @@ func (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error { backupInformer := cache.NewSharedInformer(&lw, &velerov1api.Backup{}, time.Second) _, _ = backupInformer.AddEventHandler( cache.FilteringResourceEventHandler{ - FilterFunc: func(obj interface{}) bool { + FilterFunc: func(obj any) bool { backup, ok := obj.(*velerov1api.Backup) if !ok { @@ -263,14 +263,14 @@ func (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error { return backup.Name == o.Name }, Handler: cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { backup, ok := obj.(*velerov1api.Backup) if !ok { return } updates <- backup }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { backup, ok := obj.(*velerov1api.Backup) if !ok { return diff --git a/pkg/cmd/cli/backup/create_test.go b/pkg/cmd/cli/backup/create_test.go index 640e5380ad..33f2912147 100644 --- a/pkg/cmd/cli/backup/create_test.go +++ b/pkg/cmd/cli/backup/create_test.go @@ -19,6 +19,7 @@ package backup import ( "context" "fmt" + "strconv" "strings" "testing" "time" @@ -211,7 +212,7 @@ func TestCreateCommand(t *testing.T) { flags.Parse([]string{"--default-volumes-to-fs-backup", defaultVolumesToFsBackup}) flags.Parse([]string{"--resource-policies-configmap", resPoliciesConfigmap}) flags.Parse([]string{"--data-mover", dataMover}) - flags.Parse([]string{"--parallel-files-upload", fmt.Sprintf("%d", parallelFilesUpload)}) + flags.Parse([]string{"--parallel-files-upload", strconv.Itoa(parallelFilesUpload)}) //flags.Parse([]string{"--wait"}) client := velerotest.NewFakeControllerRuntimeClient(t).(kbclient.WithWatch) diff --git a/pkg/cmd/cli/datamover/data_mover_test.go b/pkg/cmd/cli/datamover/data_mover_test.go index 51d9376d31..206ba36eef 100644 --- a/pkg/cmd/cli/datamover/data_mover_test.go +++ b/pkg/cmd/cli/datamover/data_mover_test.go @@ -56,7 +56,7 @@ func TestExitWithMessage(t *testing.T) { name string message string succeed bool - args []interface{} + args []any createErr error writeFail bool expectedExitCode int @@ -77,7 +77,7 @@ func TestExitWithMessage(t *testing.T) { { name: "not succeed", message: "fake-message-1, arg-1 %s, arg-2 %v, arg-3 %v", - args: []interface{}{ + args: []any{ "arg-1-1", 10, false, @@ -88,7 +88,7 @@ func TestExitWithMessage(t *testing.T) { { name: "not succeed", message: "fake-message-2, arg-1 %s, arg-2 %v, arg-3 %v", - args: []interface{}{ + args: []any{ "arg-1-2", 20, true, diff --git a/pkg/cmd/cli/restore/create.go b/pkg/cmd/cli/restore/create.go index 6d4b25f0ab..78a396ee3f 100644 --- a/pkg/cmd/cli/restore/create.go +++ b/pkg/cmd/cli/restore/create.go @@ -53,7 +53,7 @@ func NewCreateCommand(f client.Factory, use string) *cobra.Command { # Create a restore with a default name ("backup-1-") from backup "backup-1". velero restore create --from-backup backup-1 - + # Create a restore from the latest successful backup triggered by schedule "schedule-1". velero restore create --from-schedule schedule-1 @@ -296,7 +296,7 @@ func (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error { } } - var resModifiers *corev1.TypedLocalObjectReference = nil + var resModifiers *corev1.TypedLocalObjectReference if o.ResourceModifierConfigMap != "" { resModifiers = &corev1.TypedLocalObjectReference{ @@ -365,7 +365,7 @@ func (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error { _, _ = restoreInformer.AddEventHandler( cache.FilteringResourceEventHandler{ - FilterFunc: func(obj interface{}) bool { + FilterFunc: func(obj any) bool { restore, ok := obj.(*api.Restore) if !ok { return false @@ -373,14 +373,14 @@ func (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error { return restore.Name == o.RestoreName }, Handler: cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { restore, ok := obj.(*api.Restore) if !ok { return } updates <- restore }, - DeleteFunc: func(obj interface{}) { + DeleteFunc: func(obj any) { restore, ok := obj.(*api.Restore) if !ok { return diff --git a/pkg/cmd/const.go b/pkg/cmd/const.go index 7f44598997..a5434e04e8 100644 --- a/pkg/cmd/const.go +++ b/pkg/cmd/const.go @@ -1,3 +1,3 @@ package cmd -var TRUE string = "true" +var TRUE = "true" diff --git a/pkg/cmd/errors.go b/pkg/cmd/errors.go index 2ba4420a81..4f374c8aff 100644 --- a/pkg/cmd/errors.go +++ b/pkg/cmd/errors.go @@ -34,7 +34,7 @@ func CheckError(err error) { } // Exit prints msg (with optional args), plus a newline, to stderr and exits with code 1. -func Exit(msg string, args ...interface{}) { +func Exit(msg string, args ...any) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) } diff --git a/pkg/cmd/server/plugin/plugin.go b/pkg/cmd/server/plugin/plugin.go index 3688ea3544..a9bd344210 100644 --- a/pkg/cmd/server/plugin/plugin.go +++ b/pkg/cmd/server/plugin/plugin.go @@ -208,16 +208,16 @@ func NewCommand(f client.Factory) *cobra.Command { return c } -func newPVBackupItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newPVBackupItemAction(logger logrus.FieldLogger) (any, error) { return bia.NewPVCAction(logger), nil } -func newPodBackupItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newPodBackupItemAction(logger logrus.FieldLogger) (any, error) { return bia.NewPodAction(logger), nil } func newServiceAccountBackupItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { // TODO(ncdc): consider a k8s style WantsKubernetesClientSet initialization approach clientset, err := f.KubeClient() if err != nil { @@ -242,7 +242,7 @@ func newServiceAccountBackupItemAction(f client.Factory) plugincommon.HandlerIni } func newRemapCRDVersionAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { config, err := f.ClientConfig() if err != nil { return nil, err @@ -266,20 +266,20 @@ func newRemapCRDVersionAction(f client.Factory) plugincommon.HandlerInitializer } } -func newJobRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newJobRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewJobAction(logger), nil } -func newPodRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newPodRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewPodAction(logger), nil } -func newInitRestoreHookPodAction(logger logrus.FieldLogger) (interface{}, error) { +func newInitRestoreHookPodAction(logger logrus.FieldLogger) (any, error) { return ria.NewInitRestoreHookPodAction(logger), nil } func newPodVolumeRestoreItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubeClient() if err != nil { return nil, err @@ -294,28 +294,28 @@ func newPodVolumeRestoreItemAction(f client.Factory) plugincommon.HandlerInitial } } -func newServiceRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newServiceRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewServiceAction(logger), nil } -func newServiceAccountRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newServiceAccountRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewServiceAccountAction(logger), nil } -func newAddPVCFromPodRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newAddPVCFromPodRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewAddPVCFromPodAction(logger), nil } -func newAddPVFromPVCRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newAddPVFromPVCRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewAddPVFromPVCAction(logger), nil } -func newCRDV1PreserveUnknownFieldsItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newCRDV1PreserveUnknownFieldsItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewCRDV1PreserveUnknownFieldsAction(logger), nil } func newChangeStorageClassRestoreItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubeClient() if err != nil { return nil, err @@ -330,7 +330,7 @@ func newChangeStorageClassRestoreItemAction(f client.Factory) plugincommon.Handl } func newChangeImageNameRestoreItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubeClient() if err != nil { return nil, err @@ -342,16 +342,16 @@ func newChangeImageNameRestoreItemAction(f client.Factory) plugincommon.HandlerI ), nil } } -func newRoleBindingItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newRoleBindingItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewRoleBindingAction(logger), nil } -func newClusterRoleBindingItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newClusterRoleBindingItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewClusterRoleBindingAction(logger), nil } func newChangePVCNodeSelectorItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubeClient() if err != nil { return nil, err @@ -365,16 +365,16 @@ func newChangePVCNodeSelectorItemAction(f client.Factory) plugincommon.HandlerIn } } -func newAPIServiceRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newAPIServiceRestoreItemAction(logger logrus.FieldLogger) (any, error) { return ria.NewAPIServiceAction(logger), nil } -func newAdmissionWebhookConfigurationAction(logger logrus.FieldLogger) (interface{}, error) { +func newAdmissionWebhookConfigurationAction(logger logrus.FieldLogger) (any, error) { return ria.NewAdmissionWebhookConfigurationAction(logger), nil } func newSecretRestoreItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubebuilderClient() if err != nil { return nil, err @@ -384,7 +384,7 @@ func newSecretRestoreItemAction(f client.Factory) plugincommon.HandlerInitialize } func newDataUploadRetrieveAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubebuilderClient() if err != nil { return nil, err @@ -395,7 +395,7 @@ func newDataUploadRetrieveAction(f client.Factory) plugincommon.HandlerInitializ } func newDateUploadDeleteItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { client, err := f.KubebuilderClient() if err != nil { return nil, err @@ -416,11 +416,11 @@ func newVolumeSnapshotBackupItemAction(f client.Factory) plugincommon.HandlerIni return csibia.NewVolumeSnapshotBackupItemAction(f) } -func newVolumeSnapshotContentBackupItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newVolumeSnapshotContentBackupItemAction(logger logrus.FieldLogger) (any, error) { return csibia.NewVolumeSnapshotContentBackupItemAction(logger) } -func newVolumeSnapshotClassBackupItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newVolumeSnapshotClassBackupItemAction(logger logrus.FieldLogger) (any, error) { return csibia.NewVolumeSnapshotClassBackupItemAction(logger) } @@ -444,11 +444,11 @@ func newVolumeSnapshotRestoreItemAction(f client.Factory) plugincommon.HandlerIn return csiria.NewVolumeSnapshotRestoreItemAction(f) } -func newVolumeSnapshotContentRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newVolumeSnapshotContentRestoreItemAction(logger logrus.FieldLogger) (any, error) { return csiria.NewVolumeSnapshotContentRestoreItemAction(logger) } -func newVolumeSnapshotClassRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newVolumeSnapshotClassRestoreItemAction(logger logrus.FieldLogger) (any, error) { return csiria.NewVolumeSnapshotClassRestoreItemAction(logger) } @@ -458,12 +458,12 @@ func newPVCItemBlockAction(f client.Factory) plugincommon.HandlerInitializer { return iba.NewPVCAction(f) } -func newPodItemBlockAction(logger logrus.FieldLogger) (interface{}, error) { +func newPodItemBlockAction(logger logrus.FieldLogger) (any, error) { return iba.NewPodAction(logger), nil } func newServiceAccountItemBlockAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { // TODO(ncdc): consider a k8s style WantsKubernetesClientSet initialization approach clientset, err := f.KubeClient() if err != nil { diff --git a/pkg/cmd/test/const.go b/pkg/cmd/test/const.go index 0c07fe0fa4..6490bb0f65 100644 --- a/pkg/cmd/test/const.go +++ b/pkg/cmd/test/const.go @@ -1,4 +1,4 @@ package test -var VeleroNameSpace string = "velero-test" -var CaptureFlag string = "CAPTRUE-OUTPUT" +var VeleroNameSpace = "velero-test" +var CaptureFlag = "CAPTRUE-OUTPUT" diff --git a/pkg/cmd/util/output/backup_structured_describer.go b/pkg/cmd/util/output/backup_structured_describer.go index 63bfbbd5ba..2065b669c5 100644 --- a/pkg/cmd/util/output/backup_structured_describer.go +++ b/pkg/cmd/util/output/backup_structured_describer.go @@ -74,11 +74,11 @@ func DescribeBackupInSF( // DescribeBackupSpecInSF describes a backup spec in structured format. func DescribeBackupSpecInSF(d *StructuredDescriber, spec velerov1api.BackupSpec) { - backupSpecInfo := make(map[string]interface{}) + backupSpecInfo := make(map[string]any) var s string // describe namespaces - namespaceInfo := make(map[string]interface{}) + namespaceInfo := make(map[string]any) if len(spec.IncludedNamespaces) == 0 { s = "*" } else { @@ -140,10 +140,10 @@ func DescribeBackupSpecInSF(d *StructuredDescriber, spec velerov1api.BackupSpec) backupSpecInfo["CSISnapshotTimeout"] = spec.CSISnapshotTimeout.Duration.String() // describe hooks - hooksInfo := make(map[string]interface{}) - hooksResources := make(map[string]interface{}) + hooksInfo := make(map[string]any) + hooksResources := make(map[string]any) for _, backupResourceHookSpec := range spec.Hooks.Resources { - ResourceDetails := make(map[string]interface{}) + ResourceDetails := make(map[string]any) var s string namespaceInfo := make(map[string]string) if len(backupResourceHookSpec.IncludedNamespaces) == 0 { @@ -181,10 +181,10 @@ func DescribeBackupSpecInSF(d *StructuredDescriber, spec velerov1api.BackupSpec) } ResourceDetails["labelSelector"] = s - preHooks := make([]map[string]interface{}, 0) + preHooks := make([]map[string]any, 0) for _, hook := range backupResourceHookSpec.PreHooks { if hook.Exec != nil { - preExecHook := make(map[string]interface{}) + preExecHook := make(map[string]any) preExecHook["container"] = hook.Exec.Container preExecHook["command"] = strings.Join(hook.Exec.Command, " ") preExecHook["onError:"] = hook.Exec.OnError @@ -194,10 +194,10 @@ func DescribeBackupSpecInSF(d *StructuredDescriber, spec velerov1api.BackupSpec) } ResourceDetails["preExecHook"] = preHooks - postHooks := make([]map[string]interface{}, 0) + postHooks := make([]map[string]any, 0) for _, hook := range backupResourceHookSpec.PostHooks { if hook.Exec != nil { - postExecHook := make(map[string]interface{}) + postExecHook := make(map[string]any) postExecHook["container"] = hook.Exec.Container postExecHook["command"] = strings.Join(hook.Exec.Command, " ") postExecHook["onError:"] = hook.Exec.OnError @@ -225,7 +225,7 @@ func DescribeBackupSpecInSF(d *StructuredDescriber, spec velerov1api.BackupSpec) func DescribeBackupStatusInSF(ctx context.Context, kbClient kbclient.Client, d *StructuredDescriber, backup *velerov1api.Backup, details bool, insecureSkipTLSVerify bool, caCertPath string, podVolumeBackups []velerov1api.PodVolumeBackup) { status := backup.Status - backupStatusInfo := make(map[string]interface{}) + backupStatusInfo := make(map[string]any) // Status.Version has been deprecated, use Status.FormatVersion backupStatusInfo["backupFormatVersion"] = status.FormatVersion @@ -271,7 +271,7 @@ func DescribeBackupStatusInSF(ctx context.Context, kbClient kbclient.Client, d * } } -func describeBackupResourceListInSF(ctx context.Context, kbClient kbclient.Client, backupStatusInfo map[string]interface{}, backup *velerov1api.Backup, insecureSkipTLSVerify bool, caCertPath string) { +func describeBackupResourceListInSF(ctx context.Context, kbClient kbclient.Client, backupStatusInfo map[string]any, backup *velerov1api.Backup, insecureSkipTLSVerify bool, caCertPath string) { // In consideration of decoding structured output conveniently, the two separate fields were created here(in func describeBackupResourceList, there is only one field describing either error message or resource list) // the field of 'errorGettingResourceList' gives specific error message when it fails to get resources list // the field of 'resourceList' lists the rearranged resources @@ -299,8 +299,8 @@ func describeBackupResourceListInSF(ctx context.Context, kbClient kbclient.Clien } func describeBackupVolumesInSF(ctx context.Context, kbClient kbclient.Client, backup *velerov1api.Backup, details bool, - insecureSkipTLSVerify bool, caCertPath string, podVolumeBackupCRs []velerov1api.PodVolumeBackup, backupStatusInfo map[string]interface{}) { - backupVolumes := make(map[string]interface{}) + insecureSkipTLSVerify bool, caCertPath string, podVolumeBackupCRs []velerov1api.PodVolumeBackup, backupStatusInfo map[string]any) { + backupVolumes := make(map[string]any) nativeSnapshots := []*volume.BackupVolumeInfo{} csiSnapshots := []*volume.BackupVolumeInfo{} @@ -351,20 +351,20 @@ func describeBackupVolumesInSF(ctx context.Context, kbClient kbclient.Client, ba backupStatusInfo["backupVolumes"] = backupVolumes } -func describeNativeSnapshotsInSF(details bool, infos []*volume.BackupVolumeInfo, backupVolumes map[string]interface{}) { +func describeNativeSnapshotsInSF(details bool, infos []*volume.BackupVolumeInfo, backupVolumes map[string]any) { if len(infos) == 0 { backupVolumes["nativeSnapshots"] = "" return } - snapshotDetails := make(map[string]interface{}) + snapshotDetails := make(map[string]any) for _, info := range infos { describNativeSnapshotInSF(details, info, snapshotDetails) } backupVolumes["nativeSnapshots"] = snapshotDetails } -func describNativeSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetails map[string]interface{}) { +func describNativeSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetails map[string]any) { if details { snapshotInfo := make(map[string]string) snapshotInfo["snapshotID"] = info.NativeSnapshotInfo.SnapshotHandle @@ -379,7 +379,7 @@ func describNativeSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snap } } -func describeCSISnapshotsInSF(details bool, infos []*volume.BackupVolumeInfo, backupVolumes map[string]interface{}, legacyInfoSource bool) { +func describeCSISnapshotsInSF(details bool, infos []*volume.BackupVolumeInfo, backupVolumes map[string]any, legacyInfoSource bool) { if len(infos) == 0 { if legacyInfoSource { backupVolumes["csiSnapshots"] = "" @@ -389,15 +389,15 @@ func describeCSISnapshotsInSF(details bool, infos []*volume.BackupVolumeInfo, ba return } - snapshotDetails := make(map[string]interface{}) + snapshotDetails := make(map[string]any) for _, info := range infos { describeCSISnapshotInSF(details, info, snapshotDetails) } backupVolumes["csiSnapshots"] = snapshotDetails } -func describeCSISnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetails map[string]interface{}) { - snapshotDetail := make(map[string]interface{}) +func describeCSISnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetails map[string]any) { + snapshotDetail := make(map[string]any) describeLocalSnapshotInSF(details, info, snapshotDetail) describeDataMovementInSF(details, info, snapshotDetail) @@ -406,13 +406,13 @@ func describeCSISnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapsh } // describeLocalSnapshotInSF describes CSI volume snapshot contents in structured format. -func describeLocalSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetail map[string]interface{}) { +func describeLocalSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetail map[string]any) { if !info.PreserveLocalSnapshot { return } if details { - localSnapshot := make(map[string]interface{}) + localSnapshot := make(map[string]any) if !info.SnapshotDataMoved { localSnapshot["operationID"] = info.CSISnapshotInfo.OperationID @@ -430,13 +430,13 @@ func describeLocalSnapshotInSF(details bool, info *volume.BackupVolumeInfo, snap } } -func describeDataMovementInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetail map[string]interface{}) { +func describeDataMovementInSF(details bool, info *volume.BackupVolumeInfo, snapshotDetail map[string]any) { if !info.SnapshotDataMoved { return } if details { - dataMovement := make(map[string]interface{}) + dataMovement := make(map[string]any) dataMovement["operationID"] = info.SnapshotDataMovementInfo.OperationID dataMover := "velero" @@ -456,14 +456,14 @@ func describeDataMovementInSF(details bool, info *volume.BackupVolumeInfo, snaps // DescribeDeleteBackupRequestsInSF describes delete backup requests in structured format. func DescribeDeleteBackupRequestsInSF(d *StructuredDescriber, requests []velerov1api.DeleteBackupRequest) { - deletionAttempts := make(map[string]interface{}) + deletionAttempts := make(map[string]any) if count := failedDeletionCount(requests); count > 0 { deletionAttempts["failed"] = count } - deletionRequests := make([]map[string]interface{}, 0) + deletionRequests := make([]map[string]any, 0) for _, req := range requests { - deletionReq := make(map[string]interface{}) + deletionReq := make(map[string]any) deletionReq["creationTimestamp"] = req.CreationTimestamp.String() deletionReq["phase"] = req.Status.Phase @@ -477,8 +477,8 @@ func DescribeDeleteBackupRequestsInSF(d *StructuredDescriber, requests []velerov } // describePodVolumeBackupsInSF describes pod volume backups in structured format. -func describePodVolumeBackupsInSF(backups []velerov1api.PodVolumeBackup, details bool, backupVolumes map[string]interface{}) { - podVolumeBackupsInfo := make(map[string]interface{}) +func describePodVolumeBackupsInSF(backups []velerov1api.PodVolumeBackup, details bool, backupVolumes map[string]any) { + podVolumeBackupsInfo := make(map[string]any) // Get the type of pod volume uploader. Since the uploader only comes from a single source, we can // take the uploader type from the first element of the array. var uploaderType string @@ -491,7 +491,7 @@ func describePodVolumeBackupsInSF(backups []velerov1api.PodVolumeBackup, details // type display the type of pod volume backups podVolumeBackupsInfo["uploderType"] = uploaderType - podVolumeBackupsDetails := make(map[string]interface{}) + podVolumeBackupsDetails := make(map[string]any) // separate backups by phase (combining and New into a single group) backupsByPhase := groupByPhase(backups) @@ -537,7 +537,7 @@ func DescribeBackupResultsInSF(ctx context.Context, kbClient kbclient.Client, d var buf bytes.Buffer var resultMap map[string]results.Result - errors, warnings := make(map[string]interface{}), make(map[string]interface{}) + errors, warnings := make(map[string]any), make(map[string]any) defer func() { d.Describe("errors", errors) d.Describe("warnings", warnings) @@ -572,13 +572,13 @@ func DescribeBackupResultsInSF(ctx context.Context, kbClient kbclient.Client, d // DescribeResourcePoliciesInSF describes resource policies in structured format. func DescribeResourcePoliciesInSF(d *StructuredDescriber, resPolicies *v1.TypedLocalObjectReference) { - policiesInfo := make(map[string]interface{}) + policiesInfo := make(map[string]any) policiesInfo["type"] = resPolicies.Kind policiesInfo["name"] = resPolicies.Name d.Describe("resourcePolicies", policiesInfo) } -func describeResultInSF(m map[string]interface{}, result results.Result) { +func describeResultInSF(m map[string]any, result results.Result) { m["velero"], m["cluster"], m["namespace"] = []string{}, []string{}, []string{} if len(result.Velero) > 0 { diff --git a/pkg/cmd/util/output/backup_structured_describer_test.go b/pkg/cmd/util/output/backup_structured_describer_test.go index 1ac32830c2..c635836ce8 100644 --- a/pkg/cmd/util/output/backup_structured_describer_test.go +++ b/pkg/cmd/util/output/backup_structured_describer_test.go @@ -33,7 +33,7 @@ import ( func TestDescribeBackupInSF(t *testing.T) { sd := &StructuredDescriber{ - output: make(map[string]interface{}), + output: make(map[string]any), format: "", } backupBuilder1 := builder.ForBackup("test-ns", "test-backup") @@ -75,9 +75,9 @@ func TestDescribeBackupInSF(t *testing.T) { }, }) - expect1 := map[string]interface{}{ - "spec": map[string]interface{}{ - "namespaces": map[string]interface{}{ + expect1 := map[string]any{ + "spec": map[string]any{ + "namespaces": map[string]any{ "included": "inc-ns-1, inc-ns-2", "excluded": "exc-ns-1, exc-ns-2", }, @@ -93,15 +93,15 @@ func TestDescribeBackupInSF(t *testing.T) { "TTL": "72h0m0s", "CSISnapshotTimeout": "10m0s", "veleroSnapshotMoveData": "auto", - "hooks": map[string]interface{}{ - "resources": map[string]interface{}{ - "hook-1": map[string]interface{}{ + "hooks": map[string]any{ + "resources": map[string]any{ + "hook-1": map[string]any{ "labelSelector": emptyDisplay, "namespaces": map[string]string{ "included": "hook-inc-ns-1, hook-inc-ns-2", "excluded": "hook-exc-ns-1, hook-exc-ns-2", }, - "preExecHook": []map[string]interface{}{ + "preExecHook": []map[string]any{ { "container": "hook-container-1", "command": "pre", @@ -109,7 +109,7 @@ func TestDescribeBackupInSF(t *testing.T) { "timeout": "0s", }, }, - "postExecHook": []map[string]interface{}{ + "postExecHook": []map[string]any{ { "container": "hook-container-1", "command": "post", @@ -160,9 +160,9 @@ func TestDescribeBackupInSF(t *testing.T) { }, }) - expect2 := map[string]interface{}{ - "spec": map[string]interface{}{ - "namespaces": map[string]interface{}{ + expect2 := map[string]any{ + "spec": map[string]any{ + "namespaces": map[string]any{ "included": "*", "excluded": emptyDisplay, }, @@ -178,15 +178,15 @@ func TestDescribeBackupInSF(t *testing.T) { "TTL": "0s", "CSISnapshotTimeout": "0s", "veleroSnapshotMoveData": "auto", - "hooks": map[string]interface{}{ - "resources": map[string]interface{}{ - "hook-1": map[string]interface{}{ + "hooks": map[string]any{ + "resources": map[string]any{ + "hook-1": map[string]any{ "labelSelector": emptyDisplay, "namespaces": map[string]string{ "included": "*", "excluded": emptyDisplay, }, - "preExecHook": []map[string]interface{}{ + "preExecHook": []map[string]any{ { "container": "hook-container-1", "command": "pre", @@ -194,7 +194,7 @@ func TestDescribeBackupInSF(t *testing.T) { "timeout": "0s", }, }, - "postExecHook": []map[string]interface{}{ + "postExecHook": []map[string]any{ { "container": "hook-container-1", "command": "post", @@ -244,21 +244,21 @@ func TestDescribePodVolumeBackupsInSF(t *testing.T) { name string inputPVBList []velerov1api.PodVolumeBackup inputDetails bool - expect map[string]interface{} + expect map[string]any }{ { name: "empty list", inputPVBList: []velerov1api.PodVolumeBackup{}, inputDetails: false, - expect: map[string]interface{}{"podVolumeBackups": ""}, + expect: map[string]any{"podVolumeBackups": ""}, }, { name: "2 completed pvbs", inputPVBList: []velerov1api.PodVolumeBackup{*pvb1, *pvb2}, inputDetails: true, - expect: map[string]interface{}{ - "podVolumeBackups": map[string]interface{}{ - "podVolumeBackupsDetails": map[string]interface{}{ + expect: map[string]any{ + "podVolumeBackups": map[string]any{ + "podVolumeBackupsDetails": map[string]any{ "Completed": []map[string]string{ {"pod-ns-1/pod-1": "vol-1"}, {"pod-ns-1/pod-2": "vol-2"}, @@ -271,7 +271,7 @@ func TestDescribePodVolumeBackupsInSF(t *testing.T) { } for _, tc := range testcases { t.Run(tc.name, func(tt *testing.T) { - output := make(map[string]interface{}) + output := make(map[string]any) describePodVolumeBackupsInSF(tc.inputPVBList, tc.inputDetails, output) assert.True(tt, reflect.DeepEqual(output, tc.expect)) }) @@ -283,7 +283,7 @@ func TestDescribeNativeSnapshotsInSF(t *testing.T) { name string volumeInfo []*volume.BackupVolumeInfo inputDetails bool - expect map[string]interface{} + expect map[string]any }{ { name: "no details", @@ -299,8 +299,8 @@ func TestDescribeNativeSnapshotsInSF(t *testing.T) { }, }, }, - expect: map[string]interface{}{ - "nativeSnapshots": map[string]interface{}{ + expect: map[string]any{ + "nativeSnapshots": map[string]any{ "pv-1": "specify --details for more information", }, }, @@ -321,8 +321,8 @@ func TestDescribeNativeSnapshotsInSF(t *testing.T) { }, }, inputDetails: true, - expect: map[string]interface{}{ - "nativeSnapshots": map[string]interface{}{ + expect: map[string]any{ + "nativeSnapshots": map[string]any{ "pv-1": map[string]string{ "snapshotID": "snapshot-1", "type": "ebs", @@ -337,7 +337,7 @@ func TestDescribeNativeSnapshotsInSF(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(tt *testing.T) { - output := make(map[string]interface{}) + output := make(map[string]any) describeNativeSnapshotsInSF(tc.inputDetails, tc.volumeInfo, output) assert.True(tt, reflect.DeepEqual(output, tc.expect)) }) @@ -349,13 +349,13 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { name string volumeInfo []*volume.BackupVolumeInfo inputDetails bool - expect map[string]interface{} + expect map[string]any legacyInfoSource bool }{ { name: "empty info, not legacy", volumeInfo: []*volume.BackupVolumeInfo{}, - expect: map[string]interface{}{ + expect: map[string]any{ "csiSnapshots": "", }, }, @@ -363,7 +363,7 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { name: "empty info, legacy", volumeInfo: []*volume.BackupVolumeInfo{}, legacyInfoSource: true, - expect: map[string]interface{}{ + expect: map[string]any{ "csiSnapshots": "", }, }, @@ -384,9 +384,9 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { }, }, }, - expect: map[string]interface{}{ - "csiSnapshots": map[string]interface{}{ - "pvc-ns-1/pvc-1": map[string]interface{}{ + expect: map[string]any{ + "csiSnapshots": map[string]any{ + "pvc-ns-1/pvc-1": map[string]any{ "snapshot": "included, specify --details for more information", }, }, @@ -411,10 +411,10 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { }, }, inputDetails: true, - expect: map[string]interface{}{ - "csiSnapshots": map[string]interface{}{ - "pvc-ns-2/pvc-2": map[string]interface{}{ - "snapshot": map[string]interface{}{ + expect: map[string]any{ + "csiSnapshots": map[string]any{ + "pvc-ns-2/pvc-2": map[string]any{ + "snapshot": map[string]any{ "operationID": "fake-operation-2", "snapshotContentName": "vsc-2", "storageSnapshotID": "snapshot-2", @@ -442,9 +442,9 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { }, }, }, - expect: map[string]interface{}{ - "csiSnapshots": map[string]interface{}{ - "pvc-ns-3/pvc-3": map[string]interface{}{ + expect: map[string]any{ + "csiSnapshots": map[string]any{ + "pvc-ns-3/pvc-3": map[string]any{ "dataMovement": "included, specify --details for more information", }, }, @@ -468,10 +468,10 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { }, }, inputDetails: true, - expect: map[string]interface{}{ - "csiSnapshots": map[string]interface{}{ - "pvc-ns-4/pvc-4": map[string]interface{}{ - "dataMovement": map[string]interface{}{ + expect: map[string]any{ + "csiSnapshots": map[string]any{ + "pvc-ns-4/pvc-4": map[string]any{ + "dataMovement": map[string]any{ "operationID": "fake-operation-4", "dataMover": "velero", "uploaderType": "fake-uploader", @@ -498,10 +498,10 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { }, }, inputDetails: true, - expect: map[string]interface{}{ - "csiSnapshots": map[string]interface{}{ - "pvc-ns-4/pvc-4": map[string]interface{}{ - "dataMovement": map[string]interface{}{ + expect: map[string]any{ + "csiSnapshots": map[string]any{ + "pvc-ns-4/pvc-4": map[string]any{ + "dataMovement": map[string]any{ "operationID": "fake-operation-4", "dataMover": "velero", "uploaderType": "fake-uploader", @@ -515,7 +515,7 @@ func TestDescribeCSISnapshotsInSF(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(tt *testing.T) { - output := make(map[string]interface{}) + output := make(map[string]any) describeCSISnapshotsInSF(tc.inputDetails, tc.volumeInfo, output, tc.legacyInfoSource) assert.True(tt, reflect.DeepEqual(output, tc.expect)) }) @@ -527,14 +527,14 @@ func TestDescribeResourcePoliciesInSF(t *testing.T) { Kind: "configmap", Name: "resource-policy-1", } - expect := map[string]interface{}{ - "resourcePolicies": map[string]interface{}{ + expect := map[string]any{ + "resourcePolicies": map[string]any{ "type": "configmap", "name": "resource-policy-1", }, } sd := &StructuredDescriber{ - output: make(map[string]interface{}), + output: make(map[string]any), format: "", } DescribeResourcePoliciesInSF(sd, input) @@ -549,8 +549,8 @@ func TestDescribeBackupResultInSF(t *testing.T) { "ns-1": {"ns-1-msg-1", "ns-1-msg-2"}, }, } - got := map[string]interface{}{} - expect := map[string]interface{}{ + got := map[string]any{} + expect := map[string]any{ "velero": []string{"msg-1", "msg-2"}, "cluster": []string{"cluster-1", "cluster-2"}, "namespace": map[string][]string{ @@ -579,24 +579,24 @@ func TestDescribeDeleteBackupRequestsInSF(t *testing.T) { testcases := []struct { name string input []velerov1api.DeleteBackupRequest - expect map[string]interface{} + expect map[string]any }{ { name: "empty list", input: []velerov1api.DeleteBackupRequest{}, - expect: map[string]interface{}{ - "deletionAttempts": map[string]interface{}{ - "deleteBackupRequests": []map[string]interface{}{}, + expect: map[string]any{ + "deletionAttempts": map[string]any{ + "deleteBackupRequests": []map[string]any{}, }, }, }, { name: "list with one failed and one in-progress request", input: []velerov1api.DeleteBackupRequest{*dbr1, *dbr2}, - expect: map[string]interface{}{ - "deletionAttempts": map[string]interface{}{ + expect: map[string]any{ + "deletionAttempts": map[string]any{ "failed": int(1), - "deleteBackupRequests": []map[string]interface{}{ + "deleteBackupRequests": []map[string]any{ { "creationTimestamp": t1.String(), "phase": velerov1api.DeleteBackupRequestPhaseProcessed, @@ -616,7 +616,7 @@ func TestDescribeDeleteBackupRequestsInSF(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(tt *testing.T) { sd := &StructuredDescriber{ - output: make(map[string]interface{}), + output: make(map[string]any), format: "", } DescribeDeleteBackupRequestsInSF(sd, tc.input) diff --git a/pkg/cmd/util/output/describe.go b/pkg/cmd/util/output/describe.go index c0ec080281..049308a035 100644 --- a/pkg/cmd/util/output/describe.go +++ b/pkg/cmd/util/output/describe.go @@ -47,12 +47,12 @@ func Describe(fn func(d *Describer)) string { return d.buf.String() } -func (d *Describer) Printf(msg string, args ...interface{}) { +func (d *Describer) Printf(msg string, args ...any) { fmt.Fprint(d.out, d.Prefix) fmt.Fprintf(d.out, msg, args...) } -func (d *Describer) Println(args ...interface{}) { +func (d *Describer) Println(args ...any) { fmt.Fprint(d.out, d.Prefix) fmt.Fprintln(d.out, args...) } @@ -122,14 +122,14 @@ func BoolPointerString(b *bool, falseString, trueString, nilString string) strin } type StructuredDescriber struct { - output map[string]interface{} + output map[string]any format string } // NewStructuredDescriber creates a StructuredDescriber. func NewStructuredDescriber(format string) *StructuredDescriber { return &StructuredDescriber{ - output: make(map[string]interface{}), + output: make(map[string]any), format: format, } } @@ -144,13 +144,13 @@ func DescribeInSF(fn func(d *StructuredDescriber), format string) string { } // Describe adds all types of argument to d.output. -func (d *StructuredDescriber) Describe(name string, arg interface{}) { +func (d *StructuredDescriber) Describe(name string, arg any) { d.output[name] = arg } // DescribeMetadata describes standard object metadata. func (d *StructuredDescriber) DescribeMetadata(metadata metav1.ObjectMeta) { - metadataInfo := make(map[string]interface{}) + metadataInfo := make(map[string]any) metadataInfo["name"] = metadata.Name metadataInfo["namespace"] = metadata.Namespace metadataInfo["labels"] = metadata.Labels diff --git a/pkg/cmd/util/output/describe_test.go b/pkg/cmd/util/output/describe_test.go index 45becf8733..02e8cd53ee 100644 --- a/pkg/cmd/util/output/describe_test.go +++ b/pkg/cmd/util/output/describe_test.go @@ -106,17 +106,17 @@ func TestDescriber_DescribeSlice(t *testing.T) { func TestStructuredDescriber_JSONEncode(t *testing.T) { testcases := []struct { name string - inputMap map[string]interface{} + inputMap map[string]any expect string }{ { name: "invalid json", - inputMap: map[string]interface{}{}, + inputMap: map[string]any{}, expect: "{}\n", }, { name: "valid json", - inputMap: map[string]interface{}{"k1": "v1"}, + inputMap: map[string]any{"k1": "v1"}, expect: `{ "k1": "v1" } @@ -148,8 +148,8 @@ func TestStructuredDescriber_DescribeMetadata(t *testing.T) { "annotation-2": "v2", }, } - expect := map[string]interface{}{ - "metadata": map[string]interface{}{ + expect := map[string]any{ + "metadata": map[string]any{ "name": "test", "namespace": "test-ns", "labels": map[string]string{ diff --git a/pkg/cmd/util/output/restore_describer.go b/pkg/cmd/util/output/restore_describer.go index 55363b4b63..c499c34c90 100644 --- a/pkg/cmd/util/output/restore_describer.go +++ b/pkg/cmd/util/output/restore_describer.go @@ -188,7 +188,7 @@ func DescribeRestore( } else { describeCSISnapshotsRestores(d, restoreVolInfo, details) } - } else if err != nil && !errors.Is(err, downloadrequest.ErrNotFound) { + } else if !errors.Is(err, downloadrequest.ErrNotFound) { // For the restores by older versions of velero, it will see NotFound Error when downloading the volume info. // In that case, no errors will be printed. d.Printf("\t\n", err) diff --git a/pkg/controller/backup_deletion_controller.go b/pkg/controller/backup_deletion_controller.go index e76ff5cbbe..5f2f4d35bc 100644 --- a/pkg/controller/backup_deletion_controller.go +++ b/pkg/controller/backup_deletion_controller.go @@ -529,7 +529,7 @@ func (r *backupDeletionReconciler) deleteMovedSnapshots(ctx context.Context, bac directSnapshots := map[string][]repotypes.SnapshotIdentifier{} for i := range list.Items { cm := list.Items[i] - if cm.Data == nil || len(cm.Data) == 0 { + if len(cm.Data) == 0 { errs = append(errs, errors.New("no snapshot info in config")) continue } diff --git a/pkg/controller/backup_repository_controller.go b/pkg/controller/backup_repository_controller.go index fbe193095c..c811b14dc4 100644 --- a/pkg/controller/backup_repository_controller.go +++ b/pkg/controller/backup_repository_controller.go @@ -402,7 +402,7 @@ func getBackupRepositoryConfig(ctx context.Context, ctrlClient client.Client, co return nil, nil } - var unmarshalled map[string]interface{} + var unmarshalled map[string]any if err := json.Unmarshal([]byte(jsonData), &unmarshalled); err != nil { return nil, errors.Wrapf(err, "error unmarshalling config data from %s for repo %s, repo type %s", configName, repoName, repoType) } diff --git a/pkg/controller/backup_repository_controller_test.go b/pkg/controller/backup_repository_controller_test.go index 89b63e9eee..cd667defda 100644 --- a/pkg/controller/backup_repository_controller_test.go +++ b/pkg/controller/backup_repository_controller_test.go @@ -37,7 +37,7 @@ import ( const testMaintenanceFrequency = 10 * time.Minute -func mockBackupRepoReconciler(t *testing.T, mockOn string, arg interface{}, ret interface{}) *BackupRepoReconciler { +func mockBackupRepoReconciler(t *testing.T, mockOn string, arg any, ret any) *BackupRepoReconciler { t.Helper() mgr := &repomokes.Manager{} if mockOn != "" { diff --git a/pkg/controller/backup_sync_controller.go b/pkg/controller/backup_sync_controller.go index 0cbf392407..c6a046d2d9 100644 --- a/pkg/controller/backup_sync_controller.go +++ b/pkg/controller/backup_sync_controller.go @@ -110,7 +110,7 @@ func (b *backupSyncReconciler) Reconcile(ctx context.Context, req ctrl.Request) log.WithError(err).Error("Error listing backups in backup store") return ctrl.Result{}, nil } - backupStoreBackups := sets.New[string](res...) + backupStoreBackups := sets.New(res...) log.WithField("backupCount", len(backupStoreBackups)).Debug("Got backups from backup store") // get a list of all the backups that exist as custom resources in the cluster diff --git a/pkg/controller/backup_sync_controller_test.go b/pkg/controller/backup_sync_controller_test.go index 1bba441343..f26911da8e 100644 --- a/pkg/controller/backup_sync_controller_test.go +++ b/pkg/controller/backup_sync_controller_test.go @@ -556,30 +556,30 @@ var _ = Describe("Backup Sync Reconciler", func() { { name: "no overlapping backups", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backupA").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backupB").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backupC").Phase(velerov1api.BackupPhasePartiallyFailed).Result(), }, - expectedDeletes: sets.New[string]("backupA", "backupB", "backupC"), + expectedDeletes: sets.New("backupA", "backupB", "backupC"), }, { name: "some overlapping backups", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backup-1").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-2").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-B").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-C").Phase(velerov1api.BackupPhasePartiallyFailed).Result(), }, - expectedDeletes: sets.New[string]("backup-B", "backup-C"), + expectedDeletes: sets.New("backup-B", "backup-C"), }, { name: "all overlapping backups", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backup-1").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-2").Phase(velerov1api.BackupPhaseCompleted).Result(), @@ -590,7 +590,7 @@ var _ = Describe("Backup Sync Reconciler", func() { { name: "no overlapping backups but including backups that are not complete", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backupA").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backupB").Phase(velerov1api.BackupPhasePartiallyFailed).Result(), @@ -600,12 +600,12 @@ var _ = Describe("Backup Sync Reconciler", func() { baseBuilder("InProgress").Phase(velerov1api.BackupPhaseInProgress).Result(), baseBuilder("New").Phase(velerov1api.BackupPhaseNew).Result(), }, - expectedDeletes: sets.New[string]("backupA", "backupB"), + expectedDeletes: sets.New("backupA", "backupB"), }, { name: "all overlapping backups and all backups that are not complete", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backup-1").Phase(velerov1api.BackupPhaseFailed).Result(), baseBuilder("backup-2").Phase(velerov1api.BackupPhaseFailedValidation).Result(), @@ -616,7 +616,7 @@ var _ = Describe("Backup Sync Reconciler", func() { { name: "no completed backups in other locations are deleted", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ baseBuilder("backup-1").Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-2").Phase(velerov1api.BackupPhaseCompleted).Result(), @@ -627,12 +627,12 @@ var _ = Describe("Backup Sync Reconciler", func() { baseBuilder("backup-5").ObjectMeta(builder.WithLabels(velerov1api.StorageLocationLabel, "alternate")).Phase(velerov1api.BackupPhaseCompleted).Result(), baseBuilder("backup-6").ObjectMeta(builder.WithLabels(velerov1api.StorageLocationLabel, "alternate")).Phase(velerov1api.BackupPhasePartiallyFailed).Result(), }, - expectedDeletes: sets.New[string]("backup-C", "backup-D"), + expectedDeletes: sets.New("backup-C", "backup-D"), }, { name: "some overlapping backups", namespace: "ns-1", - cloudBackups: sets.New[string]("backup-1", "backup-2", "backup-3"), + cloudBackups: sets.New("backup-1", "backup-2", "backup-3"), k8sBackups: []*velerov1api.Backup{ builder.ForBackup("ns-1", "backup-1"). ObjectMeta( @@ -659,7 +659,7 @@ var _ = Describe("Backup Sync Reconciler", func() { Phase(velerov1api.BackupPhasePartiallyFailed). Result(), }, - expectedDeletes: sets.New[string]("backup-C", "backup-D"), + expectedDeletes: sets.New("backup-C", "backup-D"), useLongBSLName: true, }, } @@ -879,7 +879,7 @@ var _ = Describe("Backup Sync Reconciler", func() { }, } for _, test := range testCases { - test := test + It(test.name, func() { logger := velerotest.NewLogger() b := backupSyncReconciler{ diff --git a/pkg/controller/data_download_controller_test.go b/pkg/controller/data_download_controller_test.go index 498e379edc..c3bd6e4f52 100644 --- a/pkg/controller/data_download_controller_test.go +++ b/pkg/controller/data_download_controller_test.go @@ -70,7 +70,7 @@ func dataDownloadBuilder() *builder.DataDownloadBuilder { } func initDataDownloadReconciler(objects []runtime.Object, needError ...bool) (*DataDownloadReconciler, error) { - var errs []error = make([]error, 6) + errs := make([]error, 6) for k, isError := range needError { if k == 0 && isError { errs[0] = fmt.Errorf("Get error") @@ -503,13 +503,9 @@ func TestDataDownloadReconcile(t *testing.T) { assert.Contains(t, dd.Status.Message, test.expectedStatusMsg) } if test.dd.Namespace == velerov1api.DefaultNamespace { - if controllerutil.ContainsFinalizer(test.dd, DataUploadDownloadFinalizer) { - assert.True(t, true, apierrors.IsNotFound(err)) - } else { + if !controllerutil.ContainsFinalizer(test.dd, DataUploadDownloadFinalizer) { require.NoError(t, err) } - } else { - assert.True(t, true, apierrors.IsNotFound(err)) } if !test.needCreateFSBR { @@ -955,9 +951,10 @@ type ddResumeTestHelper struct { asyncBR datapath.AsyncBR } -func (dt *ddResumeTestHelper) resumeCancellableDataPath(_ *DataUploadReconciler, _ context.Context, _ *velerov2alpha1api.DataUpload, _ logrus.FieldLogger) error { - return dt.resumeErr -} +// Unused function - golangci-lint +// func (dt *ddResumeTestHelper) resumeCancellableDataPath(_ *DataUploadReconciler, _ context.Context, _ *velerov2alpha1api.DataUpload, _ logrus.FieldLogger) error { +// return dt.resumeErr +// } func (dt *ddResumeTestHelper) Expose(context.Context, corev1.ObjectReference, string, string, map[string]string, corev1.ResourceRequirements, time.Duration) error { return nil diff --git a/pkg/controller/data_upload_controller.go b/pkg/controller/data_upload_controller.go index fb96300746..ee89393b01 100644 --- a/pkg/controller/data_upload_controller.go +++ b/pkg/controller/data_upload_controller.go @@ -798,7 +798,7 @@ func (r *DataUploadReconciler) closeDataPath(ctx context.Context, duName string) r.dataPathMgr.RemoveAsyncBR(duName) } -func (r *DataUploadReconciler) setupExposeParam(du *velerov2alpha1api.DataUpload) (interface{}, error) { +func (r *DataUploadReconciler) setupExposeParam(du *velerov2alpha1api.DataUpload) (any, error) { if du.Spec.SnapshotType == velerov2alpha1api.SnapshotTypeCSI { pvc := &corev1.PersistentVolumeClaim{} err := r.client.Get(context.Background(), types.NamespacedName{ @@ -843,7 +843,7 @@ func (r *DataUploadReconciler) setupExposeParam(du *velerov2alpha1api.DataUpload return nil, nil } -func (r *DataUploadReconciler) setupWaitExposePara(du *velerov2alpha1api.DataUpload) interface{} { +func (r *DataUploadReconciler) setupWaitExposePara(du *velerov2alpha1api.DataUpload) any { if du.Spec.SnapshotType == velerov2alpha1api.SnapshotTypeCSI { return &exposer.CSISnapshotExposeWaitParam{ NodeClient: r.client, diff --git a/pkg/controller/data_upload_controller_test.go b/pkg/controller/data_upload_controller_test.go index c7f110e88e..c8a3756070 100644 --- a/pkg/controller/data_upload_controller_test.go +++ b/pkg/controller/data_upload_controller_test.go @@ -120,7 +120,7 @@ func (c *FakeClient) List(ctx context.Context, list kbclient.ObjectList, opts .. } func initDataUploaderReconciler(needError ...bool) (*DataUploadReconciler, error) { - var errs []error = make([]error, 6) + errs := make([]error, 6) for k, isError := range needError { if k == 0 && isError { errs[0] = fmt.Errorf("Get error") @@ -267,7 +267,7 @@ type fakeSnapshotExposer struct { peekErr error } -func (f *fakeSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.ObjectReference, param interface{}) error { +func (f *fakeSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.ObjectReference, param any) error { du := velerov2alpha1api.DataUpload{} err := f.kubeClient.Get(ctx, kbclient.ObjectKey{ Name: dataUploadName, @@ -284,7 +284,7 @@ func (f *fakeSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.Obj return nil } -func (f *fakeSnapshotExposer) GetExposed(ctx context.Context, du corev1.ObjectReference, tm time.Duration, para interface{}) (*exposer.ExposeResult, error) { +func (f *fakeSnapshotExposer) GetExposed(ctx context.Context, du corev1.ObjectReference, tm time.Duration, para any) (*exposer.ExposeResult, error) { pod := &corev1.Pod{} err := f.kubeClient.Get(ctx, kbclient.ObjectKey{ Name: dataUploadName, @@ -315,11 +315,11 @@ type fakeDataUploadFSBR struct { startErr error } -func (f *fakeDataUploadFSBR) Init(ctx context.Context, param interface{}) error { +func (f *fakeDataUploadFSBR) Init(ctx context.Context, param any) error { return f.initErr } -func (f *fakeDataUploadFSBR) StartBackup(source datapath.AccessPoint, uploaderConfigs map[string]string, param interface{}) error { +func (f *fakeDataUploadFSBR) StartBackup(source datapath.AccessPoint, uploaderConfigs map[string]string, param any) error { return f.startErr } @@ -1035,11 +1035,11 @@ func (dt *duResumeTestHelper) resumeCancellableDataPath(_ *DataUploadReconciler, return dt.resumeErr } -func (dt *duResumeTestHelper) Expose(context.Context, corev1.ObjectReference, interface{}) error { +func (dt *duResumeTestHelper) Expose(context.Context, corev1.ObjectReference, any) error { return nil } -func (dt *duResumeTestHelper) GetExposed(context.Context, corev1.ObjectReference, time.Duration, interface{}) (*exposer.ExposeResult, error) { +func (dt *duResumeTestHelper) GetExposed(context.Context, corev1.ObjectReference, time.Duration, any) (*exposer.ExposeResult, error) { return dt.exposeResult, dt.getExposeErr } diff --git a/pkg/controller/pod_volume_backup_controller.go b/pkg/controller/pod_volume_backup_controller.go index dad1593032..53f7129b8a 100644 --- a/pkg/controller/pod_volume_backup_controller.go +++ b/pkg/controller/pod_volume_backup_controller.go @@ -348,7 +348,7 @@ func (r *PodVolumeBackupReconciler) getParentSnapshot(ctx context.Context, log l return "" } - log.WithFields(map[string]interface{}{ + log.WithFields(map[string]any{ "parentPodVolumeBackup": mostRecentPVB.Name, "parentSnapshotID": mostRecentPVB.Status.SnapshotID, }).Info("Found most recent completed PodVolumeBackup for PVC") diff --git a/pkg/controller/pod_volume_backup_controller_test.go b/pkg/controller/pod_volume_backup_controller_test.go index 1b4d408e4a..0affc406fa 100644 --- a/pkg/controller/pod_volume_backup_controller_test.go +++ b/pkg/controller/pod_volume_backup_controller_test.go @@ -97,11 +97,11 @@ type fakeFSBR struct { clock clock.WithTickerAndDelayedExecution } -func (b *fakeFSBR) Init(ctx context.Context, param interface{}) error { +func (b *fakeFSBR) Init(ctx context.Context, param any) error { return nil } -func (b *fakeFSBR) StartBackup(source datapath.AccessPoint, uploaderConfigs map[string]string, param interface{}) error { +func (b *fakeFSBR) StartBackup(source datapath.AccessPoint, uploaderConfigs map[string]string, param any) error { pvb := b.pvb original := b.pvb.DeepCopy() diff --git a/pkg/controller/restore_controller.go b/pkg/controller/restore_controller.go index aa55715c2c..a865135880 100644 --- a/pkg/controller/restore_controller.go +++ b/pkg/controller/restore_controller.go @@ -396,7 +396,7 @@ func (r *restoreReconciler) validateAndComplete(restore *api.Restore) (backupInf restore.Spec.ScheduleName = info.backup.GetLabels()[api.ScheduleNameLabel] } - var resourceModifiers *resourcemodifiers.ResourceModifiers = nil + var resourceModifiers *resourcemodifiers.ResourceModifiers if restore.Spec.ResourceModifier != nil && strings.EqualFold(restore.Spec.ResourceModifier.Kind, resourcemodifiers.ConfigmapRefType) { ResourceModifierConfigMap := &corev1api.ConfigMap{} err := r.kbClient.Get(context.Background(), client.ObjectKey{Namespace: restore.Namespace, Name: restore.Spec.ResourceModifier.Name}, ResourceModifierConfigMap) diff --git a/pkg/datamover/backup_micro_service.go b/pkg/datamover/backup_micro_service.go index de77204a84..3c6601cbf5 100644 --- a/pkg/datamover/backup_micro_service.go +++ b/pkg/datamover/backup_micro_service.go @@ -99,7 +99,7 @@ func (r *BackupMicroService) Init() error { handler, err := r.duInformer.AddEventHandler( cachetool.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj interface{}, newObj interface{}) { + UpdateFunc: func(oldObj any, newObj any) { oldDu := oldObj.(*velerov2alpha1api.DataUpload) newDu := newObj.(*velerov2alpha1api.DataUpload) diff --git a/pkg/datamover/restore_micro_service.go b/pkg/datamover/restore_micro_service.go index 1746366c9d..25a3f3ff38 100644 --- a/pkg/datamover/restore_micro_service.go +++ b/pkg/datamover/restore_micro_service.go @@ -88,7 +88,7 @@ func (r *RestoreMicroService) Init() error { handler, err := r.ddInformer.AddEventHandler( cachetool.ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj interface{}, newObj interface{}) { + UpdateFunc: func(oldObj any, newObj any) { oldDd := oldObj.(*velerov2alpha1api.DataDownload) newDd := newObj.(*velerov2alpha1api.DataDownload) diff --git a/pkg/datapath/file_system.go b/pkg/datapath/file_system.go index 5d3b54f281..430226dd2c 100644 --- a/pkg/datapath/file_system.go +++ b/pkg/datapath/file_system.go @@ -85,7 +85,7 @@ func newFileSystemBR(jobName string, requestorType string, client client.Client, return fs } -func (fs *fileSystemBR) Init(ctx context.Context, param interface{}) error { +func (fs *fileSystemBR) Init(ctx context.Context, param any) error { initParam := param.(*FSBRInitParam) var err error @@ -164,7 +164,7 @@ func (fs *fileSystemBR) close(ctx context.Context) { } } -func (fs *fileSystemBR) StartBackup(source AccessPoint, uploaderConfig map[string]string, param interface{}) error { +func (fs *fileSystemBR) StartBackup(source AccessPoint, uploaderConfig map[string]string, param any) error { if !fs.initialized { return errors.New("file system data path is not initialized") } diff --git a/pkg/datapath/micro_service_watcher.go b/pkg/datapath/micro_service_watcher.go index 8d09275389..6e6dea0db2 100644 --- a/pkg/datapath/micro_service_watcher.go +++ b/pkg/datapath/micro_service_watcher.go @@ -104,7 +104,7 @@ func newMicroServiceBRWatcher(client client.Client, kubeClient kubernetes.Interf return ms } -func (ms *microServiceBRWatcher) Init(ctx context.Context, param interface{}) error { +func (ms *microServiceBRWatcher) Init(ctx context.Context, param any) error { eventInformer, err := ms.mgr.GetCache().GetInformer(ctx, &v1.Event{}) if err != nil { return errors.Wrap(err, "error getting event informer") @@ -117,7 +117,7 @@ func (ms *microServiceBRWatcher) Init(ctx context.Context, param interface{}) er eventHandler, err := eventInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { + AddFunc: func(obj any) { evt := obj.(*v1.Event) if evt.InvolvedObject.Namespace != ms.namespace || evt.InvolvedObject.Name != ms.associatedObject { return @@ -125,7 +125,7 @@ func (ms *microServiceBRWatcher) Init(ctx context.Context, param interface{}) er ms.eventCh <- evt }, - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { evt := obj.(*v1.Event) if evt.InvolvedObject.Namespace != ms.namespace || evt.InvolvedObject.Name != ms.associatedObject { return @@ -141,7 +141,7 @@ func (ms *microServiceBRWatcher) Init(ctx context.Context, param interface{}) er podHandler, err := podInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { pod := obj.(*v1.Pod) if pod.Namespace != ms.namespace || pod.Name != ms.thisPod { return @@ -213,7 +213,7 @@ func (ms *microServiceBRWatcher) close() { } } -func (ms *microServiceBRWatcher) StartBackup(source AccessPoint, uploaderConfig map[string]string, param interface{}) error { +func (ms *microServiceBRWatcher) StartBackup(source AccessPoint, uploaderConfig map[string]string, param any) error { ms.log.Infof("Start watching backup ms for source %v", source.ByPath) ms.startWatch() @@ -251,7 +251,7 @@ var funcRedirectLog = redirectDataMoverLogs var funcGetResultFromMessage = getResultFromMessage var funcGetProgressFromMessage = getProgressFromMessage -var eventWaitTimeout time.Duration = time.Minute +var eventWaitTimeout = time.Minute func (ms *microServiceBRWatcher) startWatch() { ms.wgWatcher.Add(1) diff --git a/pkg/datapath/types.go b/pkg/datapath/types.go index a2fac3ed59..1f8bb642b5 100644 --- a/pkg/datapath/types.go +++ b/pkg/datapath/types.go @@ -57,10 +57,10 @@ type AccessPoint struct { // AsyncBR is the interface for asynchronous data path methods type AsyncBR interface { // Init initializes an asynchronous data path instance - Init(ctx context.Context, param interface{}) error + Init(ctx context.Context, param any) error // StartBackup starts an asynchronous data path instance for backup - StartBackup(source AccessPoint, dataMoverConfig map[string]string, param interface{}) error + StartBackup(source AccessPoint, dataMoverConfig map[string]string, param any) error // StartRestore starts an asynchronous data path instance for restore StartRestore(snapshotID string, target AccessPoint, dataMoverConfig map[string]string) error diff --git a/pkg/exposer/csi_snapshot.go b/pkg/exposer/csi_snapshot.go index 871d54cec8..5aa1cf53e5 100644 --- a/pkg/exposer/csi_snapshot.go +++ b/pkg/exposer/csi_snapshot.go @@ -97,7 +97,7 @@ type csiSnapshotExposer struct { log logrus.FieldLogger } -func (e *csiSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.ObjectReference, param interface{}) error { +func (e *csiSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.ObjectReference, param any) error { csiExposeParam := param.(*CSISnapshotExposeParam) curLog := e.log.WithFields(logrus.Fields{ @@ -228,7 +228,7 @@ func (e *csiSnapshotExposer) Expose(ctx context.Context, ownerObject corev1.Obje return nil } -func (e *csiSnapshotExposer) GetExposed(ctx context.Context, ownerObject corev1.ObjectReference, timeout time.Duration, param interface{}) (*ExposeResult, error) { +func (e *csiSnapshotExposer) GetExposed(ctx context.Context, ownerObject corev1.ObjectReference, timeout time.Duration, param any) (*ExposeResult, error) { exposeWaitParam := param.(*CSISnapshotExposeWaitParam) backupPodName := ownerObject.Name @@ -528,7 +528,7 @@ func (e *csiSnapshotExposer) createBackupPod( return nil, errors.Wrap(err, "error to get inherited pod info from node-agent") } - var gracePeriod int64 = 0 + var gracePeriod int64 volumeMounts, volumeDevices, volumePath := kube.MakePodPVCAttachment(volumeName, backupPVC.Spec.VolumeMode, backupPVCReadOnly) volumeMounts = append(volumeMounts, podInfo.volumeMounts...) diff --git a/pkg/exposer/generic_restore.go b/pkg/exposer/generic_restore.go index af61ed438f..505cd0794b 100644 --- a/pkg/exposer/generic_restore.go +++ b/pkg/exposer/generic_restore.go @@ -359,7 +359,7 @@ func (e *genericRestoreExposer) createRestorePod(ctx context.Context, ownerObjec return nil, errors.Wrap(err, "error to get inherited pod info from node-agent") } - var gracePeriod int64 = 0 + var gracePeriod int64 volumeMounts, volumeDevices, volumePath := kube.MakePodPVCAttachment(volumeName, targetPVC.Spec.VolumeMode, false) volumeMounts = append(volumeMounts, podInfo.volumeMounts...) diff --git a/pkg/exposer/snapshot.go b/pkg/exposer/snapshot.go index a4a6bd7df2..257ba34318 100644 --- a/pkg/exposer/snapshot.go +++ b/pkg/exposer/snapshot.go @@ -26,11 +26,11 @@ import ( // SnapshotExposer is the interfaces for a snapshot exposer type SnapshotExposer interface { // Expose starts the process to expose a snapshot, the expose process may take long time - Expose(context.Context, corev1.ObjectReference, interface{}) error + Expose(context.Context, corev1.ObjectReference, any) error // GetExposed polls the status of the expose. // If the expose is accessible by the current caller, it waits the expose ready and returns the expose result. // Otherwise, it returns nil as the expose result without an error. - GetExposed(context.Context, corev1.ObjectReference, time.Duration, interface{}) (*ExposeResult, error) + GetExposed(context.Context, corev1.ObjectReference, time.Duration, any) (*ExposeResult, error) // PeekExposed tests the status of the expose. // If the expose is incomplete but not recoverable, it returns an error. diff --git a/pkg/install/install.go b/pkg/install/install.go index 3bf0651702..3ddc362cde 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -274,7 +274,7 @@ func createResource(r *unstructured.Unstructured, factory client.DynamicFactory, id := fmt.Sprintf("%s/%s", r.GetKind(), r.GetName()) // Helper to reduce boilerplate message about the same object - log := func(f string, a ...interface{}) { + log := func(f string, a ...any) { format := strings.Join([]string{id, ": ", f, "\n"}, "") fmt.Fprintf(w, format, a...) } @@ -300,7 +300,7 @@ func CreateClient(r *unstructured.Unstructured, factory client.DynamicFactory, w id := fmt.Sprintf("%s/%s", r.GetKind(), r.GetName()) // Helper to reduce boilerplate message about the same object - log := func(f string, a ...interface{}) { + log := func(f string, a ...any) { format := strings.Join([]string{id, ": ", f, "\n"}, "") fmt.Fprintf(w, format, a...) } diff --git a/pkg/itemblock/actions/pvc_action.go b/pkg/itemblock/actions/pvc_action.go index 4ec99d03b9..eee4e2fb35 100644 --- a/pkg/itemblock/actions/pvc_action.go +++ b/pkg/itemblock/actions/pvc_action.go @@ -42,7 +42,7 @@ type PVCAction struct { } func NewPVCAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, errors.WithStack(err) diff --git a/pkg/label/label.go b/pkg/label/label.go index 411de2cda9..98d232f246 100644 --- a/pkg/label/label.go +++ b/pkg/label/label.go @@ -18,6 +18,7 @@ package label import ( "crypto/sha256" + "encoding/hex" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -38,7 +39,7 @@ func GetValidName(label string) string { } sha := sha256.Sum256([]byte(label)) - strSha := fmt.Sprintf("%x", sha) + strSha := hex.EncodeToString(sha[:]) charsFromLabel := validation.DNS1035LabelMaxLength - 6 if charsFromLabel < 0 { // Derive the label name from sha hash in case the DNS1035LabelMaxLength is less than 6 diff --git a/pkg/persistence/object_store.go b/pkg/persistence/object_store.go index 5cdb36b6f0..bfdc8fbdc1 100644 --- a/pkg/persistence/object_store.go +++ b/pkg/persistence/object_store.go @@ -187,7 +187,7 @@ func (b *objectBackupStoreGetter) Get(location *velerov1api.BackupStorageLocatio return nil, err } - log := logger.WithFields(logrus.Fields(map[string]interface{}{ + log := logger.WithFields(logrus.Fields(map[string]any{ "bucket": bucket, "prefix": prefix, })) @@ -410,7 +410,7 @@ func tryGet(objectStore velero.ObjectStore, bucket, key string) (io.ReadCloser, // decode extracts a .json.gz file reader into the object pointed to // by 'into'. -func decode(jsongzReader io.Reader, into interface{}) error { +func decode(jsongzReader io.Reader, into any) error { gzr, err := gzip.NewReader(jsongzReader) if err != nil { return errors.WithStack(err) diff --git a/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go b/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go index ce8d072614..0064280353 100644 --- a/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go +++ b/pkg/plugin/clientmgmt/backupitemaction/v1/restartable_backup_item_action_test.go @@ -36,7 +36,7 @@ import ( func TestRestartableGetBackupItemAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -105,13 +105,13 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { b := new(v1.Backup) pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } pvToReturn := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "green", }, } @@ -125,7 +125,7 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindBackupItemAction, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableBackupItemAction{ Key: key, SharedPluginProcess: p, @@ -136,15 +136,15 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Execute", - Inputs: []interface{}{pv, b}, - ExpectedErrorOutputs: []interface{}{nil, ([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{pvToReturn, additionalItems, errors.Errorf("delegate error")}, + Inputs: []any{pv, b}, + ExpectedErrorOutputs: []any{nil, ([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{pvToReturn, additionalItems, errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go b/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go index efcb94927c..77cdea74c1 100644 --- a/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go +++ b/pkg/plugin/clientmgmt/backupitemaction/v2/restartable_backup_item_action_test.go @@ -36,7 +36,7 @@ import ( func TestRestartableGetBackupItemAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -105,7 +105,7 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { b := new(v1.Backup) pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } @@ -113,7 +113,7 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { oid := "operation1" pvToReturn := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "green", }, } @@ -127,7 +127,7 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindBackupItemAction, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableBackupItemAction{ Key: key, SharedPluginProcess: p, @@ -138,27 +138,27 @@ func TestRestartableBackupItemActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Execute", - Inputs: []interface{}{pv, b}, - ExpectedErrorOutputs: []interface{}{nil, ([]velero.ResourceIdentifier)(nil), "", ([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{pvToReturn, additionalItems, "", ([]velero.ResourceIdentifier)(nil), errors.Errorf("delegate error")}, + Inputs: []any{pv, b}, + ExpectedErrorOutputs: []any{nil, ([]velero.ResourceIdentifier)(nil), "", ([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{pvToReturn, additionalItems, "", ([]velero.ResourceIdentifier)(nil), errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Progress", - Inputs: []interface{}{oid, b}, - ExpectedErrorOutputs: []interface{}{velero.OperationProgress{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.OperationProgress{}, errors.Errorf("delegate error")}, + Inputs: []any{oid, b}, + ExpectedErrorOutputs: []any{velero.OperationProgress{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.OperationProgress{}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Cancel", - Inputs: []interface{}{oid, b}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{oid, b}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go b/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go index eeec9c74c5..80bb5aeaf5 100644 --- a/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go +++ b/pkg/plugin/clientmgmt/itemblockaction/v1/restartable_item_block_action_test.go @@ -36,7 +36,7 @@ import ( func TestRestartableGetItemBlockAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -105,7 +105,7 @@ func TestRestartableItemBlockActionDelegatedFunctions(t *testing.T) { b := new(v1.Backup) pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } @@ -119,7 +119,7 @@ func TestRestartableItemBlockActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindItemBlockAction, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableItemBlockAction{ Key: key, SharedPluginProcess: p, @@ -130,15 +130,15 @@ func TestRestartableItemBlockActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "GetRelatedItems", - Inputs: []interface{}{pv, b}, - ExpectedErrorOutputs: []interface{}{([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{relatedItems, errors.Errorf("delegate error")}, + Inputs: []any{pv, b}, + ExpectedErrorOutputs: []any{([]velero.ResourceIdentifier)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{relatedItems, errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/manager_test.go b/pkg/plugin/clientmgmt/manager_test.go index 8e15bbf503..e3e9e41c13 100644 --- a/pkg/plugin/clientmgmt/manager_test.go +++ b/pkg/plugin/clientmgmt/manager_test.go @@ -159,10 +159,10 @@ func TestGetObjectStore(t *testing.T) { getPluginTest(t, common.PluginKindObjectStore, "velero.io/aws", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetObjectStore(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &restartableObjectStore{ key: process.KindAndName{Kind: common.PluginKindObjectStore, Name: name}, sharedPluginProcess: sharedPluginProcess, @@ -176,10 +176,10 @@ func TestGetVolumeSnapshotter(t *testing.T) { getPluginTest(t, common.PluginKindVolumeSnapshotter, "velero.io/aws", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetVolumeSnapshotter(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &vsv1cli.RestartableVolumeSnapshotter{ Key: process.KindAndName{Kind: common.PluginKindVolumeSnapshotter, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -193,10 +193,10 @@ func TestGetBackupItemAction(t *testing.T) { getPluginTest(t, common.PluginKindBackupItemAction, "velero.io/pod", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetBackupItemAction(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &biav1cli.RestartableBackupItemAction{ Key: process.KindAndName{Kind: common.PluginKindBackupItemAction, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -210,10 +210,10 @@ func TestGetBackupItemActionV2(t *testing.T) { getPluginTest(t, common.PluginKindBackupItemActionV2, "velero.io/pod", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetBackupItemActionV2(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &biav2cli.RestartableBackupItemAction{ Key: process.KindAndName{Kind: common.PluginKindBackupItemActionV2, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -227,10 +227,10 @@ func TestGetRestoreItemAction(t *testing.T) { getPluginTest(t, common.PluginKindRestoreItemAction, "velero.io/pod", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetRestoreItemAction(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &riav1cli.RestartableRestoreItemAction{ Key: process.KindAndName{Kind: common.PluginKindRestoreItemAction, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -244,10 +244,10 @@ func TestGetRestoreItemActionV2(t *testing.T) { getPluginTest(t, common.PluginKindRestoreItemActionV2, "velero.io/pod", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetRestoreItemActionV2(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &riav2cli.RestartableRestoreItemAction{ Key: process.KindAndName{Kind: common.PluginKindRestoreItemActionV2, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -261,10 +261,10 @@ func TestGetItemBlockAction(t *testing.T) { getPluginTest(t, common.PluginKindItemBlockAction, "velero.io/pod", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetItemBlockAction(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &ibav1cli.RestartableItemBlockAction{ Key: process.KindAndName{Kind: common.PluginKindItemBlockAction, Name: name}, SharedPluginProcess: sharedPluginProcess, @@ -278,8 +278,8 @@ func getPluginTest( t *testing.T, kind common.PluginKind, name string, - getPluginFunc func(m Manager, name string) (interface{}, error), - expectedResultFunc func(name string, sharedPluginProcess process.RestartableProcess) interface{}, + getPluginFunc func(m Manager, name string) (any, error), + expectedResultFunc func(name string, sharedPluginProcess process.RestartableProcess) any, reinitializable bool, ) { t.Helper() @@ -373,7 +373,7 @@ func TestGetBackupItemActions(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -408,7 +408,7 @@ func TestGetBackupItemActions(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range backupItemActions { actual = append(actual, backupItemActions[i]) } @@ -465,7 +465,7 @@ func TestGetBackupItemActionsV2(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -500,7 +500,7 @@ func TestGetBackupItemActionsV2(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range backupItemActions { actual = append(actual, backupItemActions[i]) } @@ -557,7 +557,7 @@ func TestGetRestoreItemActions(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -592,7 +592,7 @@ func TestGetRestoreItemActions(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range restoreItemActions { actual = append(actual, restoreItemActions[i]) } @@ -649,7 +649,7 @@ func TestGetRestoreItemActionsV2(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -684,7 +684,7 @@ func TestGetRestoreItemActionsV2(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range restoreItemActions { actual = append(actual, restoreItemActions[i]) } @@ -698,10 +698,10 @@ func TestGetDeleteItemAction(t *testing.T) { getPluginTest(t, common.PluginKindDeleteItemAction, "velero.io/deleter", - func(m Manager, name string) (interface{}, error) { + func(m Manager, name string) (any, error) { return m.GetDeleteItemAction(name) }, - func(name string, sharedPluginProcess process.RestartableProcess) interface{} { + func(name string, sharedPluginProcess process.RestartableProcess) any { return &restartableDeleteItemAction{ key: process.KindAndName{Kind: common.PluginKindDeleteItemAction, Name: name}, sharedPluginProcess: sharedPluginProcess, @@ -758,7 +758,7 @@ func TestGetDeleteItemActions(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -793,7 +793,7 @@ func TestGetDeleteItemActions(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range deleteItemActions { actual = append(actual, deleteItemActions[i]) } @@ -850,7 +850,7 @@ func TestGetItemBlockActions(t *testing.T) { } registry.On("List", pluginKind).Return(pluginIDs) - var expectedActions []interface{} + var expectedActions []any for i := range pluginIDs { pluginID := pluginIDs[i] pluginName := pluginID.Name @@ -885,7 +885,7 @@ func TestGetItemBlockActions(t *testing.T) { assert.EqualError(t, err, "NewRestartableProcess") } else { require.NoError(t, err) - var actual []interface{} + var actual []any for i := range itemBlockActions { actual = append(actual, itemBlockActions[i]) } diff --git a/pkg/plugin/clientmgmt/process/logrus_adapter.go b/pkg/plugin/clientmgmt/process/logrus_adapter.go index b8a8fb0247..da573284a7 100644 --- a/pkg/plugin/clientmgmt/process/logrus_adapter.go +++ b/pkg/plugin/clientmgmt/process/logrus_adapter.go @@ -37,8 +37,8 @@ type logrusAdapter struct { // args are alternating key, value pairs, where the keys // are expected to be strings, and values can be any type. -func argsToFields(args ...interface{}) logrus.Fields { - fields := make(map[string]interface{}) +func argsToFields(args ...any) logrus.Fields { + fields := make(map[string]any) for i := 0; i < len(args); i += 2 { switch args[i] { @@ -52,7 +52,7 @@ func argsToFields(args ...interface{}) logrus.Fields { // to log at based on the hclog-compatible `@level` field which // we're adding via HcLogLevelHook). default: - var val interface{} + var val any if i+1 < len(args) { val = args[i+1] } @@ -66,27 +66,27 @@ func argsToFields(args ...interface{}) logrus.Fields { // Trace emits a message and key/value pairs at the DEBUG level // (logrus doesn't have a TRACE level) -func (l *logrusAdapter) Trace(msg string, args ...interface{}) { +func (l *logrusAdapter) Trace(msg string, args ...any) { l.Debug(msg, args...) } // Debug emits a message and key/value pairs at the DEBUG level -func (l *logrusAdapter) Debug(msg string, args ...interface{}) { +func (l *logrusAdapter) Debug(msg string, args ...any) { l.impl.WithFields(argsToFields(args...)).Debug(msg) } // Info emits a message and key/value pairs at the INFO level -func (l *logrusAdapter) Info(msg string, args ...interface{}) { +func (l *logrusAdapter) Info(msg string, args ...any) { l.impl.WithFields(argsToFields(args...)).Info(msg) } // Warn emits a message and key/value pairs at the WARN level -func (l *logrusAdapter) Warn(msg string, args ...interface{}) { +func (l *logrusAdapter) Warn(msg string, args ...any) { l.impl.WithFields(argsToFields(args...)).Warn(msg) } // Error emits a message and key/value pairs at the ERROR level -func (l *logrusAdapter) Error(msg string, args ...interface{}) { +func (l *logrusAdapter) Error(msg string, args ...any) { l.impl.WithFields(argsToFields(args...)).Error(msg) } @@ -121,7 +121,7 @@ func (l *logrusAdapter) IsError() bool { } // With creates a sublogger that will always have the given key/value pairs -func (l *logrusAdapter) With(args ...interface{}) hclog.Logger { +func (l *logrusAdapter) With(args ...any) hclog.Logger { return &logrusAdapter{ impl: l.impl.WithFields(argsToFields(args...)), level: l.level, @@ -164,7 +164,7 @@ func (l *logrusAdapter) SetLevel(_ hclog.Level) { } // ImpliedArgs returns With key/value pairs -func (l *logrusAdapter) ImpliedArgs() []interface{} { +func (l *logrusAdapter) ImpliedArgs() []any { panic("not implemented") } @@ -172,7 +172,7 @@ func (l *logrusAdapter) ImpliedArgs() []interface{} { // keys must be strings // vals can be any type, but display is implementation specific // Emit a message and key/value pairs at a provided log level -func (l *logrusAdapter) Log(level hclog.Level, msg string, args ...interface{}) { +func (l *logrusAdapter) Log(level hclog.Level, msg string, args ...any) { switch level { case hclog.Trace: l.Trace(msg, args...) diff --git a/pkg/plugin/clientmgmt/process/logrus_adapter_test.go b/pkg/plugin/clientmgmt/process/logrus_adapter_test.go index 76fbc4f1c6..cf4ff77a1b 100644 --- a/pkg/plugin/clientmgmt/process/logrus_adapter_test.go +++ b/pkg/plugin/clientmgmt/process/logrus_adapter_test.go @@ -26,34 +26,34 @@ import ( func TestArgsToFields(t *testing.T) { tests := []struct { name string - args []interface{} + args []any expectedFields logrus.Fields }{ { name: "empty args results in empty map of fields", - args: []interface{}{}, - expectedFields: logrus.Fields(map[string]interface{}{}), + args: []any{}, + expectedFields: logrus.Fields(map[string]any{}), }, { name: "matching string keys/values are correctly set as fields", - args: []interface{}{"key-1", "value-1", "key-2", "value-2"}, - expectedFields: logrus.Fields(map[string]interface{}{ + args: []any{"key-1", "value-1", "key-2", "value-2"}, + expectedFields: logrus.Fields(map[string]any{ "key-1": "value-1", "key-2": "value-2", }), }, { name: "time/timestamp/level entries are removed", - args: []interface{}{"time", time.Now(), "key-1", "value-1", "timestamp", time.Now(), "key-2", "value-2", "level", "WARN"}, - expectedFields: logrus.Fields(map[string]interface{}{ + args: []any{"time", time.Now(), "key-1", "value-1", "timestamp", time.Now(), "key-2", "value-2", "level", "WARN"}, + expectedFields: logrus.Fields(map[string]any{ "key-1": "value-1", "key-2": "value-2", }), }, { name: "odd number of args adds the last arg as a field with a nil value", - args: []interface{}{"key-1", "value-1", "key-2", "value-2", "key-3"}, - expectedFields: logrus.Fields(map[string]interface{}{ + args: []any{"key-1", "value-1", "key-2", "value-2", "key-3"}, + expectedFields: logrus.Fields(map[string]any{ "key-1": "value-1", "key-2": "value-2", "key-3": nil, diff --git a/pkg/plugin/clientmgmt/process/process.go b/pkg/plugin/clientmgmt/process/process.go index 5ebb4a7a18..4d20a17847 100644 --- a/pkg/plugin/clientmgmt/process/process.go +++ b/pkg/plugin/clientmgmt/process/process.go @@ -40,7 +40,7 @@ func (pf *processFactory) newProcess(command string, logger logrus.FieldLogger, } type Process interface { - dispense(key KindAndName) (interface{}, error) + dispense(key KindAndName) (any, error) exited() bool kill() } @@ -97,7 +97,7 @@ func removeFeaturesFlag(args []string) []string { return commandArgs } -func (r *process) dispense(key KindAndName) (interface{}, error) { +func (r *process) dispense(key KindAndName) (any, error) { // This calls GRPCClient(clientConn) on the plugin instance registered for key.name. dispensed, err := r.protocolClient.Dispense(key.Kind.String()) if err != nil { diff --git a/pkg/plugin/clientmgmt/process/process_test.go b/pkg/plugin/clientmgmt/process/process_test.go index e65c890511..e67de8db9c 100644 --- a/pkg/plugin/clientmgmt/process/process_test.go +++ b/pkg/plugin/clientmgmt/process/process_test.go @@ -36,7 +36,7 @@ func (cp *mockClientProtocol) Close() error { return args.Error(0) } -func (cp *mockClientProtocol) Dispense(name string) (interface{}, error) { +func (cp *mockClientProtocol) Dispense(name string) (any, error) { args := cp.Called(name) return args.Get(0), args.Error(1) } @@ -50,7 +50,7 @@ type mockClientDispenser struct { mock.Mock } -func (cd *mockClientDispenser) ClientFor(name string) interface{} { +func (cd *mockClientDispenser) ClientFor(name string) any { args := cd.Called(name) return args.Get(0) } @@ -93,7 +93,7 @@ func TestDispense(t *testing.T) { clientDispenser := new(mockClientDispenser) defer clientDispenser.AssertExpectations(t) - var client interface{} + var client any key := KindAndName{} if tc.clientDispenser { diff --git a/pkg/plugin/clientmgmt/process/restartable_process.go b/pkg/plugin/clientmgmt/process/restartable_process.go index 21ed810225..e285f82daa 100644 --- a/pkg/plugin/clientmgmt/process/restartable_process.go +++ b/pkg/plugin/clientmgmt/process/restartable_process.go @@ -42,7 +42,7 @@ type RestartableProcess interface { AddReinitializer(key KindAndName, r Reinitializer) Reset() error ResetIfNeeded() error - GetByKindAndName(key KindAndName) (interface{}, error) + GetByKindAndName(key KindAndName) (any, error) Stop() } @@ -57,7 +57,7 @@ type restartableProcess struct { // lock guards all of the fields below lock sync.RWMutex process Process - plugins map[KindAndName]interface{} + plugins map[KindAndName]any reinitializers map[KindAndName]Reinitializer resetFailures int } @@ -65,7 +65,7 @@ type restartableProcess struct { // reinitializer is capable of reinitializing a restartable plugin instance using the newly dispensed plugin. type Reinitializer interface { // reinitialize reinitializes a restartable plugin instance using the newly dispensed plugin. - Reinitialize(dispensed interface{}) error + Reinitialize(dispensed any) error } // newRestartableProcess creates a new restartableProcess for the given command and options. @@ -74,7 +74,7 @@ func newRestartableProcess(command string, logger logrus.FieldLogger, logLevel l command: command, logger: logger, logLevel: logLevel, - plugins: make(map[KindAndName]interface{}), + plugins: make(map[KindAndName]any), reinitializers: make(map[KindAndName]Reinitializer), } @@ -118,7 +118,7 @@ func (p *restartableProcess) resetLH() error { // Redispense any previously dispensed plugins, reinitializing if necessary. // Start by creating a new map to hold the newly dispensed plugins. - newPlugins := make(map[KindAndName]interface{}) + newPlugins := make(map[KindAndName]any) for key := range p.plugins { // Re-dispense dispensed, err := p.process.dispense(key) @@ -160,7 +160,7 @@ func (p *restartableProcess) ResetIfNeeded() error { } // GetByKindAndName acquires the lock and calls getByKindAndNameLH. -func (p *restartableProcess) GetByKindAndName(key KindAndName) (interface{}, error) { +func (p *restartableProcess) GetByKindAndName(key KindAndName) (any, error) { p.lock.Lock() defer p.lock.Unlock() @@ -169,7 +169,7 @@ func (p *restartableProcess) GetByKindAndName(key KindAndName) (interface{}, err // getByKindAndNameLH returns the dispensed plugin for key. If the plugin hasn't been dispensed before, it dispenses a // new one. -func (p *restartableProcess) getByKindAndNameLH(key KindAndName) (interface{}, error) { +func (p *restartableProcess) getByKindAndNameLH(key KindAndName) (any, error) { dispensed, found := p.plugins[key] if found { return dispensed, nil diff --git a/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go b/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go index b6cf8d8366..98516c2e46 100644 --- a/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go +++ b/pkg/plugin/clientmgmt/restartable_delete_item_action_test.go @@ -35,7 +35,7 @@ import ( func TestRestartableGetDeleteItemAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -103,7 +103,7 @@ func TestRestartableDeleteItemActionGetDelegate(t *testing.T) { func TestRestartableDeleteItemActionDelegatedFunctions(t *testing.T) { pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } @@ -118,7 +118,7 @@ func TestRestartableDeleteItemActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindDeleteItemAction, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &restartableDeleteItemAction{ key: key, sharedPluginProcess: p, @@ -130,15 +130,15 @@ func TestRestartableDeleteItemActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Execute", - Inputs: []interface{}{input}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{input}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/restartable_object_store.go b/pkg/plugin/clientmgmt/restartable_object_store.go index ac9ae4b875..6e66d4b3e8 100644 --- a/pkg/plugin/clientmgmt/restartable_object_store.go +++ b/pkg/plugin/clientmgmt/restartable_object_store.go @@ -54,7 +54,7 @@ func NewRestartableObjectStore(name string, sharedPluginProcess process.Restarta } // reinitialize reinitializes a re-dispensed plugin using the initial data passed to Init(). -func (r *restartableObjectStore) Reinitialize(dispensed interface{}) error { +func (r *restartableObjectStore) Reinitialize(dispensed any) error { objectStore, ok := dispensed.(velero.ObjectStore) if !ok { return errors.Errorf("plugin %T is not a ObjectStore", dispensed) diff --git a/pkg/plugin/clientmgmt/restartable_object_store_test.go b/pkg/plugin/clientmgmt/restartable_object_store_test.go index 04cdedda0e..38b92d9a06 100644 --- a/pkg/plugin/clientmgmt/restartable_object_store_test.go +++ b/pkg/plugin/clientmgmt/restartable_object_store_test.go @@ -35,7 +35,7 @@ import ( func TestRestartableGetObjectStore(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -189,7 +189,7 @@ func TestRestartableObjectStoreDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindObjectStore, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &restartableObjectStore{ key: key, sharedPluginProcess: p, @@ -200,39 +200,39 @@ func TestRestartableObjectStoreDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "PutObject", - Inputs: []interface{}{"bucket", "key", strings.NewReader("body")}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "key", strings.NewReader("body")}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "GetObject", - Inputs: []interface{}{"bucket", "key"}, - ExpectedErrorOutputs: []interface{}{nil, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{io.NopCloser(strings.NewReader("object")), errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "key"}, + ExpectedErrorOutputs: []any{nil, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{io.NopCloser(strings.NewReader("object")), errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "ListCommonPrefixes", - Inputs: []interface{}{"bucket", "prefix", "delimiter"}, - ExpectedErrorOutputs: []interface{}{([]string)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{[]string{"a", "b"}, errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "prefix", "delimiter"}, + ExpectedErrorOutputs: []any{([]string)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{[]string{"a", "b"}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "ListObjects", - Inputs: []interface{}{"bucket", "prefix"}, - ExpectedErrorOutputs: []interface{}{([]string)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{[]string{"a", "b"}, errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "prefix"}, + ExpectedErrorOutputs: []any{([]string)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{[]string{"a", "b"}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "DeleteObject", - Inputs: []interface{}{"bucket", "key"}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "key"}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "CreateSignedURL", - Inputs: []interface{}{"bucket", "key", 30 * time.Minute}, - ExpectedErrorOutputs: []interface{}{"", errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{"signedURL", errors.Errorf("delegate error")}, + Inputs: []any{"bucket", "key", 30 * time.Minute}, + ExpectedErrorOutputs: []any{"", errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{"signedURL", errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go b/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go index e00a6fddae..1cc5f24d84 100644 --- a/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go +++ b/pkg/plugin/clientmgmt/restoreitemaction/v1/restartable_restore_item_action_test.go @@ -35,7 +35,7 @@ import ( func TestRestartableGetRestoreItemAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -102,7 +102,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } @@ -115,7 +115,7 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { output := &velero.RestoreItemActionExecuteOutput{ UpdatedItem: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "green", }, }, @@ -124,7 +124,7 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindRestoreItemAction, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableRestoreItemAction{ Key: key, SharedPluginProcess: p, @@ -135,15 +135,15 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Execute", - Inputs: []interface{}{input}, - ExpectedErrorOutputs: []interface{}{nil, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{output, errors.Errorf("delegate error")}, + Inputs: []any{input}, + ExpectedErrorOutputs: []any{nil, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{output, errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go b/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go index 73d4f81455..cc36e4f644 100644 --- a/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go +++ b/pkg/plugin/clientmgmt/restoreitemaction/v2/restartable_restore_item_action_test.go @@ -35,7 +35,7 @@ import ( func TestRestartableGetRestoreItemAction(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -102,7 +102,7 @@ func TestRestartableRestoreItemActionGetDelegate(t *testing.T) { func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } @@ -115,7 +115,7 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { output := &velero.RestoreItemActionExecuteOutput{ UpdatedItem: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "green", }, }, @@ -127,7 +127,7 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindRestoreItemActionV2, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableRestoreItemAction{ Key: key, SharedPluginProcess: p, @@ -138,33 +138,33 @@ func TestRestartableRestoreItemActionDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "AppliesTo", - Inputs: []interface{}{}, - ExpectedErrorOutputs: []interface{}{velero.ResourceSelector{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, + Inputs: []any{}, + ExpectedErrorOutputs: []any{velero.ResourceSelector{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.ResourceSelector{IncludedNamespaces: []string{"a"}}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Execute", - Inputs: []interface{}{input}, - ExpectedErrorOutputs: []interface{}{nil, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{output, errors.Errorf("delegate error")}, + Inputs: []any{input}, + ExpectedErrorOutputs: []any{nil, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{output, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Progress", - Inputs: []interface{}{oid, r}, - ExpectedErrorOutputs: []interface{}{velero.OperationProgress{}, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{velero.OperationProgress{}, errors.Errorf("delegate error")}, + Inputs: []any{oid, r}, + ExpectedErrorOutputs: []any{velero.OperationProgress{}, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{velero.OperationProgress{}, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "Cancel", - Inputs: []interface{}{oid, r}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{oid, r}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "AreAdditionalItemsReady", - Inputs: []interface{}{additionalItems, r}, - ExpectedErrorOutputs: []interface{}{false, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{true, errors.Errorf("delegate error")}, + Inputs: []any{additionalItems, r}, + ExpectedErrorOutputs: []any{false, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{true, errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter.go b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter.go index a7d2b4223e..7aec39872c 100644 --- a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter.go +++ b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter.go @@ -69,7 +69,7 @@ func NewRestartableVolumeSnapshotter(name string, sharedPluginProcess process.Re } // reinitialize reinitializes a re-dispensed plugin using the initial data passed to Init(). -func (r *RestartableVolumeSnapshotter) Reinitialize(dispensed interface{}) error { +func (r *RestartableVolumeSnapshotter) Reinitialize(dispensed any) error { volumeSnapshotter, ok := dispensed.(vsv1.VolumeSnapshotter) if !ok { return errors.Errorf("plugin %T is not a VolumeSnapshotter", dispensed) diff --git a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go index eaa3862896..d090daeb70 100644 --- a/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go +++ b/pkg/plugin/clientmgmt/volumesnapshotter/v1/restartable_volume_snapshotter_test.go @@ -34,7 +34,7 @@ import ( func TestRestartableGetVolumeSnapshotter(t *testing.T) { tests := []struct { name string - plugin interface{} + plugin any getError error expectedError string }{ @@ -186,13 +186,13 @@ func TestRestartableVolumeSnapshotterInit(t *testing.T) { func TestRestartableVolumeSnapshotterDelegatedFunctions(t *testing.T) { pv := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "blue", }, } pvToReturn := &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "color": "green", }, } @@ -200,7 +200,7 @@ func TestRestartableVolumeSnapshotterDelegatedFunctions(t *testing.T) { restartabletest.RunRestartableDelegateTests( t, common.PluginKindVolumeSnapshotter, - func(key process.KindAndName, p process.RestartableProcess) interface{} { + func(key process.KindAndName, p process.RestartableProcess) any { return &RestartableVolumeSnapshotter{ Key: key, SharedPluginProcess: p, @@ -211,39 +211,39 @@ func TestRestartableVolumeSnapshotterDelegatedFunctions(t *testing.T) { }, restartabletest.RestartableDelegateTest{ Function: "CreateVolumeFromSnapshot", - Inputs: []interface{}{"snapshotID", "volumeID", "volumeAZ", to.Ptr(int64(10000))}, - ExpectedErrorOutputs: []interface{}{"", errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{"volumeID", errors.Errorf("delegate error")}, + Inputs: []any{"snapshotID", "volumeID", "volumeAZ", to.Ptr(int64(10000))}, + ExpectedErrorOutputs: []any{"", errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{"volumeID", errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "GetVolumeID", - Inputs: []interface{}{pv}, - ExpectedErrorOutputs: []interface{}{"", errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{"volumeID", errors.Errorf("delegate error")}, + Inputs: []any{pv}, + ExpectedErrorOutputs: []any{"", errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{"volumeID", errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "SetVolumeID", - Inputs: []interface{}{pv, "volumeID"}, - ExpectedErrorOutputs: []interface{}{nil, errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{pvToReturn, errors.Errorf("delegate error")}, + Inputs: []any{pv, "volumeID"}, + ExpectedErrorOutputs: []any{nil, errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{pvToReturn, errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "GetVolumeInfo", - Inputs: []interface{}{"volumeID", "volumeAZ"}, - ExpectedErrorOutputs: []interface{}{"", (*int64)(nil), errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{"volumeType", to.Ptr(int64(10000)), errors.Errorf("delegate error")}, + Inputs: []any{"volumeID", "volumeAZ"}, + ExpectedErrorOutputs: []any{"", (*int64)(nil), errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{"volumeType", to.Ptr(int64(10000)), errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "CreateSnapshot", - Inputs: []interface{}{"volumeID", "volumeAZ", map[string]string{"a": "b"}}, - ExpectedErrorOutputs: []interface{}{"", errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{"snapshotID", errors.Errorf("delegate error")}, + Inputs: []any{"volumeID", "volumeAZ", map[string]string{"a": "b"}}, + ExpectedErrorOutputs: []any{"", errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{"snapshotID", errors.Errorf("delegate error")}, }, restartabletest.RestartableDelegateTest{ Function: "DeleteSnapshot", - Inputs: []interface{}{"snapshotID"}, - ExpectedErrorOutputs: []interface{}{errors.Errorf("reset error")}, - ExpectedDelegateOutputs: []interface{}{errors.Errorf("delegate error")}, + Inputs: []any{"snapshotID"}, + ExpectedErrorOutputs: []any{errors.Errorf("reset error")}, + ExpectedDelegateOutputs: []any{errors.Errorf("delegate error")}, }, ) } diff --git a/pkg/plugin/framework/backup_item_action.go b/pkg/plugin/framework/backup_item_action.go index 8f6bc7554a..00f3cc0ea5 100644 --- a/pkg/plugin/framework/backup_item_action.go +++ b/pkg/plugin/framework/backup_item_action.go @@ -34,7 +34,7 @@ type BackupItemActionPlugin struct { } // GRPCClient returns a clientDispenser for BackupItemAction gRPC clients. -func (p *BackupItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *BackupItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newBackupItemActionGRPCClient), nil } diff --git a/pkg/plugin/framework/backup_item_action_client.go b/pkg/plugin/framework/backup_item_action_client.go index 50101975f9..948cb3492e 100644 --- a/pkg/plugin/framework/backup_item_action_client.go +++ b/pkg/plugin/framework/backup_item_action_client.go @@ -46,7 +46,7 @@ type BackupItemActionGRPCClient struct { grpcClient protobiav1.BackupItemActionClient } -func newBackupItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newBackupItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &BackupItemActionGRPCClient{ ClientBase: base, grpcClient: protobiav1.NewBackupItemActionClient(clientConn), diff --git a/pkg/plugin/framework/backup_item_action_test.go b/pkg/plugin/framework/backup_item_action_test.go index fb304072e0..59a1bbba84 100644 --- a/pkg/plugin/framework/backup_item_action_test.go +++ b/pkg/plugin/framework/backup_item_action_test.go @@ -156,7 +156,7 @@ func TestBackupItemActionGRPCServerExecute(t *testing.T) { s := &BackupItemActionGRPCServer{mux: &common.ServerMux{ ServerLog: velerotest.NewLogger(), - Handlers: map[string]interface{}{ + Handlers: map[string]any{ "xyz": itemAction, }, }} diff --git a/pkg/plugin/framework/backupitemaction/v2/backup_item_action.go b/pkg/plugin/framework/backupitemaction/v2/backup_item_action.go index a4efa9a2e1..c1e2e54018 100644 --- a/pkg/plugin/framework/backupitemaction/v2/backup_item_action.go +++ b/pkg/plugin/framework/backupitemaction/v2/backup_item_action.go @@ -34,7 +34,7 @@ type BackupItemActionPlugin struct { } // GRPCClient returns a clientDispenser for BackupItemAction gRPC clients. -func (p *BackupItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *BackupItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newBackupItemActionGRPCClient), nil } diff --git a/pkg/plugin/framework/backupitemaction/v2/backup_item_action_client.go b/pkg/plugin/framework/backupitemaction/v2/backup_item_action_client.go index d5a154b5fb..52733de2d9 100644 --- a/pkg/plugin/framework/backupitemaction/v2/backup_item_action_client.go +++ b/pkg/plugin/framework/backupitemaction/v2/backup_item_action_client.go @@ -46,7 +46,7 @@ type BackupItemActionGRPCClient struct { grpcClient protobiav2.BackupItemActionClient } -func newBackupItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newBackupItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &BackupItemActionGRPCClient{ ClientBase: base, grpcClient: protobiav2.NewBackupItemActionClient(clientConn), diff --git a/pkg/plugin/framework/backupitemaction/v2/backup_item_action_test.go b/pkg/plugin/framework/backupitemaction/v2/backup_item_action_test.go index 82d70a8e84..47f69dea95 100644 --- a/pkg/plugin/framework/backupitemaction/v2/backup_item_action_test.go +++ b/pkg/plugin/framework/backupitemaction/v2/backup_item_action_test.go @@ -159,7 +159,7 @@ func TestBackupItemActionGRPCServerExecute(t *testing.T) { s := &BackupItemActionGRPCServer{mux: &common.ServerMux{ ServerLog: velerotest.NewLogger(), - Handlers: map[string]interface{}{ + Handlers: map[string]any{ "xyz": itemAction, }, }} diff --git a/pkg/plugin/framework/common/client_dispenser.go b/pkg/plugin/framework/common/client_dispenser.go index 1abb11c2df..bff8b90ae5 100644 --- a/pkg/plugin/framework/common/client_dispenser.go +++ b/pkg/plugin/framework/common/client_dispenser.go @@ -28,7 +28,7 @@ type ClientBase struct { } type ClientDispenser interface { - ClientFor(name string) interface{} + ClientFor(name string) any } // clientDispenser supports the initialization and retrieval of multiple implementations for a single plugin kind, such as @@ -41,10 +41,10 @@ type clientDispenser struct { // initFunc returns a client that implements a plugin interface, such as ObjectStore. initFunc clientInitFunc // clients keeps track of all the initialized implementations. - clients map[string]interface{} + clients map[string]any } -type clientInitFunc func(base *ClientBase, clientConn *grpc.ClientConn) interface{} +type clientInitFunc func(base *ClientBase, clientConn *grpc.ClientConn) any // newClientDispenser creates a new clientDispenser. func NewClientDispenser(logger logrus.FieldLogger, clientConn *grpc.ClientConn, initFunc clientInitFunc) *clientDispenser { @@ -52,13 +52,13 @@ func NewClientDispenser(logger logrus.FieldLogger, clientConn *grpc.ClientConn, clientConn: clientConn, logger: logger, initFunc: initFunc, - clients: make(map[string]interface{}), + clients: make(map[string]any), } } // ClientFor returns a gRPC client stub for the implementation of a plugin named name. If the client stub does not // currently exist, clientFor creates it. -func (cd *clientDispenser) ClientFor(name string) interface{} { +func (cd *clientDispenser) ClientFor(name string) any { if client, found := cd.clients[name]; found { return client } diff --git a/pkg/plugin/framework/common/client_dispenser_test.go b/pkg/plugin/framework/common/client_dispenser_test.go index 3a33774987..3aa0cd2995 100644 --- a/pkg/plugin/framework/common/client_dispenser_test.go +++ b/pkg/plugin/framework/common/client_dispenser_test.go @@ -36,7 +36,7 @@ func TestNewClientDispenser(t *testing.T) { clientConn := new(grpc.ClientConn) c := 3 - initFunc := func(base *ClientBase, clientConn *grpc.ClientConn) interface{} { + initFunc := func(base *ClientBase, clientConn *grpc.ClientConn) any { return c } @@ -52,7 +52,7 @@ func TestClientFor(t *testing.T) { c := new(fakeClient) count := 0 - initFunc := func(base *ClientBase, clientConn *grpc.ClientConn) interface{} { + initFunc := func(base *ClientBase, clientConn *grpc.ClientConn) any { c.base = base c.clientConn = clientConn count++ diff --git a/pkg/plugin/framework/common/client_errors.go b/pkg/plugin/framework/common/client_errors.go index 377851aa8f..1d9e6c22f9 100644 --- a/pkg/plugin/framework/common/client_errors.go +++ b/pkg/plugin/framework/common/client_errors.go @@ -37,8 +37,7 @@ func FromGRPCError(err error) error { } for _, detail := range statusErr.Details() { - switch t := detail.(type) { - case *proto.Stack: + if t, ok := detail.(*proto.Stack); ok { return &ProtoStackError{ error: err, stack: t, diff --git a/pkg/plugin/framework/common/handle_panic.go b/pkg/plugin/framework/common/handle_panic.go index e4324898dd..697ff588c0 100644 --- a/pkg/plugin/framework/common/handle_panic.go +++ b/pkg/plugin/framework/common/handle_panic.go @@ -24,7 +24,7 @@ import ( ) // HandlePanic is a panic handler for the server half of velero plugins. -func HandlePanic(p interface{}) error { +func HandlePanic(p any) error { if p == nil { return nil } diff --git a/pkg/plugin/framework/common/server_errors.go b/pkg/plugin/framework/common/server_errors.go index 60eff50f43..2b2c100b5f 100644 --- a/pkg/plugin/framework/common/server_errors.go +++ b/pkg/plugin/framework/common/server_errors.go @@ -17,6 +17,8 @@ limitations under the License. package common import ( + "math" + "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -72,7 +74,7 @@ func ErrorStack(err error) *proto.Stack { stackTrace.Frames = append(stackTrace.Frames, &proto.StackFrame{ File: location.File, - Line: int32(location.Line), + Line: int32(min(location.Line, math.MaxInt32)), Function: location.Function, }) } diff --git a/pkg/plugin/framework/common/server_mux.go b/pkg/plugin/framework/common/server_mux.go index 960975c7e6..4eecdb8d21 100644 --- a/pkg/plugin/framework/common/server_mux.go +++ b/pkg/plugin/framework/common/server_mux.go @@ -27,13 +27,13 @@ import ( // HandlerInitializer is a function that initializes and returns a new instance of one of Velero's plugin interfaces // (ObjectStore, VolumeSnapshotter, BackupItemAction, RestoreItemAction). -type HandlerInitializer func(logger logrus.FieldLogger) (interface{}, error) +type HandlerInitializer func(logger logrus.FieldLogger) (any, error) // ServerMux manages multiple implementations of a single plugin kind, such as pod and pvc BackupItemActions. type ServerMux struct { kind PluginKind initializers map[string]HandlerInitializer - Handlers map[string]interface{} + Handlers map[string]any ServerLog logrus.FieldLogger } @@ -41,7 +41,7 @@ type ServerMux struct { func NewServerMux(logger logrus.FieldLogger) *ServerMux { return &ServerMux{ initializers: make(map[string]HandlerInitializer), - Handlers: make(map[string]interface{}), + Handlers: make(map[string]any), ServerLog: logger, } } @@ -63,7 +63,7 @@ func (m *ServerMux) Names() []string { // GetHandler returns the instance for a plugin with the given name. If an instance has already been initialized, // that is returned. Otherwise, the instance is initialized by calling its initialization function. -func (m *ServerMux) GetHandler(name string) (interface{}, error) { +func (m *ServerMux) GetHandler(name string) (any, error) { if instance, found := m.Handlers[name]; found { return instance, nil } diff --git a/pkg/plugin/framework/delete_item_action.go b/pkg/plugin/framework/delete_item_action.go index c6c0f6bbb1..afc5d548ed 100644 --- a/pkg/plugin/framework/delete_item_action.go +++ b/pkg/plugin/framework/delete_item_action.go @@ -34,7 +34,7 @@ type DeleteItemActionPlugin struct { } // GRPCClient returns a DeleteItemAction gRPC client. -func (p *DeleteItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *DeleteItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newDeleteItemActionGRPCClient), nil } diff --git a/pkg/plugin/framework/delete_item_action_client.go b/pkg/plugin/framework/delete_item_action_client.go index 4241d0b33c..088c42b511 100644 --- a/pkg/plugin/framework/delete_item_action_client.go +++ b/pkg/plugin/framework/delete_item_action_client.go @@ -44,7 +44,7 @@ type DeleteItemActionGRPCClient struct { grpcClient proto.DeleteItemActionClient } -func newDeleteItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newDeleteItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &DeleteItemActionGRPCClient{ ClientBase: base, grpcClient: proto.NewDeleteItemActionClient(clientConn), diff --git a/pkg/plugin/framework/examples_test.go b/pkg/plugin/framework/examples_test.go index 16ce5bd492..41bb8395ec 100644 --- a/pkg/plugin/framework/examples_test.go +++ b/pkg/plugin/framework/examples_test.go @@ -30,7 +30,7 @@ func ExampleNewServer_volumeSnapshotter() { Serve() // serve the plugin } -func newVolumeSnapshotter(logger logrus.FieldLogger) (interface{}, error) { +func newVolumeSnapshotter(logger logrus.FieldLogger) (any, error) { return &VolumeSnapshotter{FieldLogger: logger}, nil } @@ -97,7 +97,7 @@ func (b *VolumeSnapshotter) DeleteSnapshot(snapshotID string) error { // Implement all methods for the DeleteItemAction interface -func newDeleteItemAction(logger logrus.FieldLogger) (interface{}, error) { +func newDeleteItemAction(logger logrus.FieldLogger) (any, error) { return DeleteItemAction{FieldLogger: logger}, nil } diff --git a/pkg/plugin/framework/itemblockaction/v1/item_block_action.go b/pkg/plugin/framework/itemblockaction/v1/item_block_action.go index dfe7a83b48..9fb8094ee2 100644 --- a/pkg/plugin/framework/itemblockaction/v1/item_block_action.go +++ b/pkg/plugin/framework/itemblockaction/v1/item_block_action.go @@ -34,7 +34,7 @@ type ItemBlockActionPlugin struct { } // GRPCClient returns a clientDispenser for ItemBlockAction gRPC clients. -func (p *ItemBlockActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *ItemBlockActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newItemBlockActionGRPCClient), nil } diff --git a/pkg/plugin/framework/itemblockaction/v1/item_block_action_client.go b/pkg/plugin/framework/itemblockaction/v1/item_block_action_client.go index 06287da33c..612a14a6cc 100644 --- a/pkg/plugin/framework/itemblockaction/v1/item_block_action_client.go +++ b/pkg/plugin/framework/itemblockaction/v1/item_block_action_client.go @@ -45,7 +45,7 @@ type ItemBlockActionGRPCClient struct { grpcClient protoibav1.ItemBlockActionClient } -func newItemBlockActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newItemBlockActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &ItemBlockActionGRPCClient{ ClientBase: base, grpcClient: protoibav1.NewItemBlockActionClient(clientConn), diff --git a/pkg/plugin/framework/itemblockaction/v1/item_block_action_test.go b/pkg/plugin/framework/itemblockaction/v1/item_block_action_test.go index ecfa693ae2..4397821cb5 100644 --- a/pkg/plugin/framework/itemblockaction/v1/item_block_action_test.go +++ b/pkg/plugin/framework/itemblockaction/v1/item_block_action_test.go @@ -132,7 +132,7 @@ func TestItemBlockActionGRPCServerGetRelatedItems(t *testing.T) { s := &ItemBlockActionGRPCServer{mux: &common.ServerMux{ ServerLog: velerotest.NewLogger(), - Handlers: map[string]interface{}{ + Handlers: map[string]any{ "xyz": itemAction, }, }} diff --git a/pkg/plugin/framework/object_store.go b/pkg/plugin/framework/object_store.go index ad246ede8e..d7c7b95e4d 100644 --- a/pkg/plugin/framework/object_store.go +++ b/pkg/plugin/framework/object_store.go @@ -34,7 +34,7 @@ type ObjectStorePlugin struct { } // GRPCClient returns an ObjectStore gRPC client. -func (p *ObjectStorePlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *ObjectStorePlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newObjectStoreGRPCClient), nil } diff --git a/pkg/plugin/framework/object_store_client.go b/pkg/plugin/framework/object_store_client.go index 3cc5cd6e99..725f8e934d 100644 --- a/pkg/plugin/framework/object_store_client.go +++ b/pkg/plugin/framework/object_store_client.go @@ -44,7 +44,7 @@ type ObjectStoreGRPCClient struct { grpcClient proto.ObjectStoreClient } -func newObjectStoreGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newObjectStoreGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &ObjectStoreGRPCClient{ ClientBase: base, grpcClient: proto.NewObjectStoreClient(clientConn), diff --git a/pkg/plugin/framework/plugin_lister.go b/pkg/plugin/framework/plugin_lister.go index e658ae8a21..19e3490070 100644 --- a/pkg/plugin/framework/plugin_lister.go +++ b/pkg/plugin/framework/plugin_lister.go @@ -69,7 +69,7 @@ func NewPluginListerPlugin(impl PluginLister) *PluginListerPlugin { ////////////////////////////////////////////////////////////////////////////// // GRPCClient returns a PluginLister gRPC client. -func (p *PluginListerPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *PluginListerPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return &PluginListerGRPCClient{grpcClient: proto.NewPluginListerClient(clientConn)}, nil } diff --git a/pkg/plugin/framework/plugin_types_test.go b/pkg/plugin/framework/plugin_types_test.go index f9b4d1f809..8ec8318f0f 100644 --- a/pkg/plugin/framework/plugin_types_test.go +++ b/pkg/plugin/framework/plugin_types_test.go @@ -24,7 +24,7 @@ import ( ) func TestPluginImplementationsAreGRPCPlugins(t *testing.T) { - pluginImpls := []interface{}{ + pluginImpls := []any{ new(VolumeSnapshotterPlugin), new(BackupItemActionPlugin), new(ObjectStorePlugin), diff --git a/pkg/plugin/framework/restore_item_action.go b/pkg/plugin/framework/restore_item_action.go index b5a3d41c16..0aaf2b47ed 100644 --- a/pkg/plugin/framework/restore_item_action.go +++ b/pkg/plugin/framework/restore_item_action.go @@ -34,7 +34,7 @@ type RestoreItemActionPlugin struct { } // GRPCClient returns a RestoreItemAction gRPC client. -func (p *RestoreItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *RestoreItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newRestoreItemActionGRPCClient), nil } diff --git a/pkg/plugin/framework/restore_item_action_client.go b/pkg/plugin/framework/restore_item_action_client.go index 75490d4c2f..8809e31c3d 100644 --- a/pkg/plugin/framework/restore_item_action_client.go +++ b/pkg/plugin/framework/restore_item_action_client.go @@ -47,7 +47,7 @@ type RestoreItemActionGRPCClient struct { grpcClient proto.RestoreItemActionClient } -func newRestoreItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newRestoreItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &RestoreItemActionGRPCClient{ ClientBase: base, grpcClient: proto.NewRestoreItemActionClient(clientConn), diff --git a/pkg/plugin/framework/restoreitemaction/v2/restore_item_action.go b/pkg/plugin/framework/restoreitemaction/v2/restore_item_action.go index 13ec1b851d..243e2fd678 100644 --- a/pkg/plugin/framework/restoreitemaction/v2/restore_item_action.go +++ b/pkg/plugin/framework/restoreitemaction/v2/restore_item_action.go @@ -34,7 +34,7 @@ type RestoreItemActionPlugin struct { } // GRPCClient returns a RestoreItemAction gRPC client. -func (p *RestoreItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *RestoreItemActionPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newRestoreItemActionGRPCClient), nil } diff --git a/pkg/plugin/framework/restoreitemaction/v2/restore_item_action_client.go b/pkg/plugin/framework/restoreitemaction/v2/restore_item_action_client.go index 4abb2c9969..b1d61fb75c 100644 --- a/pkg/plugin/framework/restoreitemaction/v2/restore_item_action_client.go +++ b/pkg/plugin/framework/restoreitemaction/v2/restore_item_action_client.go @@ -48,7 +48,7 @@ type RestoreItemActionGRPCClient struct { grpcClient protoriav2.RestoreItemActionClient } -func newRestoreItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newRestoreItemActionGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &RestoreItemActionGRPCClient{ ClientBase: base, grpcClient: protoriav2.NewRestoreItemActionClient(clientConn), diff --git a/pkg/plugin/framework/volume_snapshotter.go b/pkg/plugin/framework/volume_snapshotter.go index 566fc1eb72..5eb6159eb5 100644 --- a/pkg/plugin/framework/volume_snapshotter.go +++ b/pkg/plugin/framework/volume_snapshotter.go @@ -34,7 +34,7 @@ type VolumeSnapshotterPlugin struct { } // GRPCClient returns a VolumeSnapshotter gRPC client. -func (p *VolumeSnapshotterPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (interface{}, error) { +func (p *VolumeSnapshotterPlugin) GRPCClient(_ context.Context, _ *plugin.GRPCBroker, clientConn *grpc.ClientConn) (any, error) { return common.NewClientDispenser(p.ClientLogger, clientConn, newVolumeSnapshotterGRPCClient), nil } diff --git a/pkg/plugin/framework/volume_snapshotter_client.go b/pkg/plugin/framework/volume_snapshotter_client.go index a359046177..da66f2cea2 100644 --- a/pkg/plugin/framework/volume_snapshotter_client.go +++ b/pkg/plugin/framework/volume_snapshotter_client.go @@ -43,7 +43,7 @@ type VolumeSnapshotterGRPCClient struct { grpcClient proto.VolumeSnapshotterClient } -func newVolumeSnapshotterGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) interface{} { +func newVolumeSnapshotterGRPCClient(base *common.ClientBase, clientConn *grpc.ClientConn) any { return &VolumeSnapshotterGRPCClient{ ClientBase: base, grpcClient: proto.NewVolumeSnapshotterClient(clientConn), diff --git a/pkg/podexec/pod_command_executor.go b/pkg/podexec/pod_command_executor.go index 60793aebd3..b1d7fbf59a 100644 --- a/pkg/podexec/pod_command_executor.go +++ b/pkg/podexec/pod_command_executor.go @@ -39,7 +39,7 @@ const defaultTimeout = 30 * time.Second type PodCommandExecutor interface { // ExecutePodCommand executes a command in a container in a pod. If the command takes longer than // the specified timeout, an error is returned. - ExecutePodCommand(log logrus.FieldLogger, item map[string]interface{}, namespace, name, hookName string, hook *api.ExecHook) error + ExecutePodCommand(log logrus.FieldLogger, item map[string]any, namespace, name, hookName string, hook *api.ExecHook) error } type poster interface { @@ -67,7 +67,7 @@ func NewPodCommandExecutor(restClientConfig *rest.Config, restClient poster) Pod // command takes longer than the specified timeout, an error is returned (NOTE: it is not currently // possible to ensure the command is terminated when the timeout occurs, so it may continue to run // in the background). -func (e *defaultPodCommandExecutor) ExecutePodCommand(log logrus.FieldLogger, item map[string]interface{}, namespace, name, hookName string, hook *api.ExecHook) error { +func (e *defaultPodCommandExecutor) ExecutePodCommand(log logrus.FieldLogger, item map[string]any, namespace, name, hookName string, hook *api.ExecHook) error { if item == nil { return errors.New("item is required") } diff --git a/pkg/podexec/pod_command_executor_test.go b/pkg/podexec/pod_command_executor_test.go index 150c1babdf..ad22a302ca 100644 --- a/pkg/podexec/pod_command_executor_test.go +++ b/pkg/podexec/pod_command_executor_test.go @@ -52,7 +52,7 @@ func TestNewPodCommandExecutor(t *testing.T) { func TestExecutePodCommandMissingInputs(t *testing.T) { tests := []struct { name string - item map[string]interface{} + item map[string]any podNamespace string podName string hookName string @@ -63,22 +63,22 @@ func TestExecutePodCommandMissingInputs(t *testing.T) { }, { name: "missing pod namespace", - item: map[string]interface{}{}, + item: map[string]any{}, }, { name: "missing pod name", - item: map[string]interface{}{}, + item: map[string]any{}, podNamespace: "ns", }, { name: "missing hookName", - item: map[string]interface{}{}, + item: map[string]any{}, podNamespace: "ns", podName: "pod", }, { name: "missing hook", - item: map[string]interface{}{}, + item: map[string]any{}, podNamespace: "ns", podName: "pod", hookName: "hook", diff --git a/pkg/podvolume/backupper.go b/pkg/podvolume/backupper.go index 471cdb1a0c..780ae12e1b 100644 --- a/pkg/podvolume/backupper.go +++ b/pkg/podvolume/backupper.go @@ -157,7 +157,7 @@ func newBackupper( b.handlerRegistration, _ = pvbInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { pvb, ok := obj.(*velerov1api.PodVolumeBackup) if !ok { log.Errorf("expected PodVolumeBackup, but got %T", obj) diff --git a/pkg/podvolume/restorer.go b/pkg/podvolume/restorer.go index 4b3e4354dd..2e806b27ea 100644 --- a/pkg/podvolume/restorer.go +++ b/pkg/podvolume/restorer.go @@ -92,7 +92,7 @@ func newRestorer( _, _ = pvrInformer.AddEventHandler( cache.ResourceEventHandlerFuncs{ - UpdateFunc: func(_, obj interface{}) { + UpdateFunc: func(_, obj any) { pvr := obj.(*velerov1api.PodVolumeRestore) if pvr.GetLabels()[velerov1api.RestoreUIDLabel] != string(restore.UID) { return diff --git a/pkg/repository/provider/unified_repo.go b/pkg/repository/provider/unified_repo.go index 6191c44528..4b4e4325fd 100644 --- a/pkg/repository/provider/unified_repo.go +++ b/pkg/repository/provider/unified_repo.go @@ -368,7 +368,7 @@ func (urp *unifiedRepoProvider) DefaultMaintenanceFrequency(ctx context.Context, return urp.repoService.DefaultMaintenanceFrequency() } -func (urp *unifiedRepoProvider) GetPassword(param interface{}) (string, error) { +func (urp *unifiedRepoProvider) GetPassword(param any) (string, error) { _, ok := param.(RepoParam) if !ok { return "", errors.Errorf("invalid parameter, expect %T, actual %T", RepoParam{}, param) @@ -382,7 +382,7 @@ func (urp *unifiedRepoProvider) GetPassword(param interface{}) (string, error) { return repoPassword, nil } -func (urp *unifiedRepoProvider) GetStoreType(param interface{}) (string, error) { +func (urp *unifiedRepoProvider) GetStoreType(param any) (string, error) { repoParam, ok := param.(RepoParam) if !ok { return "", errors.Errorf("invalid parameter, expect %T, actual %T", RepoParam{}, param) @@ -391,7 +391,7 @@ func (urp *unifiedRepoProvider) GetStoreType(param interface{}) (string, error) return getStorageType(repoParam.BackupLocation), nil } -func (urp *unifiedRepoProvider) GetStoreOptions(param interface{}) (map[string]string, error) { +func (urp *unifiedRepoProvider) GetStoreOptions(param any) (map[string]string, error) { repoParam, ok := param.(RepoParam) if !ok { return map[string]string{}, errors.Errorf("invalid parameter, expect %T, actual %T", RepoParam{}, param) diff --git a/pkg/repository/provider/unified_repo_test.go b/pkg/repository/provider/unified_repo_test.go index 6f87858489..733e52763c 100644 --- a/pkg/repository/provider/unified_repo_test.go +++ b/pkg/repository/provider/unified_repo_test.go @@ -537,7 +537,7 @@ func TestGetStoreOptions(t *testing.T) { testCases := []struct { name string funcTable localFuncTable - repoParam interface{} + repoParam any expected map[string]string expectedErr string }{ @@ -741,9 +741,9 @@ func TestForget(t *testing.T) { getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService backupRepo *reposervicenmocks.BackupRepo - retFuncOpen []interface{} - retFuncDelete interface{} - retFuncFlush interface{} + retFuncOpen []any + retFuncDelete any + retFuncFlush any credStoreReturn string credStoreError error expectedErr string @@ -765,7 +765,7 @@ func TestForget(t *testing.T) { }, }, repoService: new(reposervicenmocks.BackupRepoService), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -790,7 +790,7 @@ func TestForget(t *testing.T) { }, repoService: new(reposervicenmocks.BackupRepoService), backupRepo: new(reposervicenmocks.BackupRepo), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -818,7 +818,7 @@ func TestForget(t *testing.T) { }, repoService: new(reposervicenmocks.BackupRepoService), backupRepo: new(reposervicenmocks.BackupRepo), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -890,9 +890,9 @@ func TestBatchForget(t *testing.T) { getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService backupRepo *reposervicenmocks.BackupRepo - retFuncOpen []interface{} - retFuncDelete interface{} - retFuncFlush interface{} + retFuncOpen []any + retFuncDelete any + retFuncFlush any credStoreReturn string credStoreError error snapshots []string @@ -915,7 +915,7 @@ func TestBatchForget(t *testing.T) { }, }, repoService: new(reposervicenmocks.BackupRepoService), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -940,7 +940,7 @@ func TestBatchForget(t *testing.T) { }, repoService: new(reposervicenmocks.BackupRepoService), backupRepo: new(reposervicenmocks.BackupRepo), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -969,7 +969,7 @@ func TestBatchForget(t *testing.T) { }, repoService: new(reposervicenmocks.BackupRepoService), backupRepo: new(reposervicenmocks.BackupRepo), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -1042,7 +1042,7 @@ func TestInitRepo(t *testing.T) { funcTable localFuncTable getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService - retFuncInit interface{} + retFuncInit any credStoreReturn string credStoreError error expectedErr string @@ -1130,7 +1130,7 @@ func TestConnectToRepo(t *testing.T) { funcTable localFuncTable getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService - retFuncInit interface{} + retFuncInit any credStoreReturn string credStoreError error expectedErr string @@ -1221,8 +1221,8 @@ func TestBoostRepoConnect(t *testing.T) { getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService backupRepo *reposervicenmocks.BackupRepo - retFuncInit interface{} - retFuncOpen []interface{} + retFuncInit any + retFuncOpen []any credStoreReturn string credStoreError error expectedErr string @@ -1244,7 +1244,7 @@ func TestBoostRepoConnect(t *testing.T) { }, }, repoService: new(reposervicenmocks.BackupRepoService), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -1271,7 +1271,7 @@ func TestBoostRepoConnect(t *testing.T) { }, }, repoService: new(reposervicenmocks.BackupRepoService), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -1298,7 +1298,7 @@ func TestBoostRepoConnect(t *testing.T) { }, repoService: new(reposervicenmocks.BackupRepoService), backupRepo: new(reposervicenmocks.BackupRepo), - retFuncOpen: []interface{}{ + retFuncOpen: []any{ func(context.Context, udmrepo.RepoOptions) udmrepo.BackupRepo { return backupRepo }, @@ -1362,7 +1362,7 @@ func TestPruneRepo(t *testing.T) { funcTable localFuncTable getter *credmock.SecretStore repoService *reposervicenmocks.BackupRepoService - retFuncMaintain interface{} + retFuncMaintain any credStoreReturn string credStoreError error expectedErr string diff --git a/pkg/repository/udmrepo/kopialib/lib_repo.go b/pkg/repository/udmrepo/kopialib/lib_repo.go index e203949c37..ece4d1416a 100644 --- a/pkg/repository/udmrepo/kopialib/lib_repo.go +++ b/pkg/repository/udmrepo/kopialib/lib_repo.go @@ -18,6 +18,7 @@ package kopialib import ( "context" + "math" "os" "strings" "sync/atomic" @@ -515,7 +516,7 @@ func (kow *kopiaObjectWriter) Close() error { } // getCompressorForObject returns the compressor for an object, at present, we don't support compression -func getCompressorForObject(opt udmrepo.ObjectWriteOptions) compression.Name { +func getCompressorForObject(_ udmrepo.ObjectWriteOptions) compression.Name { return "" } @@ -523,7 +524,7 @@ func getManifestEntryFromKopia(mani *manifest.EntryMetadata) *udmrepo.ManifestEn return &udmrepo.ManifestEntryMetadata{ ID: udmrepo.ID(mani.ID), Labels: mani.Labels, - Length: int32(mani.Length), + Length: int32(min(mani.Length, math.MaxInt32)), ModTime: mani.ModTime, } } @@ -535,7 +536,7 @@ func getManifestEntriesFromKopia(mani []*manifest.EntryMetadata) []*udmrepo.Mani ret = append(ret, &udmrepo.ManifestEntryMetadata{ ID: udmrepo.ID(entry.ID), Labels: entry.Labels, - Length: int32(entry.Length), + Length: int32(min(entry.Length, math.MaxInt32)), ModTime: entry.ModTime, }) } diff --git a/pkg/repository/udmrepo/repo.go b/pkg/repository/udmrepo/repo.go index db32d09535..0adb397510 100644 --- a/pkg/repository/udmrepo/repo.go +++ b/pkg/repository/udmrepo/repo.go @@ -33,7 +33,7 @@ type ManifestEntryMetadata struct { } type RepoManifest struct { - Payload interface{} // The user data of manifest + Payload any // The user data of manifest Metadata *ManifestEntryMetadata // The metadata data of manifest } diff --git a/pkg/repository/udmrepo/repo_options.go b/pkg/repository/udmrepo/repo_options.go index 28eadfdb9b..bb72303a8d 100644 --- a/pkg/repository/udmrepo/repo_options.go +++ b/pkg/repository/udmrepo/repo_options.go @@ -96,13 +96,13 @@ type RepoOptions struct { // PasswordGetter defines the method to get a repository password. type PasswordGetter interface { - GetPassword(param interface{}) (string, error) + GetPassword(param any) (string, error) } // StoreOptionsGetter defines the methods to get the storage related options. type StoreOptionsGetter interface { - GetStoreType(param interface{}) (string, error) - GetStoreOptions(param interface{}) (map[string]string, error) + GetStoreType(param any) (string, error) + GetStoreOptions(param any) (map[string]string, error) } // NewRepoOptions creates a new RepoOptions for different purpose @@ -124,7 +124,7 @@ func NewRepoOptions(optionFuncs ...func(*RepoOptions) error) (*RepoOptions, erro // WithPassword sets the RepoPassword to RepoOptions, the password is acquired through // the provided interface -func WithPassword(getter PasswordGetter, param interface{}) func(*RepoOptions) error { +func WithPassword(getter PasswordGetter, param any) func(*RepoOptions) error { return func(options *RepoOptions) error { password, err := getter.GetPassword(param) if err != nil { @@ -158,7 +158,7 @@ func WithGenOptions(genOptions map[string]string) func(*RepoOptions) error { // WithStoreOptions sets the StorageOptions to RepoOptions, the store options are acquired through // the provided interface -func WithStoreOptions(getter StoreOptionsGetter, param interface{}) func(*RepoOptions) error { +func WithStoreOptions(getter StoreOptionsGetter, param any) func(*RepoOptions) error { return func(options *RepoOptions) error { storeType, err := getter.GetStoreType(param) if err != nil { diff --git a/pkg/restore/actions/admissionwebhook_config_action.go b/pkg/restore/actions/admissionwebhook_config_action.go index c6c9676999..82599dc62f 100644 --- a/pkg/restore/actions/admissionwebhook_config_action.go +++ b/pkg/restore/actions/admissionwebhook_config_action.go @@ -69,7 +69,7 @@ func (a *AdmissionWebhookConfigurationAction) Execute(input *velero.RestoreItemA logger.Info("webhooks is not set, skip") return velero.NewRestoreItemActionExecuteOutput(input.Item), nil } - newWebhooks := make([]interface{}, 0) + newWebhooks := make([]any, 0) for i := range webhooks { logger2 := logger.WithField("index", i) obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&webhooks[i]) diff --git a/pkg/restore/actions/admissionwebhook_config_action_test.go b/pkg/restore/actions/admissionwebhook_config_action_test.go index fb0205cb4e..4daad1c088 100644 --- a/pkg/restore/actions/admissionwebhook_config_action_test.go +++ b/pkg/restore/actions/admissionwebhook_config_action_test.go @@ -177,7 +177,7 @@ func TestNewAdmissionWebhookConfigurationActionExecute(t *testing.T) { } for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { - o := map[string]interface{}{} + o := map[string]any{} json.Unmarshal([]byte(tt.itemJSON), &o) input := &velero.RestoreItemActionExecuteInput{ Item: &unstructured.Unstructured{ diff --git a/pkg/restore/actions/change_image_name_action.go b/pkg/restore/actions/change_image_name_action.go index 66fac1f186..c705ddfa35 100644 --- a/pkg/restore/actions/change_image_name_action.go +++ b/pkg/restore/actions/change_image_name_action.go @@ -145,7 +145,7 @@ func (a *ChangeImageNameAction) Execute(input *velero.RestoreItemActionExecuteIn } func (a *ChangeImageNameAction) replaceImageName(obj *unstructured.Unstructured, config *corev1.ConfigMap, filed ...string) error { - log := a.logger.WithFields(map[string]interface{}{ + log := a.logger.WithFields(map[string]any{ "kind": obj.GetKind(), "namespace": obj.GetNamespace(), "name": obj.GetName(), @@ -161,12 +161,12 @@ func (a *ChangeImageNameAction) replaceImageName(obj *unstructured.Unstructured, } for i, container := range containers { log.Infoln("container:", container) - if image, ok := container.(map[string]interface{})["image"]; ok { + if image, ok := container.(map[string]any)["image"]; ok { imageName := image.(string) if exists, newImageName, err := a.isImageReplaceRuleExist(log, imageName, config); exists && err == nil { needUpdateObj = true log.Infof("Updating item's image from %s to %s", imageName, newImageName) - container.(map[string]interface{})["image"] = newImageName + container.(map[string]any)["image"] = newImageName containers[i] = container } } diff --git a/pkg/restore/actions/change_image_name_action_test.go b/pkg/restore/actions/change_image_name_action_test.go index 134fc154ce..75f9b5939d 100644 --- a/pkg/restore/actions/change_image_name_action_test.go +++ b/pkg/restore/actions/change_image_name_action_test.go @@ -40,11 +40,11 @@ import ( func TestChangeImageRepositoryActionExecute(t *testing.T) { tests := []struct { name string - podOrObj interface{} + podOrObj any configMap *corev1.ConfigMap freshedImageName string imageNameSlice []string - want interface{} + want any wantErr error }{ { diff --git a/pkg/restore/actions/change_pvc_node_selector.go b/pkg/restore/actions/change_pvc_node_selector.go index 2888b6b2da..64d5ceb3f5 100644 --- a/pkg/restore/actions/change_pvc_node_selector.go +++ b/pkg/restore/actions/change_pvc_node_selector.go @@ -81,7 +81,7 @@ func (p *ChangePVCNodeSelectorAction) Execute(input *velero.RestoreItemActionExe return velero.NewRestoreItemActionExecuteOutput(input.Item), nil } - log := p.logger.WithFields(map[string]interface{}{ + log := p.logger.WithFields(map[string]any{ "kind": typeAcc.GetKind(), "namespace": metadata.GetNamespace(), "name": metadata.GetName(), diff --git a/pkg/restore/actions/change_storageclass_action.go b/pkg/restore/actions/change_storageclass_action.go index b4052eb2dc..5743042fa4 100644 --- a/pkg/restore/actions/change_storageclass_action.go +++ b/pkg/restore/actions/change_storageclass_action.go @@ -84,7 +84,7 @@ func (a *ChangeStorageClassAction) Execute(input *velero.RestoreItemActionExecut return nil, errors.Errorf("object was of unexpected type %T", input.Item) } - log := a.logger.WithFields(map[string]interface{}{ + log := a.logger.WithFields(map[string]any{ "kind": obj.GetKind(), "namespace": obj.GetNamespace(), "name": obj.GetName(), diff --git a/pkg/restore/actions/change_storageclass_action_test.go b/pkg/restore/actions/change_storageclass_action_test.go index 4d32a6bade..686be146f2 100644 --- a/pkg/restore/actions/change_storageclass_action_test.go +++ b/pkg/restore/actions/change_storageclass_action_test.go @@ -42,11 +42,11 @@ import ( func TestChangeStorageClassActionExecute(t *testing.T) { tests := []struct { name string - pvOrPvcOrSTS interface{} + pvOrPvcOrSTS any configMap *corev1api.ConfigMap storageClass *storagev1api.StorageClass storageClassSlice []*storagev1api.StorageClass - want interface{} + want any wantErr error }{ { diff --git a/pkg/restore/actions/crd_v1_preserve_unknown_fields_action.go b/pkg/restore/actions/crd_v1_preserve_unknown_fields_action.go index 673edd1b61..9e4cf7e2fa 100644 --- a/pkg/restore/actions/crd_v1_preserve_unknown_fields_action.go +++ b/pkg/restore/actions/crd_v1_preserve_unknown_fields_action.go @@ -107,7 +107,7 @@ func (c *CRDV1PreserveUnknownFieldsAction) Execute(input *velero.RestoreItemActi }, nil } -func fromUnstructured(unstructured map[string]interface{}) (*apiextv1.CustomResourceDefinition, error) { +func fromUnstructured(unstructured map[string]any) (*apiextv1.CustomResourceDefinition, error) { var crd apiextv1.CustomResourceDefinition js, err := json.Marshal(unstructured) diff --git a/pkg/restore/actions/csi/pvc_action.go b/pkg/restore/actions/csi/pvc_action.go index 19c687e8bf..f828b29066 100644 --- a/pkg/restore/actions/csi/pvc_action.go +++ b/pkg/restore/actions/csi/pvc_action.go @@ -597,7 +597,7 @@ func (p *pvcRestoreItemAction) isResourceExist( } func NewPvcRestoreItemAction(f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, err diff --git a/pkg/restore/actions/csi/volumesnapshot_action.go b/pkg/restore/actions/csi/volumesnapshot_action.go index 61af12c675..6383d047bd 100644 --- a/pkg/restore/actions/csi/volumesnapshot_action.go +++ b/pkg/restore/actions/csi/volumesnapshot_action.go @@ -171,7 +171,7 @@ func (p *volumeSnapshotRestoreItemAction) Execute( return nil, errors.WithStack(err) } - p.log.Infof(`Returning from VolumeSnapshotRestoreItemAction with + p.log.Infof(`Returning from VolumeSnapshotRestoreItemAction with no additionalItems`) return &velero.RestoreItemActionExecuteOutput{ @@ -207,7 +207,7 @@ func (p *volumeSnapshotRestoreItemAction) AreAdditionalItemsReady( func NewVolumeSnapshotRestoreItemAction( f client.Factory) plugincommon.HandlerInitializer { - return func(logger logrus.FieldLogger) (interface{}, error) { + return func(logger logrus.FieldLogger) (any, error) { crClient, err := f.KubebuilderClient() if err != nil { return nil, err diff --git a/pkg/restore/actions/csi/volumesnapshot_action_test.go b/pkg/restore/actions/csi/volumesnapshot_action_test.go index 1cc3f0ba94..e2e81fd30c 100644 --- a/pkg/restore/actions/csi/volumesnapshot_action_test.go +++ b/pkg/restore/actions/csi/volumesnapshot_action_test.go @@ -89,7 +89,7 @@ func TestResetVolumeSnapshotSpecForRestore(t *testing.T) { before := tc.vs.DeepCopy() resetVolumeSnapshotSpecForRestore(&tc.vs, &tc.vscName) - assert.Equalf(t, tc.vs.Name, before.Name, "unexpected change to Object.Name, Want: %s; Got %s", tc.name, before.Name, tc.vs.Name) + assert.Equalf(t, tc.vs.Name, before.Name, "unexpected change to Object.Name, Want: %s; Got %s", before.Name, tc.vs.Name) assert.Equal(t, tc.vs.Namespace, before.Namespace, "unexpected change to Object.Namespace, Want: %s; Got %s", tc.name, before.Namespace, tc.vs.Namespace) assert.NotNil(t, tc.vs.Spec.Source) assert.Nil(t, tc.vs.Spec.Source.PersistentVolumeClaimName) diff --git a/pkg/restore/actions/csi/volumesnapshotclass_action.go b/pkg/restore/actions/csi/volumesnapshotclass_action.go index 577445a4bb..34782efe2c 100644 --- a/pkg/restore/actions/csi/volumesnapshotclass_action.go +++ b/pkg/restore/actions/csi/volumesnapshotclass_action.go @@ -106,6 +106,6 @@ func (p *volumeSnapshotClassRestoreItemAction) AreAdditionalItemsReady( } func NewVolumeSnapshotClassRestoreItemAction( - logger logrus.FieldLogger) (interface{}, error) { + logger logrus.FieldLogger) (any, error) { return &volumeSnapshotClassRestoreItemAction{logger}, nil } diff --git a/pkg/restore/actions/csi/volumesnapshotcontent_action.go b/pkg/restore/actions/csi/volumesnapshotcontent_action.go index c00919a279..bea63b53b9 100644 --- a/pkg/restore/actions/csi/volumesnapshotcontent_action.go +++ b/pkg/restore/actions/csi/volumesnapshotcontent_action.go @@ -108,6 +108,6 @@ func (p *volumeSnapshotContentRestoreItemAction) AreAdditionalItemsReady( return true, nil } -func NewVolumeSnapshotContentRestoreItemAction(logger logrus.FieldLogger) (interface{}, error) { +func NewVolumeSnapshotContentRestoreItemAction(logger logrus.FieldLogger) (any, error) { return &volumeSnapshotContentRestoreItemAction{logger}, nil } diff --git a/pkg/restore/actions/dataupload_retrieve_action_test.go b/pkg/restore/actions/dataupload_retrieve_action_test.go index 6bfc7aabfb..c3d262947a 100644 --- a/pkg/restore/actions/dataupload_retrieve_action_test.go +++ b/pkg/restore/actions/dataupload_retrieve_action_test.go @@ -90,7 +90,7 @@ func TestDataUploadRetrieveActionExectue(t *testing.T) { fakeClient := fakeClientBuilder.WithRuntimeObjects(tc.veleroObjs...).Build() - var unstructuredDataUpload map[string]interface{} + var unstructuredDataUpload map[string]any if tc.dataUpload != nil { var err error unstructuredDataUpload, err = runtime.DefaultUnstructuredConverter.ToUnstructured(tc.dataUpload) diff --git a/pkg/restore/actions/pod_volume_restore_action_test.go b/pkg/restore/actions/pod_volume_restore_action_test.go index 5b836cba15..9d48619acf 100644 --- a/pkg/restore/actions/pod_volume_restore_action_test.go +++ b/pkg/restore/actions/pod_volume_restore_action_test.go @@ -274,7 +274,7 @@ func TestPodVolumeRestoreActionExecute(t *testing.T) { require.NoError(t, err) // Default to using the same pod for both Item and ItemFromBackup if podFromBackup not provided - var unstructuredPodFromBackup map[string]interface{} + var unstructuredPodFromBackup map[string]any if tc.podFromBackup != nil { unstructuredPodFromBackup, err = runtime.DefaultUnstructuredConverter.ToUnstructured(tc.podFromBackup) require.NoError(t, err) diff --git a/pkg/restore/actions/service_action.go b/pkg/restore/actions/service_action.go index ee392a3810..9de75228e7 100644 --- a/pkg/restore/actions/service_action.go +++ b/pkg/restore/actions/service_action.go @@ -96,7 +96,7 @@ func deleteHealthCheckNodePort(service *corev1api.Service) error { // annotation(HealthCheckNodePort is specified by `kubectl apply` command) lastAppliedConfig, ok := service.Annotations[annotationLastAppliedConfig] if ok { - appliedServiceUnstructured := new(map[string]interface{}) + appliedServiceUnstructured := new(map[string]any) if err := json.Unmarshal([]byte(lastAppliedConfig), appliedServiceUnstructured); err != nil { return errors.WithStack(err) } @@ -119,7 +119,7 @@ func deleteHealthCheckNodePort(service *corev1api.Service) error { if entry.FieldsV1 == nil { continue } - fields := new(map[string]interface{}) + fields := new(map[string]any) if err := json.Unmarshal(entry.FieldsV1.Raw, fields); err != nil { return errors.WithStack(err) } @@ -157,7 +157,7 @@ func deleteNodePorts(service *corev1api.Service) error { if ok { explicitNodePorts := sets.NewString() unnamedPortInts := sets.NewInt() - appliedServiceUnstructured := new(map[string]interface{}) + appliedServiceUnstructured := new(map[string]any) if err := json.Unmarshal([]byte(lastAppliedConfig), appliedServiceUnstructured); err != nil { return errors.WithStack(err) } @@ -170,7 +170,7 @@ func deleteNodePorts(service *corev1api.Service) error { if bool { for _, port := range ports { - p, ok := port.(map[string]interface{}) + p, ok := port.(map[string]any) if !ok { continue } @@ -224,7 +224,7 @@ func deleteNodePorts(service *corev1api.Service) error { if entry.FieldsV1 == nil { continue } - fields := new(map[string]interface{}) + fields := new(map[string]any) if err := json.Unmarshal(entry.FieldsV1.Raw, fields); err != nil { return errors.WithStack(err) } @@ -237,7 +237,7 @@ func deleteNodePorts(service *corev1api.Service) error { continue } for key, port := range ports { - p, ok := port.(map[string]interface{}) + p, ok := port.(map[string]any) if !ok { continue } diff --git a/pkg/restore/actions/service_action_test.go b/pkg/restore/actions/service_action_test.go index e8ed85d698..42c0d290d1 100644 --- a/pkg/restore/actions/service_action_test.go +++ b/pkg/restore/actions/service_action_test.go @@ -49,9 +49,9 @@ func svcJSON(ports ...corev1api.ServicePort) string { return string(data) } -func svcJSONFromUnstructured(ports ...map[string]interface{}) string { - svc := map[string]interface{}{ - "spec": map[string]interface{}{ +func svcJSONFromUnstructured(ports ...map[string]any) string { + svc := map[string]any{ + "spec": map[string]any{ "ports": ports, }, } @@ -259,7 +259,7 @@ func TestServiceActionExecute(t *testing.T) { ObjectMeta: metav1.ObjectMeta{ Name: "svc-1", Annotations: map[string]string{ - annotationLastAppliedConfig: svcJSONFromUnstructured(map[string]interface{}{"name": "http", "nodePort": "8080"}), + annotationLastAppliedConfig: svcJSONFromUnstructured(map[string]any{"name": "http", "nodePort": "8080"}), }, }, Spec: corev1api.ServiceSpec{ @@ -275,7 +275,7 @@ func TestServiceActionExecute(t *testing.T) { ObjectMeta: metav1.ObjectMeta{ Name: "svc-1", Annotations: map[string]string{ - annotationLastAppliedConfig: svcJSONFromUnstructured(map[string]interface{}{"name": "http", "nodePort": "8080"}), + annotationLastAppliedConfig: svcJSONFromUnstructured(map[string]any{"name": "http", "nodePort": "8080"}), }, }, Spec: corev1api.ServiceSpec{ diff --git a/pkg/restore/merge_service_account.go b/pkg/restore/merge_service_account.go index f77a7730aa..7abaa7ee20 100644 --- a/pkg/restore/merge_service_account.go +++ b/pkg/restore/merge_service_account.go @@ -54,7 +54,7 @@ func mergeServiceAccounts(fromCluster, fromBackup *unstructured.Unstructured) (* } // The DefaultUnstructuredConverter.ToUnstructured function will populate the creation timestamp with the nil value // However, we remove this on both the backup and cluster objects before comparison, and we don't want it in any patches. - delete(desiredUnstructured["metadata"].(map[string]interface{}), "creationTimestamp") + delete(desiredUnstructured["metadata"].(map[string]any), "creationTimestamp") return &unstructured.Unstructured{Object: desiredUnstructured}, nil } diff --git a/pkg/restore/pv_restorer.go b/pkg/restore/pv_restorer.go index 49d2e885fb..53fbd0126a 100644 --- a/pkg/restore/pv_restorer.go +++ b/pkg/restore/pv_restorer.go @@ -92,7 +92,7 @@ func (r *pvRestorer) executePVAction(obj *unstructured.Unstructured) (*unstructu if !ok { return nil, errors.Errorf("unexpected type %T", updated1) } - var iops int64 = 0 + var iops int64 if snapshotInfo.volumeIOPS != nil { iops = *snapshotInfo.volumeIOPS } diff --git a/pkg/restore/pv_restorer_test.go b/pkg/restore/pv_restorer_test.go index 86ee05e408..8db8a21a86 100644 --- a/pkg/restore/pv_restorer_test.go +++ b/pkg/restore/pv_restorer_test.go @@ -253,7 +253,7 @@ type testUnstructured struct { func newTestUnstructured() *testUnstructured { obj := &testUnstructured{ Unstructured: &unstructured.Unstructured{ - Object: make(map[string]interface{}), + Object: make(map[string]any), }, } @@ -275,15 +275,15 @@ func (obj *testUnstructured) WithStatus(fields ...string) *testUnstructured { return obj.withMap("status", fields...) } -func (obj *testUnstructured) WithMetadataField(field string, value interface{}) *testUnstructured { +func (obj *testUnstructured) WithMetadataField(field string, value any) *testUnstructured { return obj.withMapEntry("metadata", field, value) } -func (obj *testUnstructured) WithSpecField(field string, value interface{}) *testUnstructured { +func (obj *testUnstructured) WithSpecField(field string, value any) *testUnstructured { return obj.withMapEntry("spec", field, value) } -func (obj *testUnstructured) WithStatusField(field string, value interface{}) *testUnstructured { +func (obj *testUnstructured) WithStatusField(field string, value any) *testUnstructured { return obj.withMapEntry("status", field, value) } @@ -297,7 +297,7 @@ func (obj *testUnstructured) WithAnnotations(fields ...string) *testUnstructured } func (obj *testUnstructured) WithAnnotationValues(fieldVals map[string]string) *testUnstructured { - annotations := make(map[string]interface{}) + annotations := make(map[string]any) for field, val := range fieldVals { annotations[field] = val } @@ -312,7 +312,7 @@ func (obj *testUnstructured) WithName(name string) *testUnstructured { } func (obj *testUnstructured) withMap(name string, fields ...string) *testUnstructured { - m := make(map[string]interface{}) + m := make(map[string]any) obj.Object[name] = m for _, field := range fields { @@ -322,14 +322,14 @@ func (obj *testUnstructured) withMap(name string, fields ...string) *testUnstruc return obj } -func (obj *testUnstructured) withMapEntry(mapName, field string, value interface{}) *testUnstructured { - var m map[string]interface{} +func (obj *testUnstructured) withMapEntry(mapName, field string, value any) *testUnstructured { + var m map[string]any if res, ok := obj.Unstructured.Object[mapName]; !ok { - m = make(map[string]interface{}) + m = make(map[string]any) obj.Unstructured.Object[mapName] = m } else { - m = res.(map[string]interface{}) + m = res.(map[string]any) } m[field] = value diff --git a/pkg/restore/restore.go b/pkg/restore/restore.go index 9ae0b0f663..6a5aa9a2dc 100644 --- a/pkg/restore/restore.go +++ b/pkg/restore/restore.go @@ -773,7 +773,7 @@ func (ctx *restoreContext) processSelectedResource( itemsRestored: len(ctx.restoredItems), } } - ctx.log.WithFields(map[string]interface{}{ + ctx.log.WithFields(map[string]any{ "progress": "", "resource": groupResource.String(), "namespace": selectedItem.targetNamespace, @@ -2035,7 +2035,7 @@ func hasPodVolumeBackup(unstructuredPV *unstructured.Unstructured, ctx *restoreC return found } -func hasDeleteReclaimPolicy(obj map[string]interface{}) bool { +func hasDeleteReclaimPolicy(obj map[string]any) bool { policy, _, _ := unstructured.NestedString(obj, "spec", "persistentVolumeReclaimPolicy") return policy == string(v1.PersistentVolumeReclaimDelete) } @@ -2071,9 +2071,9 @@ func resetMetadata(obj *unstructured.Unstructured) (*unstructured.Unstructured, if !ok { return nil, errors.New("metadata not found") } - metadata, ok := res.(map[string]interface{}) + metadata, ok := res.(map[string]any) if !ok { - return nil, errors.Errorf("metadata was of type %T, expected map[string]interface{}", res) + return nil, errors.Errorf("metadata was of type %T, expected map[string]any", res) } for k := range metadata { diff --git a/pkg/restore/restore_test.go b/pkg/restore/restore_test.go index 311d68cd47..1bb123b9b3 100644 --- a/pkg/restore/restore_test.go +++ b/pkg/restore/restore_test.go @@ -1708,7 +1708,7 @@ func (a *pluggableAction) AreAdditionalItemsReady(additionalItems []velero.Resou } // TestRestoreActionModifications runs restores with restore item actions that modify resources, and -// verifies that that the modified item is correctly created in the API. Verification is done by looking +// verifies that the modified item is correctly created in the API. Verification is done by looking // at the full object in the API. func TestRestoreActionModifications(t *testing.T) { // modifyingActionGetter is a helper function that returns a *pluggableAction, whose Execute(...) @@ -2005,7 +2005,7 @@ func TestRestoreWithAsyncOperations(t *testing.T) { } // TestRestoreActionAdditionalItems runs restores with restore item actions that return additional items -// to be restored, and verifies that that the correct set of items is created in the API. Verification is +// to be restored, and verifies that the correct set of items is created in the API. Verification is // done by looking at the namespaces/names of the items in the API; contents are not checked. func TestRestoreActionAdditionalItems(t *testing.T) { tests := []struct { @@ -2352,7 +2352,7 @@ func assertRestoredItems(t *testing.T, h *harness, want []*test.APIResource) { t.Logf("%v", string(itemJSON)) - u := make(map[string]interface{}) + u := make(map[string]any) if !assert.NoError(t, json.Unmarshal(itemJSON, &u)) { continue } @@ -3758,7 +3758,7 @@ func Test_resetVolumeBindingInfo(t *testing.T) { kubeutil.KubeAnnBindCompleted, kubeutil.KubeAnnBoundByController, kubeutil.KubeAnnDynamicallyProvisioned, - ).WithSpecField("claimRef", map[string]interface{}{ + ).WithSpecField("claimRef", map[string]any{ "namespace": "ns-1", "name": "pvc-1", "uid": "abc", @@ -3766,7 +3766,7 @@ func Test_resetVolumeBindingInfo(t *testing.T) { expected: newTestUnstructured().WithMetadataField("kind", "persistentVolume"). WithName("pv-1"). WithAnnotations(kubeutil.KubeAnnDynamicallyProvisioned). - WithSpecField("claimRef", map[string]interface{}{ + WithSpecField("claimRef", map[string]any{ "namespace": "ns-1", "name": "pvc-1"}).Unstructured, }, { @@ -3806,7 +3806,7 @@ func TestIsAlreadyExistsError(t *testing.T) { { name: "The input obj isn't service", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Pod", }, }, @@ -3815,7 +3815,7 @@ func TestIsAlreadyExistsError(t *testing.T) { { name: "The StatusError contains no causes", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Service", }, }, @@ -3829,7 +3829,7 @@ func TestIsAlreadyExistsError(t *testing.T) { { name: "The causes contains not only port already allocated error", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Service", }, }, @@ -3849,9 +3849,9 @@ func TestIsAlreadyExistsError(t *testing.T) { { name: "Get already allocated error but the service doesn't exist", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Service", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, @@ -3875,9 +3875,9 @@ func TestIsAlreadyExistsError(t *testing.T) { builder.ForService("default", "test").Result(), ), obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Service", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, @@ -3935,7 +3935,7 @@ func TestHasCSIVolumeSnapshot(t *testing.T) { { name: "Invalid PV, expect false.", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": 1, }, }, @@ -3944,10 +3944,10 @@ func TestHasCSIVolumeSnapshot(t *testing.T) { { name: "Cannot find VS, expect false", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, @@ -3958,15 +3958,15 @@ func TestHasCSIVolumeSnapshot(t *testing.T) { { name: "VS's source PVC is nil, expect false", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, - "spec": map[string]interface{}{ - "claimRef": map[string]interface{}{ + "spec": map[string]any{ + "claimRef": map[string]any{ "namespace": "velero", "name": "test", }, @@ -3979,10 +3979,10 @@ func TestHasCSIVolumeSnapshot(t *testing.T) { { name: "PVs claimref is nil, expect false.", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "velero", "name": "test", }, @@ -3995,15 +3995,15 @@ func TestHasCSIVolumeSnapshot(t *testing.T) { { name: "Find VS, expect true.", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "velero", "name": "test", }, - "spec": map[string]interface{}{ - "claimRef": map[string]interface{}{ + "spec": map[string]any{ + "claimRef": map[string]any{ "namespace": "velero", "name": "test", }, @@ -4043,7 +4043,7 @@ func TestHasSnapshotDataUpload(t *testing.T) { { name: "Invalid PV, expect false.", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": 1, }, }, @@ -4052,10 +4052,10 @@ func TestHasSnapshotDataUpload(t *testing.T) { { name: "PV without ClaimRef, expect false", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, @@ -4068,15 +4068,15 @@ func TestHasSnapshotDataUpload(t *testing.T) { { name: "Cannot find DataUploadResult CM, expect false", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, - "spec": map[string]interface{}{ - "claimRef": map[string]interface{}{ + "spec": map[string]any{ + "claimRef": map[string]any{ "namespace": "velero", "name": "testPVC", }, @@ -4090,15 +4090,15 @@ func TestHasSnapshotDataUpload(t *testing.T) { { name: "Find DataUploadResult CM, expect true", obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "PersistentVolume", "apiVersion": "v1", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": "default", "name": "test", }, - "spec": map[string]interface{}{ - "claimRef": map[string]interface{}{ + "spec": map[string]any{ + "claimRef": map[string]any{ "namespace": "velero", "name": "testPVC", }, diff --git a/pkg/test/comparisons.go b/pkg/test/comparisons.go index 4a0e415739..670cf3cf02 100644 --- a/pkg/test/comparisons.go +++ b/pkg/test/comparisons.go @@ -73,7 +73,7 @@ func CompareActions(t *testing.T, expected, actual []core.Action) { // that the action is a PatchAction, that the patch decodes from JSON // with the provided decode func and has no extraneous fields, and that // the decoded patch matches the expected. -func ValidatePatch(t *testing.T, action core.Action, expected interface{}, decodeFunc func(*json.Decoder) (interface{}, error)) { +func ValidatePatch(t *testing.T, action core.Action, expected any, decodeFunc func(*json.Decoder) (any, error)) { t.Helper() patchAction, ok := action.(core.PatchAction) require.True(t, ok, "action is not a PatchAction") @@ -97,7 +97,7 @@ func TimesAreEqual(t1, t2 time.Time) bool { // AssertDeepEqual asserts the semantic equality of objects. // This function exists in order to make sure time.Time and metav1.Time objects // can be compared correctly. See https://github.com/stretchr/testify/issues/502. -func AssertDeepEqual(t *testing.T, expected, actual interface{}) bool { +func AssertDeepEqual(t *testing.T, expected, actual any) bool { t.Helper() // By default, the equality.Semantic object doesn't have a function for comparing time.Times err := equality.Semantic.AddFunc(TimesAreEqual) diff --git a/pkg/test/fake_discovery_helper.go b/pkg/test/fake_discovery_helper.go index 79b3de7f28..89218adbf3 100644 --- a/pkg/test/fake_discovery_helper.go +++ b/pkg/test/fake_discovery_helper.go @@ -158,7 +158,7 @@ func (di *FakeServerResourcesInterface) ServerPreferredResources() ([]*metav1.AP if di.ReturnError != nil { return di.ResourceList, di.ReturnError } - if di.FailedGroups == nil || len(di.FailedGroups) == 0 { + if len(di.FailedGroups) == 0 { return di.ResourceList, nil } return di.ResourceList, &discovery.ErrGroupDiscoveryFailed{Groups: di.FailedGroups} @@ -168,7 +168,7 @@ func (di *FakeServerResourcesInterface) ServerGroupsAndResources() ([]*metav1.AP if di.ReturnError != nil { return di.APIGroup, di.ResourceList, di.ReturnError } - if di.FailedGroups == nil || len(di.FailedGroups) == 0 { + if len(di.FailedGroups) == 0 { return di.APIGroup, di.ResourceList, nil } return di.APIGroup, di.ResourceList, &discovery.ErrGroupDiscoveryFailed{Groups: di.FailedGroups} diff --git a/pkg/test/helpers.go b/pkg/test/helpers.go index 5c103c5eae..3020cdfeee 100644 --- a/pkg/test/helpers.go +++ b/pkg/test/helpers.go @@ -29,8 +29,8 @@ func UnstructuredOrDie(data string) *unstructured.Unstructured { return o.(*unstructured.Unstructured) } -func GetAsMap(j string) (map[string]interface{}, error) { - m := make(map[string]interface{}) +func GetAsMap(j string) (map[string]any, error) { + m := make(map[string]any) err := json.Unmarshal([]byte(j), &m) return m, err } diff --git a/pkg/test/mock_pod_command_executor.go b/pkg/test/mock_pod_command_executor.go index 2a05914c2d..b8ace0c6e0 100644 --- a/pkg/test/mock_pod_command_executor.go +++ b/pkg/test/mock_pod_command_executor.go @@ -40,7 +40,7 @@ func (h HookExecutionEntry) String() string { return fmt.Sprintf("%s.%s.%s.%s", h.Namespace, h.Name, h.HookName, strings.Join(h.HookCommand, ",")) } -func (e *MockPodCommandExecutor) ExecutePodCommand(log logrus.FieldLogger, item map[string]interface{}, namespace, name, hookName string, hook *v1.ExecHook) error { +func (e *MockPodCommandExecutor) ExecutePodCommand(log logrus.FieldLogger, item map[string]any, namespace, name, hookName string, hook *v1.ExecHook) error { e.HookExecutionLog = append(e.HookExecutionLog, HookExecutionEntry{ Namespace: namespace, Name: name, diff --git a/pkg/test/tar_writer.go b/pkg/test/tar_writer.go index 6cfcd8bd7c..20706766cc 100644 --- a/pkg/test/tar_writer.go +++ b/pkg/test/tar_writer.go @@ -67,7 +67,7 @@ func (tw *TarWriter) AddItems(groupResource string, items ...metav1.Object) *Tar return tw } -func (tw *TarWriter) Add(name string, obj interface{}) *TarWriter { +func (tw *TarWriter) Add(name string, obj any) *TarWriter { tw.t.Helper() var data []byte diff --git a/pkg/uploader/kopia/progress.go b/pkg/uploader/kopia/progress.go index 6b38b6da51..5f14d9d4ac 100644 --- a/pkg/uploader/kopia/progress.go +++ b/pkg/uploader/kopia/progress.go @@ -17,6 +17,7 @@ limitations under the License. package kopia import ( + "math" "sync/atomic" "time" @@ -90,7 +91,7 @@ func (p *Progress) Error(path string, err error, isIgnored bool) { // EstimatedDataSize statistic the total size of files to be processed and total files to be processed func (p *Progress) EstimatedDataSize(fileCount int, totalBytes int64) { atomic.StoreInt64(&p.estimatedTotalBytes, totalBytes) - atomic.StoreInt32(&p.estimatedFileCount, int32(fileCount)) + atomic.StoreInt32(&p.estimatedFileCount, int32(min(fileCount, math.MaxInt32))) p.UpdateProgress() } diff --git a/pkg/uploader/kopia/shim.go b/pkg/uploader/kopia/shim.go index b90837d198..1a308dcc80 100644 --- a/pkg/uploader/kopia/shim.go +++ b/pkg/uploader/kopia/shim.go @@ -75,7 +75,7 @@ func (sr *shimRepository) VerifyObject(ctx context.Context, id object.ID) ([]con } // Get one or more manifest data that match the specific manifest id -func (sr *shimRepository) GetManifest(ctx context.Context, id manifest.ID, payload interface{}) (*manifest.EntryMetadata, error) { +func (sr *shimRepository) GetManifest(ctx context.Context, id manifest.ID, payload any) (*manifest.EntryMetadata, error) { repoMani := udmrepo.RepoManifest{ Payload: payload, } @@ -194,7 +194,7 @@ func (sr *shimRepository) NewObjectWriter(ctx context.Context, option object.Wri } // PutManifest saves the given manifest payload with a set of labels. -func (sr *shimRepository) PutManifest(ctx context.Context, labels map[string]string, payload interface{}) (manifest.ID, error) { +func (sr *shimRepository) PutManifest(ctx context.Context, labels map[string]string, payload any) (manifest.ID, error) { id, err := sr.udmRepo.PutManifest(ctx, udmrepo.RepoManifest{ Payload: payload, Metadata: &udmrepo.ManifestEntryMetadata{ @@ -210,7 +210,7 @@ func (sr *shimRepository) DeleteManifest(ctx context.Context, id manifest.ID) er return sr.udmRepo.DeleteManifest(ctx, udmrepo.ID(id)) } -func (sr *shimRepository) ReplaceManifests(ctx context.Context, labels map[string]string, payload interface{}) (manifest.ID, error) { +func (sr *shimRepository) ReplaceManifests(ctx context.Context, labels map[string]string, payload any) (manifest.ID, error) { const minReplaceManifestTimeDelta = 100 * time.Millisecond md, err := sr.FindManifests(ctx, labels) diff --git a/pkg/uploader/kopia/snapshot_test.go b/pkg/uploader/kopia/snapshot_test.go index de621ce85b..2d2379884d 100644 --- a/pkg/uploader/kopia/snapshot_test.go +++ b/pkg/uploader/kopia/snapshot_test.go @@ -50,7 +50,7 @@ type snapshotMockes struct { type mockArgs struct { methodName string - returns []interface{} + returns []any } func injectSnapshotFuncs() *snapshotMockes { @@ -103,65 +103,65 @@ func TestSnapshotSource(t *testing.T) { { name: "regular test", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, }, notError: true, }, { name: "failed to load snapshot, should fallback to full backup and not error", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, errors.New("failed to load snapshot")}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, errors.New("failed to load snapshot")}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, }, notError: true, }, { name: "failed to save snapshot", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, errors.New("failed to save snapshot")}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, errors.New("failed to save snapshot")}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, }, notError: false, }, { name: "failed to set policy", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{errors.New("failed to set policy")}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{errors.New("failed to set policy")}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, }, notError: false, }, { name: "set policy with parallel files upload", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, }, uploaderCfg: map[string]string{ "ParallelFilesUpload": "10", @@ -171,26 +171,26 @@ func TestSnapshotSource(t *testing.T) { { name: "failed to upload snapshot", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, errors.New("failed to upload snapshot")}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, errors.New("failed to upload snapshot")}}, + {methodName: "Flush", returns: []any{nil}}, }, notError: false, }, { name: "failed to flush repo", args: []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, errors.New("failed to save snapshot")}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{errors.New("failed to flush repo")}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, errors.New("failed to save snapshot")}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{errors.New("failed to flush repo")}}, }, notError: false, }, @@ -628,13 +628,13 @@ func TestBackup(t *testing.T) { } s := injectSnapshotFuncs() args := []mockArgs{ - {methodName: "LoadSnapshot", returns: []interface{}{manifest, nil}}, - {methodName: "SaveSnapshot", returns: []interface{}{manifest.ID, nil}}, - {methodName: "TreeForSource", returns: []interface{}{nil, nil}}, - {methodName: "ApplyRetentionPolicy", returns: []interface{}{nil, nil}}, - {methodName: "SetPolicy", returns: []interface{}{nil}}, - {methodName: "Upload", returns: []interface{}{manifest, nil}}, - {methodName: "Flush", returns: []interface{}{nil}}, + {methodName: "LoadSnapshot", returns: []any{manifest, nil}}, + {methodName: "SaveSnapshot", returns: []any{manifest.ID, nil}}, + {methodName: "TreeForSource", returns: []any{nil, nil}}, + {methodName: "ApplyRetentionPolicy", returns: []any{nil, nil}}, + {methodName: "SetPolicy", returns: []any{nil}}, + {methodName: "Upload", returns: []any{manifest, nil}}, + {methodName: "Flush", returns: []any{nil}}, } MockFuncs(s, args) if tc.isSnapshotSourceError { diff --git a/pkg/uploader/mocks/uploader.go b/pkg/uploader/mocks/uploader.go index d8b5fa2fda..d76a65f471 100644 --- a/pkg/uploader/mocks/uploader.go +++ b/pkg/uploader/mocks/uploader.go @@ -34,11 +34,11 @@ type Uploader struct { // Execute provides a mock function with given fields: ctx, source, policyTree, sourceInfo, previousManifests func (_m *Uploader) Upload(ctx context.Context, source fs.Entry, policyTree *policy.Tree, sourceInfo snapshot.SourceInfo, previousManifests ...*snapshot.Manifest) (*snapshot.Manifest, error) { - _va := make([]interface{}, len(previousManifests)) + _va := make([]any, len(previousManifests)) for _i := range previousManifests { _va[_i] = previousManifests[_i] } - var _ca []interface{} + var _ca []any _ca = append(_ca, ctx, source, policyTree, sourceInfo) _ca = append(_ca, _va...) ret := _m.Called(_ca...) diff --git a/pkg/uploader/provider/kopia.go b/pkg/uploader/provider/kopia.go index 1d2128c4d1..5e5a3c6186 100644 --- a/pkg/uploader/provider/kopia.go +++ b/pkg/uploader/provider/kopia.go @@ -196,7 +196,7 @@ func (kp *kopiaProvider) RunBackup( return snapshotInfo.ID, false, nil } -func (kp *kopiaProvider) GetPassword(param interface{}) (string, error) { +func (kp *kopiaProvider) GetPassword(param any) (string, error) { if kp.credGetter.FromSecret == nil { return "", errors.New("invalid credentials interface") } diff --git a/pkg/util/csi/volume_snapshot.go b/pkg/util/csi/volume_snapshot.go index 738bd91481..a8e40eb1ff 100644 --- a/pkg/util/csi/volume_snapshot.go +++ b/pkg/util/csi/volume_snapshot.go @@ -412,7 +412,7 @@ func GetVolumeSnapshotClassForStorageClass( for _, sc := range snapshotClasses.Items { _, hasLabelSelector := sc.Labels[velerov1api.VolumeSnapshotClassSelectorLabel] if sc.Driver == provisioner { - n += 1 + n++ vsClass = sc if hasLabelSelector { return &sc, nil diff --git a/pkg/util/csi/volume_snapshot_test.go b/pkg/util/csi/volume_snapshot_test.go index 79adaf0025..b368022b33 100644 --- a/pkg/util/csi/volume_snapshot_test.go +++ b/pkg/util/csi/volume_snapshot_test.go @@ -1621,14 +1621,14 @@ func TestWaitUntilVSCHandleIsReady(t *testing.T) { volSnap: vsWithNilStatusField, }, { - name: "waitDisabled should find volumesnapshotcontent volumesnapshotcontent status is nil", + name: "waitDisabled should find volumesnapshotcontent status is nil", wait: false, expectError: false, exepctedVSC: vscWithNilStatus, volSnap: vsForNilStatusVsc, }, { - name: "waitDisabled should find volumesnapshotcontent volumesnapshotcontent status.SnapshotHandle is nil", + name: "waitDisabled should find volumesnapshotcontent status.SnapshotHandle is nil", wait: false, expectError: false, exepctedVSC: vscWithNilStatusField, diff --git a/pkg/util/encode/encode.go b/pkg/util/encode/encode.go index 9704c1a2e1..b7cbdc1c75 100644 --- a/pkg/util/encode/encode.go +++ b/pkg/util/encode/encode.go @@ -78,7 +78,7 @@ func EncoderFor(format string, obj runtime.Object) (runtime.Encoder, error) { } // ToJSONGzip takes arbitrary Go data and encodes it to GZip compressed JSON in a buffer, as well as a description of the data to put into an error should encoding fail. -func ToJSONGzip(data interface{}, desc string) (*bytes.Buffer, []error) { +func ToJSONGzip(data any, desc string) (*bytes.Buffer, []error) { buf := new(bytes.Buffer) gzw := gzip.NewWriter(buf) diff --git a/pkg/util/kube/event.go b/pkg/util/kube/event.go index de91d3533d..d6c3db183f 100644 --- a/pkg/util/kube/event.go +++ b/pkg/util/kube/event.go @@ -124,7 +124,7 @@ func (er *eventRecorder) EndingEvent(object runtime.Object, warning bool, reason } } -var shutdownTimeout time.Duration = time.Minute +var shutdownTimeout = time.Minute func (er *eventRecorder) Shutdown() { var wait chan struct{} diff --git a/pkg/util/kube/mocks.go b/pkg/util/kube/mocks.go index f6d7d049b9..27ff9bc34b 100644 --- a/pkg/util/kube/mocks.go +++ b/pkg/util/kube/mocks.go @@ -8,7 +8,8 @@ import ( ) // Client knows how to perform CRUD operations on Kubernetes objects. -// go:generate mockery --name=Client +// +//go:generate mockery --name=Client type Client interface { client.Reader client.Writer diff --git a/pkg/util/kube/pvc_pv.go b/pkg/util/kube/pvc_pv.go index da9dfb2c74..8e227b45cd 100644 --- a/pkg/util/kube/pvc_pv.go +++ b/pkg/util/kube/pvc_pv.go @@ -347,8 +347,8 @@ func IsPVCBound(pvc *corev1api.PersistentVolumeClaim) bool { // MakePodPVCAttachment returns the volume mounts and devices for a pod needed to attach a PVC func MakePodPVCAttachment(volumeName string, volumeMode *corev1api.PersistentVolumeMode, readOnly bool) ([]corev1api.VolumeMount, []corev1api.VolumeDevice, string) { - var volumeMounts []corev1api.VolumeMount = nil - var volumeDevices []corev1api.VolumeDevice = nil + var volumeMounts []corev1api.VolumeMount + var volumeDevices []corev1api.VolumeDevice volumePath := "/" + volumeName if volumeMode != nil && *volumeMode == corev1api.PersistentVolumeBlock { diff --git a/pkg/util/logging/error_location_hook_test.go b/pkg/util/logging/error_location_hook_test.go index 1dd73d6936..606c6e5259 100644 --- a/pkg/util/logging/error_location_hook_test.go +++ b/pkg/util/logging/error_location_hook_test.go @@ -29,30 +29,30 @@ import ( func TestFire(t *testing.T) { tests := []struct { name string - preEntryFields map[string]interface{} - expectedEntryFields map[string]interface{} + preEntryFields map[string]any + expectedEntryFields map[string]any expectedErr bool }{ { name: "no error", - preEntryFields: map[string]interface{}{"foo": "bar"}, - expectedEntryFields: map[string]interface{}{"foo": "bar"}, + preEntryFields: map[string]any{"foo": "bar"}, + expectedEntryFields: map[string]any{"foo": "bar"}, }, { name: "basic (non-pkg/errors) error", - preEntryFields: map[string]interface{}{logrus.ErrorKey: errors.New("a normal error")}, - expectedEntryFields: map[string]interface{}{logrus.ErrorKey: errors.New("a normal error")}, + preEntryFields: map[string]any{logrus.ErrorKey: errors.New("a normal error")}, + expectedEntryFields: map[string]any{logrus.ErrorKey: errors.New("a normal error")}, }, { name: "non-error logged in error field", - preEntryFields: map[string]interface{}{logrus.ErrorKey: "not an error"}, - expectedEntryFields: map[string]interface{}{logrus.ErrorKey: "not an error"}, + preEntryFields: map[string]any{logrus.ErrorKey: "not an error"}, + expectedEntryFields: map[string]any{logrus.ErrorKey: "not an error"}, expectedErr: false, }, { name: "pkg/errors error", - preEntryFields: map[string]interface{}{logrus.ErrorKey: pkgerrs.New("a pkg/errors error")}, - expectedEntryFields: map[string]interface{}{ + preEntryFields: map[string]any{logrus.ErrorKey: pkgerrs.New("a pkg/errors error")}, + expectedEntryFields: map[string]any{ logrus.ErrorKey: pkgerrs.New("a pkg/errors error"), errorFileField: "", errorFunctionField: "github.com/vmware-tanzu/velero/pkg/util/logging.TestFire", @@ -60,12 +60,12 @@ func TestFire(t *testing.T) { }, { name: "already have error file and function fields", - preEntryFields: map[string]interface{}{ + preEntryFields: map[string]any{ logrus.ErrorKey: pkgerrs.New("a pkg/errors error"), errorFileField: "some_file.go:123", errorFunctionField: "SomeFunction", }, - expectedEntryFields: map[string]interface{}{ + expectedEntryFields: map[string]any{ logrus.ErrorKey: pkgerrs.New("a pkg/errors error"), errorFileField: "some_file.go:123", errorFunctionField: "SomeFunction", diff --git a/pkg/util/podvolume/pod_volume_test.go b/pkg/util/podvolume/pod_volume_test.go index 9f6738a652..2bc9da86fb 100644 --- a/pkg/util/podvolume/pod_volume_test.go +++ b/pkg/util/podvolume/pod_volume_test.go @@ -156,7 +156,7 @@ func TestGetVolumesByPod(t *testing.T) { Volumes: []corev1api.Volume{ // PVB Volumes {Name: "pvbPV1"}, {Name: "pvbPV2"}, {Name: "pvbPV3"}, - /// Excluded from PVB because colume mounting default service account token + /// Excluded from PVB because volume mounting default service account token {Name: "default-token-5xq45"}, }, }, diff --git a/pkg/util/third_party.go b/pkg/util/third_party.go index 2be1586811..b0b73d68ee 100644 --- a/pkg/util/third_party.go +++ b/pkg/util/third_party.go @@ -16,6 +16,6 @@ limitations under the License. package util -var ThirdPartyLabels []string = []string{ +var ThirdPartyLabels = []string{ "azure.workload.identity/use", } diff --git a/test/e2e/basic/api-group/enable_api_group_versions.go b/test/e2e/basic/api-group/enable_api_group_versions.go index c0eb770626..13ee3a39e1 100644 --- a/test/e2e/basic/api-group/enable_api_group_versions.go +++ b/test/e2e/basic/api-group/enable_api_group_versions.go @@ -419,20 +419,20 @@ func resourceInfo(ctx context.Context, g, v, r string, index int) (map[string]ma return nil, errors.Wrap(err, errMsg) } - var info map[string]interface{} + var info map[string]any if err := json.Unmarshal([]byte(stdout), &info); err != nil { return nil, errors.Wrap(err, "unmarshal resource info JSON") } - items := info["items"].([]interface{}) + items := info["items"].([]any) if len(items) < 1 { return nil, errors.New("resource info is empty") } - item := items[0].(map[string]interface{}) - metadata := item["metadata"].(map[string]interface{}) - annotations := metadata["annotations"].(map[string]interface{}) - specs := item["spec"].(map[string]interface{}) + item := items[0].(map[string]any) + metadata := item["metadata"].(map[string]any) + annotations := metadata["annotations"].(map[string]any) + specs := item["spec"].(map[string]any) annoSpec := make(map[string]map[string]string) diff --git a/test/e2e/basic/backup-volume-info/csi_data_mover.go b/test/e2e/basic/backup-volume-info/csi_data_mover.go index de1ca5c423..43edb0ddb0 100644 --- a/test/e2e/basic/backup-volume-info/csi_data_mover.go +++ b/test/e2e/basic/backup-volume-info/csi_data_mover.go @@ -58,7 +58,7 @@ func (c *CSIDataMoverVolumeInfo) Verify() error { Expect(err).ShouldNot(HaveOccurred(), "Fail to get VolumeInfo metadata in the Backup Repository.") fmt.Printf("The VolumeInfo metadata content: %+v\n", *volumeInfo[0]) - Expect(len(volumeInfo) > 0).To(BeIdenticalTo(true)) + Expect(volumeInfo).ToNot(BeEmpty()) Expect(volumeInfo[0].SnapshotDataMovementInfo).NotTo(BeNil()) return nil diff --git a/test/e2e/basic/backup-volume-info/csi_snapshot.go b/test/e2e/basic/backup-volume-info/csi_snapshot.go index ef476421c0..5eddb4ea22 100644 --- a/test/e2e/basic/backup-volume-info/csi_snapshot.go +++ b/test/e2e/basic/backup-volume-info/csi_snapshot.go @@ -57,7 +57,7 @@ func (c *CSISnapshotVolumeInfo) Verify() error { Expect(err).ShouldNot(HaveOccurred(), "Fail to get VolumeInfo metadata in the Backup Repository.") fmt.Printf("The VolumeInfo metadata content: %+v\n", *volumeInfo[0]) - Expect(len(volumeInfo) > 0).To(BeIdenticalTo(true)) + Expect(volumeInfo).ToNot(BeEmpty()) Expect(volumeInfo[0].CSISnapshotInfo).NotTo(BeNil()) return nil diff --git a/test/e2e/basic/backup-volume-info/filesystem_upload.go b/test/e2e/basic/backup-volume-info/filesystem_upload.go index d58eee5ada..e6266c0c66 100644 --- a/test/e2e/basic/backup-volume-info/filesystem_upload.go +++ b/test/e2e/basic/backup-volume-info/filesystem_upload.go @@ -57,7 +57,7 @@ func (f *FilesystemUploadVolumeInfo) Verify() error { Expect(err).ShouldNot(HaveOccurred(), "Fail to get VolumeInfo metadata in the Backup Repository.") fmt.Printf("The VolumeInfo metadata content: %+v\n", *volumeInfo[0]) - Expect(len(volumeInfo) > 0).To(BeIdenticalTo(true)) + Expect(volumeInfo).ToNot(BeEmpty()) Expect(volumeInfo[0].PVBInfo).NotTo(BeNil()) return nil diff --git a/test/e2e/basic/backup-volume-info/native_snapshot.go b/test/e2e/basic/backup-volume-info/native_snapshot.go index b4200f85ca..13a75d2e64 100644 --- a/test/e2e/basic/backup-volume-info/native_snapshot.go +++ b/test/e2e/basic/backup-volume-info/native_snapshot.go @@ -58,7 +58,7 @@ func (n *NativeSnapshotVolumeInfo) Verify() error { Expect(err).ShouldNot(HaveOccurred(), "Fail to get VolumeInfo metadata in the Backup Repository.") fmt.Printf("The VolumeInfo metadata content: %+v\n", *volumeInfo[0]) - Expect(len(volumeInfo) > 0).To(BeIdenticalTo(true)) + Expect(volumeInfo).ToNot(BeEmpty()) Expect(volumeInfo[0].NativeSnapshotInfo).NotTo(BeNil()) return nil diff --git a/test/e2e/basic/backup-volume-info/skipped_volumes.go b/test/e2e/basic/backup-volume-info/skipped_volumes.go index 0f1ccec0c2..2fc801a5fc 100644 --- a/test/e2e/basic/backup-volume-info/skipped_volumes.go +++ b/test/e2e/basic/backup-volume-info/skipped_volumes.go @@ -57,7 +57,7 @@ func (s *SkippedVolumeInfo) Verify() error { Expect(err).ShouldNot(HaveOccurred(), "Fail to get VolumeInfo metadata in the Backup Repository.") fmt.Printf("The VolumeInfo metadata content: %+v\n", *volumeInfo[0]) - Expect(len(volumeInfo) > 0).To(BeIdenticalTo(true)) + Expect(volumeInfo).ToNot(BeEmpty()) Expect(volumeInfo[0].Skipped).To(BeIdenticalTo(true)) return nil diff --git a/test/perf/e2e_suite_test.go b/test/perf/e2e_suite_test.go index cb4522d699..48a5ceec9e 100644 --- a/test/perf/e2e_suite_test.go +++ b/test/perf/e2e_suite_test.go @@ -88,7 +88,7 @@ func initConfig() error { ReportData = &E2EReport{ TestDescription: VeleroCfg.TestCaseDescribe, - OtherFields: make(map[string]interface{}), + OtherFields: make(map[string]any), } return nil diff --git a/test/perf/metrics/monitor.go b/test/perf/metrics/monitor.go index c98fd30134..e8f746ac62 100644 --- a/test/perf/metrics/monitor.go +++ b/test/perf/metrics/monitor.go @@ -82,11 +82,11 @@ func (m *MetricsCollector) UpdateOneTimeMetrics() { } // GetMetrics returns the metrics from all metrics -func (m *MetricsCollector) GetMetrics() map[string]interface{} { +func (m *MetricsCollector) GetMetrics() map[string]any { m.Mu.Lock() // Acquire the lock before accessing shared resources defer m.Mu.Unlock() // Release the lock after the function returns - dataMap := make(map[string]interface{}) + dataMap := make(map[string]any) resData := make(map[string]([]map[string]map[string]string)) for _, metric := range m.Metrics { monitorMetrics := metric.GetMetrics() @@ -102,7 +102,7 @@ func (m *MetricsCollector) GetMetrics() map[string]interface{} { } for _, metric := range m.OneTimeMetrics { - oneTimeMetricsMap := make(map[string]interface{}) + oneTimeMetricsMap := make(map[string]any) monitorMetrics := metric.GetMetrics() for key, value := range monitorMetrics { oneTimeMetricsMap[key] = value diff --git a/test/pkg/client/config.go b/test/pkg/client/config.go index 7546a0ac4c..687c303e7b 100644 --- a/test/pkg/client/config.go +++ b/test/pkg/client/config.go @@ -33,9 +33,9 @@ const ( ConfigKeyColorized = "colorized" ) -// VeleroConfig is a map of strings to interface{} for deserializing Velero client config options. +// VeleroConfig is a map of strings to any for deserializing Velero client config options. // The alias is a way to attach type-asserting convenience methods. -type VeleroConfig map[string]interface{} +type VeleroConfig map[string]any // LoadConfig loads the Velero client configuration file and returns it as a VeleroConfig. If the // file does not exist, an empty map is returned. diff --git a/test/pkg/client/factory_test.go b/test/pkg/client/factory_test.go index d257b88b57..5df2e07fd8 100644 --- a/test/pkg/client/factory_test.go +++ b/test/pkg/client/factory_test.go @@ -31,14 +31,14 @@ func TestFactory(t *testing.T) { // Env variable should set the namespace if no config or argument are used os.Setenv("VELERO_NAMESPACE", "env-velero") - f := NewFactory("velero", "", make(map[string]interface{})) + f := NewFactory("velero", "", make(map[string]any)) assert.Equal(t, "env-velero", f.Namespace()) os.Unsetenv("VELERO_NAMESPACE") // Argument should change the namespace - f = NewFactory("velero", "", make(map[string]interface{})) + f = NewFactory("velero", "", make(map[string]any)) s := "flag-velero" flags := new(pflag.FlagSet) @@ -50,7 +50,7 @@ func TestFactory(t *testing.T) { // An argument overrides the env variable if both are set. os.Setenv("VELERO_NAMESPACE", "env-velero") - f = NewFactory("velero", "", make(map[string]interface{})) + f = NewFactory("velero", "", make(map[string]any)) flags = new(pflag.FlagSet) f.BindFlags(flags) diff --git a/test/types.go b/test/types.go index 35a1502c2d..552b9e38d7 100644 --- a/test/types.go +++ b/test/types.go @@ -63,8 +63,8 @@ var UUIDgen uuid.UUID var VeleroCfg VeleroConfig type E2EReport struct { - TestDescription string `yaml:"Test Description"` - OtherFields map[string]interface{} `yaml:",inline"` + TestDescription string `yaml:"Test Description"` + OtherFields map[string]any `yaml:",inline"` } var ReportData *E2EReport diff --git a/test/util/providers/azure_utils.go b/test/util/providers/azure_utils.go index 86c439fb60..20cab54ba6 100644 --- a/test/util/providers/azure_utils.go +++ b/test/util/providers/azure_utils.go @@ -168,7 +168,7 @@ func getStorageAccountKey(credentialsFile, accountName, subscriptionID, resource if err != nil { return "", errors.WithStack(err) } - if res.Keys == nil || len(res.Keys) == 0 { + if len(res.Keys) == 0 { return "", errors.New("No storage keys found") } diff --git a/test/util/report/report.go b/test/util/report/report.go index 91ec876b17..6d5955392c 100644 --- a/test/util/report/report.go +++ b/test/util/report/report.go @@ -47,6 +47,6 @@ func GenerateYamlReport() error { return nil } -func AddTestSuitData(dataMap map[string]interface{}, testSuitDesc string) { +func AddTestSuitData(dataMap map[string]any, testSuitDesc string) { test.ReportData.OtherFields[testSuitDesc] = dataMap } diff --git a/test/util/velero/install.go b/test/util/velero/install.go index 027ca43048..4357a16a05 100644 --- a/test/util/velero/install.go +++ b/test/util/velero/install.go @@ -262,7 +262,7 @@ func cleanVSpherePluginConfig(c clientset.Interface, ns, secretName, configMapNa return nil } -func installVeleroServer(ctx context.Context, cli, cloudProvider string, options *installOptions) error { +func installVeleroServer(ctx context.Context, cli, _ string, options *installOptions) error { args := []string{"install"} namespace := "velero" if len(options.Namespace) > 0 { @@ -478,7 +478,7 @@ func patchResources(resources *unstructured.UnstructuredList, namespace string, ".dockerconfigjson": credential, }, } - resource.Object["imagePullSecrets"] = []map[string]interface{}{ + resource.Object["imagePullSecrets"] = []map[string]any{ { "name": "image-pull-secret", }, @@ -559,7 +559,7 @@ func patchResources(resources *unstructured.UnstructuredList, namespace string, return nil } -func toUnstructured(res interface{}) (unstructured.Unstructured, error) { +func toUnstructured(res any) (unstructured.Unstructured, error) { un := unstructured.Unstructured{} data, err := json.Marshal(res) if err != nil { @@ -672,7 +672,7 @@ func PrepareVelero(ctx context.Context, caseName string, veleroCfg test.VeleroCo fmt.Printf("error in checking velero status with %v", err) ctx, ctxCancel := context.WithTimeout(context.Background(), time.Minute*5) defer ctxCancel() - VeleroUninstall(ctx, veleroCfg) + _ = VeleroUninstall(ctx, veleroCfg) ready = false } if ready { diff --git a/test/util/velero/velero_utils.go b/test/util/velero/velero_utils.go index c57ceae4c4..d219d4dd3f 100644 --- a/test/util/velero/velero_utils.go +++ b/test/util/velero/velero_utils.go @@ -245,10 +245,10 @@ func getProviderVeleroInstallOptions(veleroCfg *VeleroConfig, io.BucketName = veleroCfg.BSLBucket io.Prefix = veleroCfg.BSLPrefix io.BackupStorageConfig = flag.NewMap() - io.BackupStorageConfig.Set(veleroCfg.BSLConfig) + _ = io.BackupStorageConfig.Set(veleroCfg.BSLConfig) io.VolumeSnapshotConfig = flag.NewMap() - io.VolumeSnapshotConfig.Set(veleroCfg.VSLConfig) + _ = io.VolumeSnapshotConfig.Set(veleroCfg.VSLConfig) io.Plugins = flag.NewStringArray(plugins...) io.Features = veleroCfg.Features @@ -787,15 +787,15 @@ func WaitForVSphereUploadCompletion(ctx context.Context, timeout time.Duration, fmt.Printf("%s %s\n", curLine, time.Now().Format("2006-01-02 15:04:05")) comps := strings.Split(curLine, "=") // SnapshotPhase represents the lifecycle phase of a Snapshot. - // New - No work yet, next phase is InProgress + // New - No work yet, next phase is // InProgress - snapshot being taken - // Snapshotted - local snapshot complete, next phase is Protecting or SnapshotFailed + // Snapshotted - local snapshot complete, next phase is Protecting or // SnapshotFailed - end state, snapshot was not able to be taken // Uploading - snapshot is being moved to durable storage // Uploaded - end state, snapshot has been protected // UploadFailed - end state, unable to move to durable storage // Canceling - when the SanpshotCancel flag is set, if the Snapshot has not already moved into a terminal state, the - // status will move to Canceling. The snapshot ID will be removed from the status status if has been filled in + // status will move to Canceling. The snapshot ID will be removed from the status if has been filled in // and the snapshot ID will not longer be valid for a Clone operation // Canceled - the operation was canceled, the snapshot ID is not valid // Canceled - the operation was canceled, the snapshot ID is not valid @@ -940,12 +940,12 @@ func InstallVeleroCLI(version string) (string, error) { return tempVeleroCliDir + "/" + name + "/velero", nil } -func getVeleroCliTarball(cliTarballUrl string) (*os.File, error) { - lastInd := strings.LastIndex(cliTarballUrl, "/") - tarball := cliTarballUrl[lastInd+1:] +func getVeleroCliTarball(cliTarballURL string) (*os.File, error) { + lastInd := strings.LastIndex(cliTarballURL, "/") + tarball := cliTarballURL[lastInd+1:] cli := &http.Client{} - req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, cliTarballUrl, nil) + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, cliTarballURL, nil) resp, err := cli.Do(req) if err != nil { return nil, errors.WithMessagef(err, "failed to access Velero CLI tarball")