From dac6705a466941e0bc69569aa1757a1fe5726564 Mon Sep 17 00:00:00 2001 From: Vince Prignano Date: Mon, 4 Mar 2024 12:27:15 -0800 Subject: [PATCH] :seedling: Align golangci-lint with upstream Cluster API Signed-off-by: Vince Prignano --- .github/workflows/pr-golangci-lint.yaml | 33 +++ .golangci.yml | 198 ++++++++++++------ Makefile | 9 +- api/v1beta1/awscluster_types.go | 1 + api/v1beta1/awsclustertemplate_types.go | 1 + api/v1beta1/conversion_test.go | 19 +- api/v1beta2/awscluster_types.go | 15 +- api/v1beta2/awsclustertemplate_types.go | 1 + api/v1beta2/doc.go | 2 +- api/v1beta2/groupversion_info.go | 2 +- api/v1beta2/network_types.go | 8 +- api/v1beta2/types.go | 2 + bootstrap/eks/api/v1beta1/conversion_test.go | 1 - bootstrap/eks/api/v1beta2/doc.go | 2 +- .../eks/api/v1beta2/eksconfig_webhook.go | 2 +- .../api/v1beta2/eksconfigtemplate_webhook.go | 2 +- .../eks/api/v1beta2/groupversion_info.go | 3 +- .../eks/controllers/eksconfig_controller.go | 1 + bootstrap/eks/controllers/suite_test.go | 2 - bootstrap/eks/internal/userdata/commands.go | 1 + bootstrap/eks/internal/userdata/node.go | 2 + cmd/clusterawsadm/ami/helper.go | 16 +- cmd/clusterawsadm/ami/list.go | 1 + .../api/ami/v1beta1/scheme/scheme.go | 2 + .../api/bootstrap/v1alpha1/scheme/scheme.go | 2 + .../api/bootstrap/v1beta1/scheme/scheme.go | 2 + .../bootstrap/cluster_api_controller.go | 96 ++++----- .../cloudformation/bootstrap/iam.go | 1 + .../cloudformation/bootstrap/template.go | 2 + .../cloudformation/bootstrap/template_test.go | 3 +- .../cloudformation/service/service.go | 1 + cmd/clusterawsadm/cmd/ami/ami.go | 1 + cmd/clusterawsadm/cmd/ami/common/common.go | 1 + cmd/clusterawsadm/cmd/ami/common/copy.go | 1 - cmd/clusterawsadm/cmd/ami/list/list.go | 1 + cmd/clusterawsadm/cmd/bootstrap/bootstrap.go | 2 + .../cmd/bootstrap/credentials/credentials.go | 1 + .../cmd/bootstrap/iam/iam_doc.go | 2 +- cmd/clusterawsadm/cmd/bootstrap/iam/root.go | 1 + .../cmd/controller/controller.go | 1 + .../cmd/controller/credentials/print.go | 1 + .../cmd/controller/rollout/common.go | 1 + cmd/clusterawsadm/cmd/eks/addons/addons.go | 1 + .../cmd/eks/addons/list_installed.go | 4 +- cmd/clusterawsadm/cmd/eks/addons/types.go | 2 +- cmd/clusterawsadm/cmd/eks/eks.go | 1 + cmd/clusterawsadm/cmd/flags/common.go | 1 + cmd/clusterawsadm/cmd/gc/gc.go | 6 +- cmd/clusterawsadm/cmd/resource/list/list.go | 3 +- cmd/clusterawsadm/cmd/resource/resource.go | 6 +- cmd/clusterawsadm/cmd/root.go | 3 +- cmd/clusterawsadm/cmd/util/util.go | 1 + cmd/clusterawsadm/cmd/version/version.go | 1 + .../configreader/configreader.go | 1 + .../credentials/update_credentials.go | 3 +- cmd/clusterawsadm/controller/helper.go | 1 + .../controller/rollout/rollout.go | 1 + cmd/clusterawsadm/converters/iam.go | 1 + cmd/clusterawsadm/credentials/credentials.go | 1 + cmd/clusterawsadm/gc/gc.go | 5 +- cmd/clusterawsadm/main.go | 1 + cmd/clusterawsadm/printers/printers.go | 1 + cmd/clusterawsadm/resource/type.go | 1 + ...ne.cluster.x-k8s.io_rosacontrolplanes.yaml | 3 + ....cluster.x-k8s.io_awsclustertemplates.yaml | 4 + ...ructure.cluster.x-k8s.io_rosaclusters.yaml | 4 +- ...ure.cluster.x-k8s.io_rosamachinepools.yaml | 1 + controllers/awsmachine_controller.go | 13 +- controllers/rosacluster_controller.go | 1 - .../v1beta1/awsmanagedcontrolplane_types.go | 1 + .../eks/api/v1beta1/conversion_test.go | 3 +- controlplane/eks/api/v1beta1/types.go | 2 +- .../v1beta2/awsmanagedcontrolplane_types.go | 1 + controlplane/eks/api/v1beta2/doc.go | 2 +- .../eks/api/v1beta2/groupversion_info.go | 2 +- controlplane/eks/api/v1beta2/types.go | 2 +- .../rosa/api/v1beta2/groupversion_info.go | 2 +- .../api/v1beta2/rosacontrolplane_types.go | 4 + .../rosacontrolplane_controller.go | 7 +- docs/book/cmd/amilist/main.go | 1 + docs/book/cmd/clusterawsadmdocs/main.go | 1 + docs/triage-party/triage-party-deployment.go | 4 +- exp/api/v1beta1/conversion.go | 5 +- exp/api/v1beta1/conversion_test.go | 1 - exp/api/v1beta2/awsmachinepool_webhook.go | 2 +- exp/api/v1beta2/groupversion_info.go | 2 +- exp/api/v1beta2/rosacluster_types.go | 4 +- exp/api/v1beta2/rosamachinepool_types.go | 1 + .../awscontrolleridentity_controller.go | 1 + exp/controllers/awsmachinepool_controller.go | 1 + .../awsmachinepool_controller_test.go | 2 +- exp/controllers/rosamachinepool_controller.go | 3 +- exp/doc.go | 1 + .../awsinstancestate_controller.go | 2 + feature/feature.go | 1 + hack/boilerplate/test/fail.go | 1 + hack/tools/Makefile | 9 - .../conversion-gen/generators/conversion.go | 6 +- hack/tools/third_party/conversion-gen/main.go | 7 +- iam/api/v1beta1/types.go | 1 + main.go | 1 + pkg/annotations/annotations.go | 1 + pkg/cloud/awserrors/errors.go | 2 + pkg/cloud/converters/eks.go | 2 + pkg/cloud/endpoints/endpoints.go | 1 + pkg/cloud/filter/types.go | 1 + pkg/cloud/identity/identity.go | 7 +- pkg/cloud/identity/identity_test.go | 14 +- pkg/cloud/interfaces.go | 1 + pkg/cloud/logs/logs.go | 1 + pkg/cloud/metrics/metrics.go | 1 + pkg/cloud/scope/cluster.go | 4 + pkg/cloud/scope/global.go | 1 + pkg/cloud/scope/launchtemplate.go | 2 + pkg/cloud/scope/machine.go | 2 + pkg/cloud/scope/machinepool.go | 14 +- pkg/cloud/scope/managedcontrolplane.go | 1 + pkg/cloud/scope/managednodegroup.go | 21 +- pkg/cloud/scope/rosacontrolplane.go | 9 + pkg/cloud/scope/rosamachinepool.go | 1 + pkg/cloud/scope/session.go | 6 +- .../services/autoscaling/autoscalinggroup.go | 3 + .../autoscaling/mock_autoscalingiface/doc.go | 3 +- pkg/cloud/services/awsnode/cni_test.go | 8 +- pkg/cloud/services/awsnode/service.go | 1 + pkg/cloud/services/ec2/instances.go | 8 +- pkg/cloud/services/ec2/launchtemplate.go | 5 + pkg/cloud/services/ec2/service.go | 1 + pkg/cloud/services/eks/cluster.go | 6 +- pkg/cloud/services/eks/cluster_test.go | 6 +- pkg/cloud/services/eks/eks.go | 1 + pkg/cloud/services/eks/iam/iam.go | 3 +- pkg/cloud/services/eks/nodegroup.go | 4 +- pkg/cloud/services/eks/service.go | 1 + pkg/cloud/services/elb/loadbalancer.go | 49 ++--- pkg/cloud/services/elb/loadbalancer_test.go | 2 +- pkg/cloud/services/elb/service.go | 1 + pkg/cloud/services/gc/ec2.go | 2 +- pkg/cloud/services/gc/options.go | 1 + pkg/cloud/services/gc/service.go | 1 + .../services/iamauth/mock_iamauth/doc.go | 3 +- pkg/cloud/services/iamauth/service.go | 1 + .../mock_eventbridgeiface/doc.go | 1 + .../instancestate/mock_sqsiface/doc.go | 3 +- pkg/cloud/services/instancestate/service.go | 1 + pkg/cloud/services/interfaces.go | 1 + pkg/cloud/services/kubeproxy/service.go | 1 + pkg/cloud/services/mock_services/doc.go | 3 +- pkg/cloud/services/network/natgateways.go | 2 +- pkg/cloud/services/network/service.go | 1 + pkg/cloud/services/network/subnets.go | 20 +- pkg/cloud/services/network/subnets_test.go | 2 +- pkg/cloud/services/network/vpc_test.go | 7 +- pkg/cloud/services/s3/mock_s3iface/doc.go | 1 + pkg/cloud/services/s3/mock_stsiface/doc.go | 1 + pkg/cloud/services/s3/s3.go | 5 + pkg/cloud/services/s3/s3_test.go | 2 +- .../mock_secretsmanageriface/doc.go | 3 +- pkg/cloud/services/secretsmanager/service.go | 1 + .../services/securitygroup/securitygroups.go | 12 +- .../securitygroup/securitygroups_test.go | 29 +-- pkg/cloud/services/securitygroup/service.go | 1 + pkg/cloud/services/ssm/cloudinit.go | 1 + pkg/cloud/services/ssm/mock_ssmiface/doc.go | 3 +- pkg/cloud/services/sts/mock_stsiface/doc.go | 3 +- pkg/cloud/services/userdata/userdata.go | 1 + pkg/cloud/services/wait/wait.go | 1 + pkg/cloud/tags/tags.go | 1 + pkg/cloud/throttle/throttle.go | 3 +- pkg/cloudtest/cloudtest.go | 16 +- pkg/eks/addons/plan.go | 15 +- pkg/eks/addons/procedures.go | 12 +- pkg/eks/eks.go | 1 + pkg/eks/identityprovider/plan.go | 4 +- pkg/eks/identityprovider/procedures.go | 19 +- pkg/eks/identityprovider/types.go | 1 + pkg/hash/base36.go | 1 + pkg/internal/bytes/bytes.go | 1 + pkg/internal/cidr/cidr.go | 1 + pkg/internal/cmp/slice.go | 6 + pkg/internal/mime/mime.go | 1 + pkg/internal/rate/rate.go | 2 +- pkg/internal/tristate/tristate.go | 1 + pkg/logger/logger.go | 10 +- pkg/planner/planner.go | 1 + pkg/record/recorder.go | 1 + pkg/rosa/client.go | 2 + pkg/rosa/idps.go | 20 +- pkg/rosa/oauth.go | 3 +- pkg/rosa/versions.go | 3 + scripts/go_install.sh | 2 +- test/e2e/shared/aws.go | 8 +- test/e2e/shared/common.go | 3 +- test/e2e/shared/defaults.go | 21 +- test/e2e/shared/gpu.go | 2 +- test/e2e/shared/suite.go | 8 +- test/e2e/shared/template.go | 2 +- test/e2e/suites/managed/cluster.go | 1 + test/e2e/suites/managed/machine_deployment.go | 4 - test/e2e/suites/unmanaged/helpers_test.go | 6 +- .../unmanaged/unmanaged_functional_test.go | 30 +-- test/helpers/envtest.go | 7 +- test/helpers/external/cluster.go | 1 + test/mocks/generate_aws.go | 6 +- util/conditions/helper.go | 1 + util/system/util.go | 1 + version/version.go | 1 + 207 files changed, 730 insertions(+), 407 deletions(-) create mode 100644 .github/workflows/pr-golangci-lint.yaml diff --git a/.github/workflows/pr-golangci-lint.yaml b/.github/workflows/pr-golangci-lint.yaml new file mode 100644 index 0000000000..d5e0e91b7e --- /dev/null +++ b/.github/workflows/pr-golangci-lint.yaml @@ -0,0 +1,33 @@ +name: PR golangci-lint + +on: + pull_request: + types: [opened, edited, synchronize, reopened] + +# Remove all permissions from GITHUB_TOKEN except metadata. +permissions: {} + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + working-directory: + - "" + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Calculate go version + id: vars + run: echo "go_version=$(make go-version)" >> $GITHUB_OUTPUT + - name: Set up Go + uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # tag=v5.0.0 + with: + go-version: ${{ steps.vars.outputs.go_version }} + - name: golangci-lint + uses: golangci/golangci-lint-action@3cfe3a4abbb849e10058ce4af15d205b6da42804 # tag=v4.0.0 + with: + version: v1.56.1 + args: --out-format=colored-line-number + working-directory: ${{matrix.working-directory}} diff --git a/.golangci.yml b/.golangci.yml index bd41d21015..7925fdfadb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,79 +1,126 @@ linters: - enable-all: true - disable: - - bidichk - - contextcheck - - cyclop - - dupl - - durationcheck - - errname - - errorlint - - exhaustive - - exhaustivestruct - - exhaustruct - - forcetypeassert - - forbidigo - - funlen - - gochecknoglobals - - gochecknoinits - - gocognit - - godox - - goerr113 - - gofumpt - - golint - - gomnd - - gomoddirectives - - gomodguard - - interfacer - - ireturn - - lll - - makezero - - maligned - - musttag - - nestif - - nilnil - - nlreturn - - nonamedreturns - - nosnakecase - - paralleltest - - promlinter - - scopelint - - sqlclosecheck - - tagliatelle - - tenv - - testpackage - - tparallel - - varnamelen - - wastedassign - - wrapcheck - - wsl - - deadcode - - ifshort - - structcheck - - varcheck - - interfacebloat + disable-all: true + enable: + - asasalint + - asciicheck + - bidichk + - bodyclose + - containedctx + - dogsled + - dupword + - durationcheck + - errcheck + - errchkjson + - exportloopref + - gci + - ginkgolinter + - goconst + - gocritic + - godot + - gofmt + - goimports + - goprintffuncname + - gosec + - gosimple + - govet + - importas + - ineffassign + - loggercheck + - misspell + - nakedret + - nilerr + - noctx + - nolintlint + - nosprintfhostport + - prealloc + - predeclared + - revive + - rowserrcheck + - staticcheck + - stylecheck + - thelper + - typecheck + - unconvert + - unparam + - unused + - usestdlibvars + - whitespace linters-settings: - # Restrict revive to exported. - revive: - # see https://github.com/mgechev/revive#available-rules for details. - ignore-generated-header: true - severity: warning - rules: - - name: exported - severity: warning gci: sections: - standard - default - prefix(sigs.k8s.io/cluster-api) ginkgolinter: - # Suppress the wrong length assertion warning. - suppress-len-assertion: true - # Suppress the wrong nil assertion warning. - suppress-nil-assertion: false - # Suppress the wrong error assertion warning. - suppress-err-assertion: true + forbid-focus-container: true + suppress-len-assertion: true # Suppress the wrong length assertion warning. + suppress-nil-assertion: false # Suppress the wrong nil assertion warning. + suppress-err-assertion: true # Suppress the wrong error assertion warning. + gocritic: + enabled-tags: + - diagnostic + - experimental + - performance + disabled-checks: + - appendAssign + - dupImport # https://github.com/go-critic/go-critic/issues/845 + - evalOrder + - ifElseChain + - octalLiteral + - regexpSimplify + - sloppyReassign + - truncateCmp + - typeDefFirst + - unnamedResult + - unnecessaryDefer + - whyNoLint + - wrapperFunc + - rangeValCopy + - hugeParam + - filepathJoin + - emptyStringTest + godot: + # declarations - for top level declaration comments (default); + # toplevel - for top level comments; + # all - for all comments. + scope: toplevel + exclude: + - '^ \+.*' + - '^ ANCHOR.*' + revive: + rules: + # The following rules are recommended https://github.com/mgechev/revive#recommended-configuration + - name: blank-imports + - name: context-as-argument + - name: context-keys-type + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: package-comments + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unreachable-code + - name: redefines-builtin-id + # + # Rules in addition to the recommended configuration above. + # + - name: bool-literal-in-expr + - name: constant-logical-expr + goconst: + ignore-tests: true gosec: excludes: - G307 # Deferring unsafe method "Close" on type "\*os.File" @@ -159,6 +206,10 @@ linters-settings: alias: apimachinerytypes - pkg: "sigs.k8s.io/cluster-api/exp/api/v1beta1" alias: expclusterv1 + nolintlint: + allow-unused: false + allow-leading-space: false + require-specific: true staticcheck: go: "1.21" stylecheck: @@ -178,7 +229,6 @@ issues: # List of regexps of issue texts to exclude, empty list by default. exclude: - (Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less) - - "exported: exported (const|function|method|type|var) (.+) should have comment or be unexported" - "exported: (func|type) name will be used as (.+) by other packages, and that stutters; consider calling this (.+)" - (G104|G107|G404|G505|ST1000) - "G108: Profiling endpoint is automatically exposed on /debug/pprof" @@ -188,6 +238,13 @@ issues: - "net/http.Get must not be called" exclude-rules: # Exclude revive's exported for certain packages and code, e.g. tests and fake. + - linters: + - revive + text: "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" + - linters: + - errcheck + text: Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked + # Exclude some packages or code to require comments, for example test code, or fake clients. - linters: - revive text: exported (method|function|type|const) (.+) should have comment or be unexported @@ -229,6 +286,11 @@ issues: - revive text: "var-naming: don't use underscores in Go names; func (.+) should be (.+)" path: .*/defaults.go + # These directives allow the mock and gc packages to be imported with an underscore everywhere. + - linters: + - revive + text: "var-naming: don't use an underscore in package name" + path: .*/.*(mock|gc_).*/.+\.go # Disable unparam "always receives" which might not be really # useful when building libraries. - linters: diff --git a/Makefile b/Makefile index d67ddea923..b42d7a1aec 100644 --- a/Makefile +++ b/Makefile @@ -48,6 +48,7 @@ KUBETEST_CONF_PATH ?= $(abspath $(E2E_DATA_DIR)/kubetest/conformance.yaml) EXP_DIR := exp # Binaries. +GO_INSTALL := ./scripts/go_install.sh GO_APIDIFF_BIN := $(BIN_DIR)/go-apidiff GO_APIDIFF := $(TOOLS_DIR)/$(GO_APIDIFF_BIN) CLUSTERCTL := $(BIN_DIR)/clusterctl @@ -58,7 +59,10 @@ DEFAULTER_GEN := $(TOOLS_BIN_DIR)/defaulter-gen ENVSUBST := $(TOOLS_BIN_DIR)/envsubst GH := $(TOOLS_BIN_DIR)/gh GOJQ := $(TOOLS_BIN_DIR)/gojq -GOLANGCI_LINT := $(TOOLS_BIN_DIR)/golangci-lint +GOLANGCI_LINT_BIN := golangci-lint +GOLANGCI_LINT_VER := $(shell cat .github/workflows/pr-golangci-lint.yaml | grep [[:space:]]version: | sed 's/.*version: //') +GOLANGCI_LINT := $(abspath $(TOOLS_BIN_DIR)/$(GOLANGCI_LINT_BIN)-$(GOLANGCI_LINT_VER)) +GOLANGCI_LINT_PKG := github.com/golangci/golangci-lint/cmd/golangci-lint KIND := $(TOOLS_BIN_DIR)/kind KUSTOMIZE := $(TOOLS_BIN_DIR)/kustomize MOCKGEN := $(TOOLS_BIN_DIR)/mockgen @@ -290,6 +294,9 @@ generate-go-apis: ## Alias for .build/generate-go-apis .PHONY: modules +$(GOLANGCI_LINT): # Build golangci-lint from tools folder. + GOBIN=$(abspath $(TOOLS_BIN_DIR)) $(GO_INSTALL) $(GOLANGCI_LINT_PKG) $(GOLANGCI_LINT_BIN) $(GOLANGCI_LINT_VER) + .PHONY: lint lint: $(GOLANGCI_LINT) ## Lint codebase $(GOLANGCI_LINT) run -v --fast=false $(GOLANGCI_LINT_EXTRA_ARGS) diff --git a/api/v1beta1/awscluster_types.go b/api/v1beta1/awscluster_types.go index 0e06987b4b..ddb1d2cd5a 100644 --- a/api/v1beta1/awscluster_types.go +++ b/api/v1beta1/awscluster_types.go @@ -207,6 +207,7 @@ type AWSClusterStatus struct { Conditions clusterv1.Conditions `json:"conditions,omitempty"` } +// S3Bucket defines a supporting S3 bucket for the cluster, currently can be optionally used for Ignition. type S3Bucket struct { // ControlPlaneIAMInstanceProfile is a name of the IAMInstanceProfile, which will be allowed // to read control-plane node bootstrap data from S3 Bucket. diff --git a/api/v1beta1/awsclustertemplate_types.go b/api/v1beta1/awsclustertemplate_types.go index 404da0b88a..07e2cf4039 100644 --- a/api/v1beta1/awsclustertemplate_types.go +++ b/api/v1beta1/awsclustertemplate_types.go @@ -53,6 +53,7 @@ func init() { SchemeBuilder.Register(&AWSClusterTemplate{}, &AWSClusterTemplateList{}) } +// AWSClusterTemplateResource defines the desired state of AWSClusterTemplate. type AWSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/api/v1beta1/conversion_test.go b/api/v1beta1/conversion_test.go index 7579d59aa8..24aa530ac2 100644 --- a/api/v1beta1/conversion_test.go +++ b/api/v1beta1/conversion_test.go @@ -19,9 +19,8 @@ package v1beta1 import ( "testing" - . "github.com/onsi/gomega" - fuzz "github.com/google/gofuzz" + . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" "k8s.io/apimachinery/pkg/runtime" runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" @@ -38,7 +37,7 @@ func fuzzFuncs(_ runtimeserializer.CodecFactory) []interface{} { func AWSMachineFuzzer(obj *AWSMachine, c fuzz.Continue) { c.FuzzNoCustom(obj) - + // AWSMachine.Spec.FailureDomain, AWSMachine.Spec.Subnet.ARN and AWSMachine.Spec.AdditionalSecurityGroups.ARN has been removed in v1beta2, so setting it to nil in order to avoid v1beta1 --> v1beta2 --> v1beta1 round trip errors. if obj.Spec.Subnet != nil { obj.Spec.Subnet.ARN = nil @@ -54,7 +53,7 @@ func AWSMachineFuzzer(obj *AWSMachine, c fuzz.Continue) { func AWSMachineTemplateFuzzer(obj *AWSMachineTemplate, c fuzz.Continue) { c.FuzzNoCustom(obj) - + // AWSMachineTemplate.Spec.Template.Spec.FailureDomain, AWSMachineTemplate.Spec.Template.Spec.Subnet.ARN and AWSMachineTemplate.Spec.Template.Spec.AdditionalSecurityGroups.ARN has been removed in v1beta2, so setting it to nil in order to avoid v1beta1 --> v1beta2 --> v1beta round trip errors. if obj.Spec.Template.Spec.Subnet != nil { obj.Spec.Template.Spec.Subnet.ARN = nil @@ -81,16 +80,16 @@ func TestFuzzyConversion(t *testing.T) { })) t.Run("for AWSMachine", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ - Scheme: scheme, - Hub: &v1beta2.AWSMachine{}, - Spoke: &AWSMachine{}, + Scheme: scheme, + Hub: &v1beta2.AWSMachine{}, + Spoke: &AWSMachine{}, FuzzerFuncs: []fuzzer.FuzzerFuncs{fuzzFuncs}, })) t.Run("for AWSMachineTemplate", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ - Scheme: scheme, - Hub: &v1beta2.AWSMachineTemplate{}, - Spoke: &AWSMachineTemplate{}, + Scheme: scheme, + Hub: &v1beta2.AWSMachineTemplate{}, + Spoke: &AWSMachineTemplate{}, FuzzerFuncs: []fuzzer.FuzzerFuncs{fuzzFuncs}, })) diff --git a/api/v1beta2/awscluster_types.go b/api/v1beta2/awscluster_types.go index 1df6c53b89..add00915cd 100644 --- a/api/v1beta2/awscluster_types.go +++ b/api/v1beta2/awscluster_types.go @@ -166,13 +166,19 @@ type Bastion struct { AMI string `json:"ami,omitempty"` } +// LoadBalancerType defines the type of load balancer to use. type LoadBalancerType string var ( - LoadBalancerTypeClassic = LoadBalancerType("classic") - LoadBalancerTypeELB = LoadBalancerType("elb") - LoadBalancerTypeALB = LoadBalancerType("alb") - LoadBalancerTypeNLB = LoadBalancerType("nlb") + // LoadBalancerTypeClassic is the classic ELB type. + LoadBalancerTypeClassic = LoadBalancerType("classic") + // LoadBalancerTypeELB is the ELB type. + LoadBalancerTypeELB = LoadBalancerType("elb") + // LoadBalancerTypeALB is the ALB type. + LoadBalancerTypeALB = LoadBalancerType("alb") + // LoadBalancerTypeNLB is the NLB type. + LoadBalancerTypeNLB = LoadBalancerType("nlb") + // LoadBalancerTypeDisabled disables the load balancer. LoadBalancerTypeDisabled = LoadBalancerType("disabled") ) @@ -268,6 +274,7 @@ type AWSClusterStatus struct { Conditions clusterv1.Conditions `json:"conditions,omitempty"` } +// S3Bucket defines a supporting S3 bucket for the cluster, currently can be optionally used for Ignition. type S3Bucket struct { // ControlPlaneIAMInstanceProfile is a name of the IAMInstanceProfile, which will be allowed // to read control-plane node bootstrap data from S3 Bucket. diff --git a/api/v1beta2/awsclustertemplate_types.go b/api/v1beta2/awsclustertemplate_types.go index 333cb285c3..e0a827fa3d 100644 --- a/api/v1beta2/awsclustertemplate_types.go +++ b/api/v1beta2/awsclustertemplate_types.go @@ -54,6 +54,7 @@ func init() { SchemeBuilder.Register(&AWSClusterTemplate{}, &AWSClusterTemplateList{}) } +// AWSClusterTemplateResource defines the desired state of AWSClusterTemplateResource. type AWSClusterTemplateResource struct { // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata diff --git a/api/v1beta2/doc.go b/api/v1beta2/doc.go index 912b8f6556..4ed8bbddb8 100644 --- a/api/v1beta2/doc.go +++ b/api/v1beta2/doc.go @@ -17,5 +17,5 @@ limitations under the License. // +gencrdrefdocs:force // +groupName=infrastructure.cluster.x-k8s.io -// package v1beta2 contains the v1beta2 API implementation. +// Package v1beta2 contains the v1beta2 API implementation. package v1beta2 diff --git a/api/v1beta2/groupversion_info.go b/api/v1beta2/groupversion_info.go index 7b92eca9fa..1d921ac08c 100644 --- a/api/v1beta2/groupversion_info.go +++ b/api/v1beta2/groupversion_info.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for the infrastructure v1beta2 API group +// Package v1beta2 contains API Schema definitions for the infrastructure v1beta2 API group // +kubebuilder:object:generate=true // +groupName=infrastructure.cluster.x-k8s.io package v1beta2 diff --git a/api/v1beta2/network_types.go b/api/v1beta2/network_types.go index 55cb919cdc..d487183025 100644 --- a/api/v1beta2/network_types.go +++ b/api/v1beta2/network_types.go @@ -106,6 +106,7 @@ type TargetGroupHealthCheck struct { type TargetGroupAttribute string var ( + // TargetGroupAttributeEnablePreserveClientIP defines the attribute key for enabling preserve client IP. TargetGroupAttributeEnablePreserveClientIP = "preserve_client_ip.enabled" ) @@ -113,8 +114,11 @@ var ( type LoadBalancerAttribute string var ( - LoadBalancerAttributeEnableLoadBalancingCrossZone = "load_balancing.cross_zone.enabled" - LoadBalancerAttributeIdleTimeTimeoutSeconds = "idle_timeout.timeout_seconds" + // LoadBalancerAttributeEnableLoadBalancingCrossZone defines the attribute key for enabling load balancing cross zone. + LoadBalancerAttributeEnableLoadBalancingCrossZone = "load_balancing.cross_zone.enabled" + // LoadBalancerAttributeIdleTimeTimeoutSeconds defines the attribute key for idle timeout. + LoadBalancerAttributeIdleTimeTimeoutSeconds = "idle_timeout.timeout_seconds" + // LoadBalancerAttributeIdleTimeDefaultTimeoutSecondsInSeconds defines the default idle timeout in seconds. LoadBalancerAttributeIdleTimeDefaultTimeoutSecondsInSeconds = "60" ) diff --git a/api/v1beta2/types.go b/api/v1beta2/types.go index 545c4f320c..55ce2f9cca 100644 --- a/api/v1beta2/types.go +++ b/api/v1beta2/types.go @@ -80,6 +80,7 @@ const ( ExternalResourceGCTasksAnnotation = "aws.cluster.x-k8s.io/external-resource-tasks-gc" ) +// GCTask defines a task to be executed by the garbage collector. type GCTask string var ( @@ -313,6 +314,7 @@ type InstanceMetadataOptions struct { InstanceMetadataTags InstanceMetadataState `json:"instanceMetadataTags,omitempty"` } +// SetDefaults sets the default values for the InstanceMetadataOptions. func (obj *InstanceMetadataOptions) SetDefaults() { if obj.HTTPEndpoint == "" { obj.HTTPEndpoint = InstanceMetadataEndpointStateEnabled diff --git a/bootstrap/eks/api/v1beta1/conversion_test.go b/bootstrap/eks/api/v1beta1/conversion_test.go index c6b4485354..47dcb9736d 100644 --- a/bootstrap/eks/api/v1beta1/conversion_test.go +++ b/bootstrap/eks/api/v1beta1/conversion_test.go @@ -20,7 +20,6 @@ import ( "testing" . "github.com/onsi/gomega" - runtime "k8s.io/apimachinery/pkg/runtime" v1beta2 "sigs.k8s.io/cluster-api-provider-aws/v2/bootstrap/eks/api/v1beta2" utilconversion "sigs.k8s.io/cluster-api/util/conversion" diff --git a/bootstrap/eks/api/v1beta2/doc.go b/bootstrap/eks/api/v1beta2/doc.go index 2069db82a5..992666159f 100644 --- a/bootstrap/eks/api/v1beta2/doc.go +++ b/bootstrap/eks/api/v1beta2/doc.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package v1beta2 contains API Schema definitions for the Amazon EKS Bootstrap v1beta2 API group. // +gencrdrefdocs:force //nolint: revive // +groupName=bootstrap.cluster.x-k8s.io - package v1beta2 diff --git a/bootstrap/eks/api/v1beta2/eksconfig_webhook.go b/bootstrap/eks/api/v1beta2/eksconfig_webhook.go index e1459ba1dd..30609f6755 100644 --- a/bootstrap/eks/api/v1beta2/eksconfig_webhook.go +++ b/bootstrap/eks/api/v1beta2/eksconfig_webhook.go @@ -42,7 +42,7 @@ func (r *EKSConfig) ValidateCreate() (admission.Warnings, error) { } // ValidateUpdate will do any extra validation when updating a EKSConfig. -func (r *EKSConfig) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { +func (r *EKSConfig) ValidateUpdate(_ runtime.Object) (admission.Warnings, error) { return nil, nil } diff --git a/bootstrap/eks/api/v1beta2/eksconfigtemplate_webhook.go b/bootstrap/eks/api/v1beta2/eksconfigtemplate_webhook.go index fc2504eca4..d6611c40c3 100644 --- a/bootstrap/eks/api/v1beta2/eksconfigtemplate_webhook.go +++ b/bootstrap/eks/api/v1beta2/eksconfigtemplate_webhook.go @@ -42,7 +42,7 @@ func (r *EKSConfigTemplate) ValidateCreate() (admission.Warnings, error) { } // ValidateUpdate will do any extra validation when updating a EKSConfigTemplate. -func (r *EKSConfigTemplate) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { +func (r *EKSConfigTemplate) ValidateUpdate(_ runtime.Object) (admission.Warnings, error) { return nil, nil } diff --git a/bootstrap/eks/api/v1beta2/groupversion_info.go b/bootstrap/eks/api/v1beta2/groupversion_info.go index a93c42785f..7c26521b41 100644 --- a/bootstrap/eks/api/v1beta2/groupversion_info.go +++ b/bootstrap/eks/api/v1beta2/groupversion_info.go @@ -14,10 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for the Amazon EKS Bootstrap v1beta2 API group +// Package v1beta2 contains API Schema definitions for the Amazon EKS Bootstrap v1beta2 API group // +kubebuilder:object:generate=true // +groupName=bootstrap.cluster.x-k8s.io - package v1beta2 import ( diff --git a/bootstrap/eks/controllers/eksconfig_controller.go b/bootstrap/eks/controllers/eksconfig_controller.go index 8f1de94fc3..5aa9425dd5 100644 --- a/bootstrap/eks/controllers/eksconfig_controller.go +++ b/bootstrap/eks/controllers/eksconfig_controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controllers provides a way to reconcile EKSConfig objects. package controllers import ( diff --git a/bootstrap/eks/controllers/suite_test.go b/bootstrap/eks/controllers/suite_test.go index 74cd527bd6..2b61ab258a 100644 --- a/bootstrap/eks/controllers/suite_test.go +++ b/bootstrap/eks/controllers/suite_test.go @@ -42,8 +42,6 @@ func TestMain(m *testing.M) { } func setup() { - // utilruntime.Must(bootstrapv1.AddToScheme(scheme.Scheme)) - // utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) utilruntime.Must(ekscontrolplanev1.AddToScheme(scheme.Scheme)) testEnvConfig := helpers.NewTestEnvironmentConfiguration([]string{ path.Join("config", "crd", "bases"), diff --git a/bootstrap/eks/internal/userdata/commands.go b/bootstrap/eks/internal/userdata/commands.go index af7551d8b6..1ee0c85abf 100644 --- a/bootstrap/eks/internal/userdata/commands.go +++ b/bootstrap/eks/internal/userdata/commands.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package userdata provides a way to generate ec2 instance userdata. package userdata const ( diff --git a/bootstrap/eks/internal/userdata/node.go b/bootstrap/eks/internal/userdata/node.go index 7be304cdb7..468f15478f 100644 --- a/bootstrap/eks/internal/userdata/node.go +++ b/bootstrap/eks/internal/userdata/node.go @@ -68,6 +68,7 @@ type NodeInput struct { NTP *eksbootstrapv1.NTP } +// DockerConfigJSONEscaped returns the DockerConfigJSON escaped for use in cloud-init. func (ni *NodeInput) DockerConfigJSONEscaped() string { if ni.DockerConfigJSON == nil || len(*ni.DockerConfigJSON) == 0 { return "''" @@ -76,6 +77,7 @@ func (ni *NodeInput) DockerConfigJSONEscaped() string { return shellescape.Quote(*ni.DockerConfigJSON) } +// BootstrapCommand returns the bootstrap command to be used on a node instance. func (ni *NodeInput) BootstrapCommand() string { if ni.BootstrapCommandOverride != nil && *ni.BootstrapCommandOverride != "" { return *ni.BootstrapCommandOverride diff --git a/cmd/clusterawsadm/ami/helper.go b/cmd/clusterawsadm/ami/helper.go index e8c8a2d9ed..ebc393084c 100644 --- a/cmd/clusterawsadm/ami/helper.go +++ b/cmd/clusterawsadm/ami/helper.go @@ -241,16 +241,14 @@ func findAMI(imagesMap map[string][]*ec2.Image, baseOS, kubernetesVersion string } if val, ok := imagesMap[amiName]; ok && val != nil { return latestAMI(val) - } else { - amiName, err = ec2service.GenerateAmiName(amiNameFormat, baseOS, strings.TrimPrefix(kubernetesVersion, "v")) - if err != nil { - return nil, errors.Wrapf(err, "failed to process ami format: %q", amiNameFormat) - } - if val, ok = imagesMap[amiName]; ok && val != nil { - return latestAMI(val) - } } - + amiName, err = ec2service.GenerateAmiName(amiNameFormat, baseOS, strings.TrimPrefix(kubernetesVersion, "v")) + if err != nil { + return nil, errors.Wrapf(err, "failed to process ami format: %q", amiNameFormat) + } + if val, ok := imagesMap[amiName]; ok && val != nil { + return latestAMI(val) + } return nil, nil } diff --git a/cmd/clusterawsadm/ami/list.go b/cmd/clusterawsadm/ami/list.go index b17166f75f..2b04f81422 100644 --- a/cmd/clusterawsadm/ami/list.go +++ b/cmd/clusterawsadm/ami/list.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package ami provides a way to interact with AWS AMIs. package ami import ( diff --git a/cmd/clusterawsadm/api/ami/v1beta1/scheme/scheme.go b/cmd/clusterawsadm/api/ami/v1beta1/scheme/scheme.go index 1dc2079536..851bbead25 100644 --- a/cmd/clusterawsadm/api/ami/v1beta1/scheme/scheme.go +++ b/cmd/clusterawsadm/api/ami/v1beta1/scheme/scheme.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package scheme provides a way to generate a Scheme and CodecFactory f +// or the bootstrap.aws.infrastructure.cluster.x-k8s.io API group. package scheme import ( diff --git a/cmd/clusterawsadm/api/bootstrap/v1alpha1/scheme/scheme.go b/cmd/clusterawsadm/api/bootstrap/v1alpha1/scheme/scheme.go index fc604a190f..b320f44db3 100644 --- a/cmd/clusterawsadm/api/bootstrap/v1alpha1/scheme/scheme.go +++ b/cmd/clusterawsadm/api/bootstrap/v1alpha1/scheme/scheme.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package scheme provides a way to generate a Scheme and CodecFactory +// for the bootstrap.aws.infrastructure.cluster.x-k8s.io API group. package scheme import ( diff --git a/cmd/clusterawsadm/api/bootstrap/v1beta1/scheme/scheme.go b/cmd/clusterawsadm/api/bootstrap/v1beta1/scheme/scheme.go index d84a39aee5..f70029e383 100644 --- a/cmd/clusterawsadm/api/bootstrap/v1beta1/scheme/scheme.go +++ b/cmd/clusterawsadm/api/bootstrap/v1beta1/scheme/scheme.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package scheme provides a way to generate a Scheme and CodecFactory +// for the bootstrap.aws.infrastructure.cluster.x-k8s.io API group. package scheme import ( diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go b/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go index 14f8d423bb..c91939295b 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go @@ -322,60 +322,59 @@ func (t Template) ControllersPolicy() *iamv1.PolicyDocument { // ControllersPolicyEKS creates a policy from a template for AWS Controllers. func (t Template) ControllersPolicyEKS() *iamv1.PolicyDocument { - statement := []iamv1.StatementEntry{} + statements := []iamv1.StatementEntry{} allowedIAMActions := iamv1.Actions{ "iam:GetRole", "iam:ListAttachedRolePolicies", } - statement = append(statement, iamv1.StatementEntry{ - Effect: iamv1.EffectAllow, - Resource: iamv1.Resources{ - "arn:*:ssm:*:*:parameter/aws/service/eks/optimized-ami/*", - }, - Action: iamv1.Actions{ - "ssm:GetParameter", - }, - }) - - statement = append(statement, iamv1.StatementEntry{ - Effect: iamv1.EffectAllow, - Action: iamv1.Actions{ - "iam:CreateServiceLinkedRole", - }, - Resource: iamv1.Resources{ - "arn:*:iam::*:role/aws-service-role/eks.amazonaws.com/AWSServiceRoleForAmazonEKS", - }, - Condition: iamv1.Conditions{ - iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks.amazonaws.com"}, - }, - }) - - statement = append(statement, iamv1.StatementEntry{ - Effect: iamv1.EffectAllow, - Action: iamv1.Actions{ - "iam:CreateServiceLinkedRole", - }, - Resource: iamv1.Resources{ - "arn:*:iam::*:role/aws-service-role/eks-nodegroup.amazonaws.com/AWSServiceRoleForAmazonEKSNodegroup", - }, - Condition: iamv1.Conditions{ - iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks-nodegroup.amazonaws.com"}, + statements = append(statements, + iamv1.StatementEntry{ + Effect: iamv1.EffectAllow, + Resource: iamv1.Resources{ + "arn:*:ssm:*:*:parameter/aws/service/eks/optimized-ami/*", + }, + Action: iamv1.Actions{ + "ssm:GetParameter", + }, }, - }) - - statement = append(statement, iamv1.StatementEntry{ - Effect: iamv1.EffectAllow, - Action: iamv1.Actions{ - "iam:CreateServiceLinkedRole", + iamv1.StatementEntry{ + Effect: iamv1.EffectAllow, + Action: iamv1.Actions{ + "iam:CreateServiceLinkedRole", + }, + Resource: iamv1.Resources{ + "arn:*:iam::*:role/aws-service-role/eks.amazonaws.com/AWSServiceRoleForAmazonEKS", + }, + Condition: iamv1.Conditions{ + iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks.amazonaws.com"}, + }, }, - Resource: iamv1.Resources{ - "arn:" + t.Spec.Partition + ":iam::*:role/aws-service-role/eks-fargate-pods.amazonaws.com/AWSServiceRoleForAmazonEKSForFargate", + iamv1.StatementEntry{ + Effect: iamv1.EffectAllow, + Action: iamv1.Actions{ + "iam:CreateServiceLinkedRole", + }, + Resource: iamv1.Resources{ + "arn:*:iam::*:role/aws-service-role/eks-nodegroup.amazonaws.com/AWSServiceRoleForAmazonEKSNodegroup", + }, + Condition: iamv1.Conditions{ + iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks-nodegroup.amazonaws.com"}, + }, }, - Condition: iamv1.Conditions{ - iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks-fargate.amazonaws.com"}, + iamv1.StatementEntry{ + Effect: iamv1.EffectAllow, + Action: iamv1.Actions{ + "iam:CreateServiceLinkedRole", + }, + Resource: iamv1.Resources{ + "arn:" + t.Spec.Partition + ":iam::*:role/aws-service-role/eks-fargate-pods.amazonaws.com/AWSServiceRoleForAmazonEKSForFargate", + }, + Condition: iamv1.Conditions{ + iamv1.StringLike: map[string]string{"iam:AWSServiceName": "eks-fargate.amazonaws.com"}, + }, }, - }) + ) if t.Spec.EKS.AllowIAMRoleCreation { allowedIAMActions = append(allowedIAMActions, iamv1.Actions{ @@ -386,7 +385,7 @@ func (t Template) ControllersPolicyEKS() *iamv1.PolicyDocument { "iam:AttachRolePolicy", }...) - statement = append(statement, iamv1.StatementEntry{ + statements = append(statements, iamv1.StatementEntry{ Action: iamv1.Actions{ "iam:ListOpenIDConnectProviders", "iam:GetOpenIDConnectProvider", @@ -402,7 +401,8 @@ func (t Template) ControllersPolicyEKS() *iamv1.PolicyDocument { Effect: iamv1.EffectAllow, }) } - statement = append(statement, []iamv1.StatementEntry{ + + statements = append(statements, []iamv1.StatementEntry{ { Action: allowedIAMActions, Resource: iamv1.Resources{ @@ -495,7 +495,7 @@ func (t Template) ControllersPolicyEKS() *iamv1.PolicyDocument { return &iamv1.PolicyDocument{ Version: iamv1.CurrentVersion, - Statement: statement, + Statement: statements, } } diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/iam.go b/cmd/clusterawsadm/cloudformation/bootstrap/iam.go index 1aa016606e..2a30b4ea33 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/iam.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/iam.go @@ -71,6 +71,7 @@ func (t Template) policyFunctionMap() map[PolicyName]func() *iamv1.PolicyDocumen } } +// PrintPolicyDocs prints the JSON representation of policy documents for all ManagedIAMPolicy. func (t Template) PrintPolicyDocs() error { for _, name := range ManagedIAMPolicyNames { policyDoc := t.GetPolicyDocFromPolicyName(name) diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/template.go b/cmd/clusterawsadm/cloudformation/bootstrap/template.go index 030bc248ee..c4eb4cbff7 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/template.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/template.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package bootstrap provides a way to generate a CloudFormation template for IAM policies, +// users and roles for use by Cluster API Provider AWS. package bootstrap import ( diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go b/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go index c80f2312ef..e47fbbd047 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go @@ -17,6 +17,7 @@ limitations under the License. package bootstrap import ( + "bytes" "fmt" "os" "path" @@ -201,7 +202,7 @@ func TestRenderCloudformation(t *testing.T) { t.Fatal(err) } - if string(tData) != string(data) { + if !bytes.Equal(tData, data) { dmp := diffmatchpatch.New() diffs := dmp.DiffMain(string(tData), string(data), false) out := dmp.DiffPrettyText(diffs) diff --git a/cmd/clusterawsadm/cloudformation/service/service.go b/cmd/clusterawsadm/cloudformation/service/service.go index 14a27fd2e9..33db42a8d0 100644 --- a/cmd/clusterawsadm/cloudformation/service/service.go +++ b/cmd/clusterawsadm/cloudformation/service/service.go @@ -82,6 +82,7 @@ func (s *Service) ReconcileBootstrapStack(stackName string, t go_cfn.Template, t return nil } +// ReconcileBootstrapNoUpdate creates or updates bootstrap CloudFormation without updating the stack. func (s *Service) ReconcileBootstrapNoUpdate(stackName string, t go_cfn.Template, tags map[string]string) error { yaml, err := t.YAML() processedYaml := string(yaml) diff --git a/cmd/clusterawsadm/cmd/ami/ami.go b/cmd/clusterawsadm/cmd/ami/ami.go index 0992c0723c..b4959b29e5 100644 --- a/cmd/clusterawsadm/cmd/ami/ami.go +++ b/cmd/clusterawsadm/cmd/ami/ami.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package ami provides a way to generate AMI commands. package ami import ( diff --git a/cmd/clusterawsadm/cmd/ami/common/common.go b/cmd/clusterawsadm/cmd/ami/common/common.go index 14ad2babaf..c3f79ed0de 100644 --- a/cmd/clusterawsadm/cmd/ami/common/common.go +++ b/cmd/clusterawsadm/cmd/ami/common/common.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package common provides common flags and functions for the AMI commands. package common import ( diff --git a/cmd/clusterawsadm/cmd/ami/common/copy.go b/cmd/clusterawsadm/cmd/ami/common/copy.go index 406d10f015..c2c95c6448 100644 --- a/cmd/clusterawsadm/cmd/ami/common/copy.go +++ b/cmd/clusterawsadm/cmd/ami/common/copy.go @@ -89,7 +89,6 @@ func CopyAMICmd() *cobra.Command { printer.Print(ami) - // klog.V(0).Infof("Completed copying %v\n", *image.ImageId) return nil }, } diff --git a/cmd/clusterawsadm/cmd/ami/list/list.go b/cmd/clusterawsadm/cmd/ami/list/list.go index 12ee0cfc88..5e1bef32ed 100644 --- a/cmd/clusterawsadm/cmd/ami/list/list.go +++ b/cmd/clusterawsadm/cmd/ami/list/list.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package list provides a way to list AMIs from the default AWS account where AMIs are stored. package list import ( diff --git a/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go b/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go index 00d7322f75..cfa73aa658 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go +++ b/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package bootstrap provides cli commands for bootstrapping +// AWS accounts for use with the Kubernetes Cluster API Provider AWS. package bootstrap import ( diff --git a/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go b/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go index 2abda3f3b6..0c919d7e7e 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go +++ b/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package credentials provides a way to encode credentials for use with Kubernetes Cluster API Provider AWS. package credentials import ( diff --git a/cmd/clusterawsadm/cmd/bootstrap/iam/iam_doc.go b/cmd/clusterawsadm/cmd/bootstrap/iam/iam_doc.go index f518c5cc96..775187858f 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/iam/iam_doc.go +++ b/cmd/clusterawsadm/cmd/bootstrap/iam/iam_doc.go @@ -44,7 +44,7 @@ func printPolicyCmd() *cobra.Command { clusterawsadm bootstrap iam print-policy --document AWSIAMManagedPolicyControllers # Print out the IAM policy for the Kubernetes Cluster API Provider AWS Controller using a given configuration file. - clusterawsadm bootstrap iam print-policy --document AWSIAMManagedPolicyControllers --config bootstrap_config.yaml + clusterawsadm bootstrap iam print-policy --document AWSIAMManagedPolicyControllers --config bootstrap_config.yaml # Print out the IAM policy for the Kubernetes AWS Cloud Provider for the control plane. clusterawsadm bootstrap iam print-policy --document AWSIAMManagedPolicyCloudProviderControlPlane diff --git a/cmd/clusterawsadm/cmd/bootstrap/iam/root.go b/cmd/clusterawsadm/cmd/bootstrap/iam/root.go index 1f9f2b9ca5..491610cd59 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/iam/root.go +++ b/cmd/clusterawsadm/cmd/bootstrap/iam/root.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package iam provides a way to generate IAM policies and roles. package iam import ( diff --git a/cmd/clusterawsadm/cmd/controller/controller.go b/cmd/clusterawsadm/cmd/controller/controller.go index a8897cea08..31e018d432 100644 --- a/cmd/clusterawsadm/cmd/controller/controller.go +++ b/cmd/clusterawsadm/cmd/controller/controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controller provides the controller command. package controller import ( diff --git a/cmd/clusterawsadm/cmd/controller/credentials/print.go b/cmd/clusterawsadm/cmd/controller/credentials/print.go index b88621cf25..0b4e27094a 100644 --- a/cmd/clusterawsadm/cmd/controller/credentials/print.go +++ b/cmd/clusterawsadm/cmd/controller/credentials/print.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package credentials provides a CLI utilities for AWS credentials. package credentials import ( diff --git a/cmd/clusterawsadm/cmd/controller/rollout/common.go b/cmd/clusterawsadm/cmd/controller/rollout/common.go index 37cc67b6e9..47707f3970 100644 --- a/cmd/clusterawsadm/cmd/controller/rollout/common.go +++ b/cmd/clusterawsadm/cmd/controller/rollout/common.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package rollout provides the rollout command. package rollout import ( diff --git a/cmd/clusterawsadm/cmd/eks/addons/addons.go b/cmd/clusterawsadm/cmd/eks/addons/addons.go index 3b8ae23e76..709f2f2cf3 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/addons.go +++ b/cmd/clusterawsadm/cmd/eks/addons/addons.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package addons provides EKS addons commands. package addons import "github.com/spf13/cobra" diff --git a/cmd/clusterawsadm/cmd/eks/addons/list_installed.go b/cmd/clusterawsadm/cmd/eks/addons/list_installed.go index 827c944e0a..cb73ee64b5 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/list_installed.go +++ b/cmd/clusterawsadm/cmd/eks/addons/list_installed.go @@ -113,10 +113,10 @@ func listInstalledAddons(region, clusterName, printerType *string) error { newIssue := issue{ Code: *addonIssue.Code, Message: *addonIssue.Message, - ResourceIds: []string{}, + ResourceIDs: []string{}, } for _, resID := range addonIssue.ResourceIds { - newIssue.ResourceIds = append(newIssue.ResourceIds, *resID) + newIssue.ResourceIDs = append(newIssue.ResourceIDs, *resID) } installedAddon.HealthIssues = append(installedAddon.HealthIssues, newIssue) } diff --git a/cmd/clusterawsadm/cmd/eks/addons/types.go b/cmd/clusterawsadm/cmd/eks/addons/types.go index a59368f8f6..9c9ae62616 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/types.go +++ b/cmd/clusterawsadm/cmd/eks/addons/types.go @@ -106,7 +106,7 @@ type installedAddon struct { type issue struct { Code string Message string - ResourceIds []string + ResourceIDs []string } type installedAddonsList struct { diff --git a/cmd/clusterawsadm/cmd/eks/eks.go b/cmd/clusterawsadm/cmd/eks/eks.go index 42d271f481..8856216aa8 100644 --- a/cmd/clusterawsadm/cmd/eks/eks.go +++ b/cmd/clusterawsadm/cmd/eks/eks.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package eks provides a CLI to manage EKS clusters. package eks import ( diff --git a/cmd/clusterawsadm/cmd/flags/common.go b/cmd/clusterawsadm/cmd/flags/common.go index 096d289927..d6d7e4e808 100644 --- a/cmd/clusterawsadm/cmd/flags/common.go +++ b/cmd/clusterawsadm/cmd/flags/common.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package flags provides a way to add flags to the cli. package flags import ( diff --git a/cmd/clusterawsadm/cmd/gc/gc.go b/cmd/clusterawsadm/cmd/gc/gc.go index 0bd0344514..c9d91bf703 100644 --- a/cmd/clusterawsadm/cmd/gc/gc.go +++ b/cmd/clusterawsadm/cmd/gc/gc.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package gc provides commands related to garbage collecting external resources of clusters. package gc import ( @@ -27,10 +28,7 @@ func RootCmd() *cobra.Command { Short: "Commands related to garbage collecting external resources of clusters", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/resource/list/list.go b/cmd/clusterawsadm/cmd/resource/list/list.go index 01b84e2ae4..1e65ef61ad 100644 --- a/cmd/clusterawsadm/cmd/resource/list/list.go +++ b/cmd/clusterawsadm/cmd/resource/list/list.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package list provides the list command for the resource package. package list import ( @@ -38,7 +39,7 @@ func ListAWSResourceCmd() *cobra.Command { Short: "List all AWS resources created by CAPA", Long: cmd.LongDesc(` List AWS resources directly created by CAPA based on region and cluster-name. There are some indirect resources like Cloudwatch alarms, rules, etc - which are not directly created by CAPA, so those resources are not listed here. + which are not directly created by CAPA, so those resources are not listed here. If region and cluster-name are not set, then it will throw an error. `), Example: cmd.Examples(` diff --git a/cmd/clusterawsadm/cmd/resource/resource.go b/cmd/clusterawsadm/cmd/resource/resource.go index 36e5aa3e25..c2cbde7a6a 100644 --- a/cmd/clusterawsadm/cmd/resource/resource.go +++ b/cmd/clusterawsadm/cmd/resource/resource.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package resource provides commands related to AWS resources. package resource import ( @@ -34,10 +35,7 @@ func RootCmd() *cobra.Command { # List of AWS resources created by CAPA `), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/root.go b/cmd/clusterawsadm/cmd/root.go index dc25175824..0c0b2b5614 100644 --- a/cmd/clusterawsadm/cmd/root.go +++ b/cmd/clusterawsadm/cmd/root.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cmd implements the clusterawsadm command line utility. package cmd import ( @@ -63,7 +64,7 @@ func RootCmd() *cobra.Command { export AWS_B64ENCODED_CREDENTIALS=$(clusterawsadm bootstrap credentials encode-as-profile) clusterctl init --infrastructure aws `), - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/util/util.go b/cmd/clusterawsadm/cmd/util/util.go index 8e714ed80c..7b974add4a 100644 --- a/cmd/clusterawsadm/cmd/util/util.go +++ b/cmd/clusterawsadm/cmd/util/util.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package util provides utility functions. package util import ( diff --git a/cmd/clusterawsadm/cmd/version/version.go b/cmd/clusterawsadm/cmd/version/version.go index db85908013..23930f6fde 100644 --- a/cmd/clusterawsadm/cmd/version/version.go +++ b/cmd/clusterawsadm/cmd/version/version.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package version provides the version information of clusterawsadm. package version import ( diff --git a/cmd/clusterawsadm/configreader/configreader.go b/cmd/clusterawsadm/configreader/configreader.go index 3047152cb6..e5b1d800cd 100644 --- a/cmd/clusterawsadm/configreader/configreader.go +++ b/cmd/clusterawsadm/configreader/configreader.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package configreader provides a way to load a bootstrapv1.AWSIAMConfiguration from a file. package configreader import ( diff --git a/cmd/clusterawsadm/controller/credentials/update_credentials.go b/cmd/clusterawsadm/controller/credentials/update_credentials.go index e4a9d1afc4..eba621cb3e 100644 --- a/cmd/clusterawsadm/controller/credentials/update_credentials.go +++ b/cmd/clusterawsadm/controller/credentials/update_credentials.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package credentials provides AWS credentials management. package credentials import ( @@ -49,7 +50,7 @@ func UpdateCredentials(input UpdateCredentialsInput) error { creds = "Cg==" } - patch := fmt.Sprintf("{\"data\":{\"credentials\": \"%s\"}}", creds) + patch := fmt.Sprintf("{\"data\":{\"credentials\": %q}}", creds) _, err = client.CoreV1().Secrets(input.Namespace).Patch( context.TODO(), controller.BootstrapCredsSecret, diff --git a/cmd/clusterawsadm/controller/helper.go b/cmd/clusterawsadm/controller/helper.go index d7ff024ff2..809678bf2b 100644 --- a/cmd/clusterawsadm/controller/helper.go +++ b/cmd/clusterawsadm/controller/helper.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controller contains the controller logic for the capa manager. package controller import ( diff --git a/cmd/clusterawsadm/controller/rollout/rollout.go b/cmd/clusterawsadm/controller/rollout/rollout.go index 12f9f722cd..eb55e32947 100644 --- a/cmd/clusterawsadm/controller/rollout/rollout.go +++ b/cmd/clusterawsadm/controller/rollout/rollout.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package rollout provides a way to rollout the CAPA controller manager deployment. package rollout import ( diff --git a/cmd/clusterawsadm/converters/iam.go b/cmd/clusterawsadm/converters/iam.go index cecf4f5530..a571962fee 100644 --- a/cmd/clusterawsadm/converters/iam.go +++ b/cmd/clusterawsadm/converters/iam.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package converters contains the conversion functions for AWS. package converters import ( diff --git a/cmd/clusterawsadm/credentials/credentials.go b/cmd/clusterawsadm/credentials/credentials.go index 4c640dfbfe..2aa320839a 100644 --- a/cmd/clusterawsadm/credentials/credentials.go +++ b/cmd/clusterawsadm/credentials/credentials.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package credentials contains utilities for working with AWS credentials. package credentials import ( diff --git a/cmd/clusterawsadm/gc/gc.go b/cmd/clusterawsadm/gc/gc.go index 046c841be6..27a9887d41 100644 --- a/cmd/clusterawsadm/gc/gc.go +++ b/cmd/clusterawsadm/gc/gc.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package gc provides a way to handle AWS garbage collection on deletion. package gc import ( @@ -23,8 +24,8 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - _ "k8s.io/client-go/plugin/pkg/client/auth/exec" - _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" + _ "k8s.io/client-go/plugin/pkg/client/auth/exec" // import all auth plugins + _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" // import all oidc plugins "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/cmd/clusterawsadm/main.go b/cmd/clusterawsadm/main.go index bd97bc0adb..0a30981ed0 100644 --- a/cmd/clusterawsadm/main.go +++ b/cmd/clusterawsadm/main.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package main is the entrypoint for the clusterawsadm command. package main import "sigs.k8s.io/cluster-api-provider-aws/v2/cmd/clusterawsadm/cmd" diff --git a/cmd/clusterawsadm/printers/printers.go b/cmd/clusterawsadm/printers/printers.go index 4d3b6aa713..0c106aca12 100644 --- a/cmd/clusterawsadm/printers/printers.go +++ b/cmd/clusterawsadm/printers/printers.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package printers provides a wrapper for the k8s.io/cli-runtime/pkg/printers package. package printers import ( diff --git a/cmd/clusterawsadm/resource/type.go b/cmd/clusterawsadm/resource/type.go index e5b344aff3..0dda210426 100644 --- a/cmd/clusterawsadm/resource/type.go +++ b/cmd/clusterawsadm/resource/type.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package resource provides definitions for AWS resource types. package resource import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/config/crd/bases/controlplane.cluster.x-k8s.io_rosacontrolplanes.yaml b/config/crd/bases/controlplane.cluster.x-k8s.io_rosacontrolplanes.yaml index b38308d4f9..61b3e37648 100644 --- a/config/crd/bases/controlplane.cluster.x-k8s.io_rosacontrolplanes.yaml +++ b/config/crd/bases/controlplane.cluster.x-k8s.io_rosacontrolplanes.yaml @@ -30,6 +30,7 @@ spec: name: v1beta2 schema: openAPIV3Schema: + description: ROSAControlPlane is the Schema for the ROSAControlPlanes API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -44,6 +45,7 @@ spec: metadata: type: object spec: + description: RosaControlPlaneSpec defines the desired state of ROSAControlPlane. properties: autoscaling: description: Autoscaling specifies auto scaling behaviour for the @@ -356,6 +358,7 @@ spec: - workerRoleARN type: object status: + description: RosaControlPlaneStatus defines the observed state of ROSAControlPlane. properties: conditions: description: Conditions specifies the cpnditions for the managed control diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclustertemplates.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclustertemplates.yaml index df369e0c2d..e8ef04c449 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclustertemplates.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclustertemplates.yaml @@ -45,6 +45,8 @@ spec: description: AWSClusterTemplateSpec defines the desired state of AWSClusterTemplate. properties: template: + description: AWSClusterTemplateResource defines the desired state + of AWSClusterTemplate. properties: metadata: description: 'Standard object''s metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata' @@ -474,6 +476,8 @@ spec: description: AWSClusterTemplateSpec defines the desired state of AWSClusterTemplate. properties: template: + description: AWSClusterTemplateResource defines the desired state + of AWSClusterTemplateResource. properties: metadata: description: 'Standard object''s metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata' diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_rosaclusters.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_rosaclusters.yaml index 710e61955a..532f17359e 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_rosaclusters.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_rosaclusters.yaml @@ -35,6 +35,7 @@ spec: name: v1beta2 schema: openAPIV3Schema: + description: ROSACluster is the Schema for the ROSAClusters API. properties: apiVersion: description: 'APIVersion defines the versioned schema of this representation @@ -49,6 +50,7 @@ spec: metadata: type: object spec: + description: ROSAClusterSpec defines the desired state of ROSACluster. properties: controlPlaneEndpoint: description: ControlPlaneEndpoint represents the endpoint used to @@ -67,7 +69,7 @@ spec: type: object type: object status: - description: ROSAClusterStatus defines the observed state of ROSACluster + description: ROSAClusterStatus defines the observed state of ROSACluster. properties: failureDomains: additionalProperties: diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_rosamachinepools.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_rosamachinepools.yaml index e4a9c9fe14..7fe083bcdb 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_rosamachinepools.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_rosamachinepools.yaml @@ -107,6 +107,7 @@ spec: description: Taints specifies the taints to apply to the nodes of the machine pool items: + description: RosaTaint represents a taint to be applied to a node. properties: effect: description: The effect of the taint on pods that do not tolerate diff --git a/controllers/awsmachine_controller.go b/controllers/awsmachine_controller.go index 416ba0c420..038e849edb 100644 --- a/controllers/awsmachine_controller.go +++ b/controllers/awsmachine_controller.go @@ -503,7 +503,7 @@ func (r *AWSMachineReconciler) reconcileNormal(_ context.Context, machineScope * // Avoid a flickering condition between InstanceProvisionStarted and InstanceProvisionFailed if there's a persistent failure with createInstance if conditions.GetReason(machineScope.AWSMachine, infrav1.InstanceReadyCondition) != infrav1.InstanceProvisionFailedReason { conditions.MarkFalse(machineScope.AWSMachine, infrav1.InstanceReadyCondition, infrav1.InstanceProvisionStartedReason, clusterv1.ConditionSeverityInfo, "") - if patchErr := machineScope.PatchObject(); err != nil { + if patchErr := machineScope.PatchObject(); patchErr != nil { machineScope.Error(patchErr, "failed to patch conditions") return ctrl.Result{}, patchErr } @@ -912,17 +912,10 @@ func (r *AWSMachineReconciler) reconcileLBAttachment(machineScope *scope.Machine func (r *AWSMachineReconciler) registerInstanceToLBs(machineScope *scope.MachineScope, elbsvc services.ELBInterface, i *infrav1.Instance, lb *infrav1.AWSLoadBalancerSpec) error { switch lb.LoadBalancerType { - case infrav1.LoadBalancerTypeClassic: - fallthrough - case "": + case infrav1.LoadBalancerTypeClassic, "": machineScope.Debug("registering to classic load balancer") return r.registerInstanceToClassicLB(machineScope, elbsvc, i) - - case infrav1.LoadBalancerTypeELB: - fallthrough - case infrav1.LoadBalancerTypeALB: - fallthrough - case infrav1.LoadBalancerTypeNLB: + case infrav1.LoadBalancerTypeELB, infrav1.LoadBalancerTypeALB, infrav1.LoadBalancerTypeNLB: machineScope.Debug("registering to v2 load balancer") return r.registerInstanceToV2LB(machineScope, elbsvc, i, lb) } diff --git a/controllers/rosacluster_controller.go b/controllers/rosacluster_controller.go index e57cb7402a..d81716e72b 100644 --- a/controllers/rosacluster_controller.go +++ b/controllers/rosacluster_controller.go @@ -109,7 +109,6 @@ func (r *ROSAClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) // Set the values from the managed control plane rosaCluster.Status.Ready = true rosaCluster.Spec.ControlPlaneEndpoint = controlPlane.Spec.ControlPlaneEndpoint - // rosaCluster.Status.FailureDomains = controlPlane.Status.FailureDomains if err := patchHelper.Patch(ctx, rosaCluster); err != nil { return reconcile.Result{}, fmt.Errorf("failed to patch ROSACluster: %w", err) diff --git a/controlplane/eks/api/v1beta1/awsmanagedcontrolplane_types.go b/controlplane/eks/api/v1beta1/awsmanagedcontrolplane_types.go index 4f7fc33cc5..a965bef381 100644 --- a/controlplane/eks/api/v1beta1/awsmanagedcontrolplane_types.go +++ b/controlplane/eks/api/v1beta1/awsmanagedcontrolplane_types.go @@ -228,6 +228,7 @@ type OIDCProviderStatus struct { TrustPolicy string `json:"trustPolicy,omitempty"` } +// IdentityProviderStatus holds the status for associated identity provider type IdentityProviderStatus struct { // ARN holds the ARN of associated identity provider ARN string `json:"arn,omitempty"` diff --git a/controlplane/eks/api/v1beta1/conversion_test.go b/controlplane/eks/api/v1beta1/conversion_test.go index 207a6b6695..b7b360d1d1 100644 --- a/controlplane/eks/api/v1beta1/conversion_test.go +++ b/controlplane/eks/api/v1beta1/conversion_test.go @@ -19,9 +19,8 @@ package v1beta1 import ( "testing" - . "github.com/onsi/gomega" - fuzz "github.com/google/gofuzz" + . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" "k8s.io/apimachinery/pkg/runtime" runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" diff --git a/controlplane/eks/api/v1beta1/types.go b/controlplane/eks/api/v1beta1/types.go index a85c433303..0ca9a64ebe 100644 --- a/controlplane/eks/api/v1beta1/types.go +++ b/controlplane/eks/api/v1beta1/types.go @@ -218,8 +218,8 @@ const ( SecurityGroupCluster = infrav1.SecurityGroupRole("cluster") ) +// OIDCIdentityProviderConfig defines the configuration for an OIDC identity provider. type OIDCIdentityProviderConfig struct { - // This is also known as audience. The ID for the client application that makes // authentication requests to the OpenID identity provider. // +kubebuilder:validation:Required diff --git a/controlplane/eks/api/v1beta2/awsmanagedcontrolplane_types.go b/controlplane/eks/api/v1beta2/awsmanagedcontrolplane_types.go index 89d5e8bc2b..fa96f494d8 100644 --- a/controlplane/eks/api/v1beta2/awsmanagedcontrolplane_types.go +++ b/controlplane/eks/api/v1beta2/awsmanagedcontrolplane_types.go @@ -231,6 +231,7 @@ type OIDCProviderStatus struct { TrustPolicy string `json:"trustPolicy,omitempty"` } +// IdentityProviderStatus holds the status for associated identity provider. type IdentityProviderStatus struct { // ARN holds the ARN of associated identity provider ARN string `json:"arn,omitempty"` diff --git a/controlplane/eks/api/v1beta2/doc.go b/controlplane/eks/api/v1beta2/doc.go index b2fbc38795..8409bb024f 100644 --- a/controlplane/eks/api/v1beta2/doc.go +++ b/controlplane/eks/api/v1beta2/doc.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group +// Package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group // +gencrdrefdocs:force // +groupName=controlplane.cluster.x-k8s.io // +k8s:defaulter-gen=TypeMeta diff --git a/controlplane/eks/api/v1beta2/groupversion_info.go b/controlplane/eks/api/v1beta2/groupversion_info.go index fcc0abb3a5..9fc8227082 100644 --- a/controlplane/eks/api/v1beta2/groupversion_info.go +++ b/controlplane/eks/api/v1beta2/groupversion_info.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group +// Package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group // +kubebuilder:object:generate=true // +groupName=controlplane.cluster.x-k8s.io package v1beta2 diff --git a/controlplane/eks/api/v1beta2/types.go b/controlplane/eks/api/v1beta2/types.go index acaa53b419..1ef47215ce 100644 --- a/controlplane/eks/api/v1beta2/types.go +++ b/controlplane/eks/api/v1beta2/types.go @@ -218,8 +218,8 @@ const ( SecurityGroupCluster = infrav1.SecurityGroupRole("cluster") ) +// OIDCIdentityProviderConfig represents the configuration for an OIDC identity provider. type OIDCIdentityProviderConfig struct { - // This is also known as audience. The ID for the client application that makes // authentication requests to the OpenID identity provider. // +kubebuilder:validation:Required diff --git a/controlplane/rosa/api/v1beta2/groupversion_info.go b/controlplane/rosa/api/v1beta2/groupversion_info.go index 9eeee3d76c..ea4ec8f784 100644 --- a/controlplane/rosa/api/v1beta2/groupversion_info.go +++ b/controlplane/rosa/api/v1beta2/groupversion_info.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group +// Package v1beta2 contains API Schema definitions for the controlplane v1beta2 API group. // +kubebuilder:object:generate=true // +groupName=controlplane.cluster.x-k8s.io package v1beta2 diff --git a/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go b/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go index 27e1c27348..c6c00f43c8 100644 --- a/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go +++ b/controlplane/rosa/api/v1beta2/rosacontrolplane_types.go @@ -25,6 +25,7 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) +// RosaControlPlaneSpec defines the desired state of ROSAControlPlane. type RosaControlPlaneSpec struct { //nolint: maligned // Cluster name must be valid DNS-1035 label, so it must consist of lower case alphanumeric // characters or '-', start with an alphabetic character, end with an alphanumeric character @@ -509,6 +510,7 @@ type AWSRolesRef struct { KMSProviderARN string `json:"kmsProviderARN"` } +// RosaControlPlaneStatus defines the observed state of ROSAControlPlane. type RosaControlPlaneStatus struct { // ExternalManagedControlPlane indicates to cluster-api that the control plane // is managed by an external service such as AKS, EKS, GKE, etc. @@ -551,6 +553,7 @@ type RosaControlPlaneStatus struct { // +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.ready",description="Control plane infrastructure is ready for worker nodes" // +k8s:defaulter-gen=true +// ROSAControlPlane is the Schema for the ROSAControlPlanes API. type ROSAControlPlane struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -561,6 +564,7 @@ type ROSAControlPlane struct { // +kubebuilder:object:root=true +// ROSAControlPlaneList contains a list of ROSAControlPlane. type ROSAControlPlaneList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/controlplane/rosa/controllers/rosacontrolplane_controller.go b/controlplane/rosa/controllers/rosacontrolplane_controller.go index aecf06ab2f..d9b27893af 100644 --- a/controlplane/rosa/controllers/rosacontrolplane_controller.go +++ b/controlplane/rosa/controllers/rosacontrolplane_controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controllers provides a way to reconcile ROSA resources. package controllers import ( @@ -67,6 +68,7 @@ const ( ROSAControlPlaneFinalizer = "rosacontrolplane.controlplane.cluster.x-k8s.io" ) +// ROSAControlPlaneReconciler reconciles a ROSAControlPlane object. type ROSAControlPlaneReconciler struct { client.Client WatchFilterValue string @@ -179,10 +181,6 @@ func (r *ROSAControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.Req func (r *ROSAControlPlaneReconciler) reconcileNormal(ctx context.Context, rosaScope *scope.ROSAControlPlaneScope) (res ctrl.Result, reterr error) { rosaScope.Info("Reconciling ROSAControlPlane") - // if !rosaScope.Cluster.Status.InfrastructureReady { - // rosaScope.Info("Cluster infrastructure is not ready yet") - // return ctrl.Result{RequeueAfter: r.WaitInfraPeriod}, nil - //} if controllerutil.AddFinalizer(rosaScope.ControlPlane, ROSAControlPlaneFinalizer) { if err := rosaScope.PatchObject(); err != nil { return ctrl.Result{}, err @@ -215,6 +213,7 @@ func (r *ROSAControlPlaneReconciler) reconcileNormal(ctx context.Context, rosaSc // dont' requeue because input is invalid and manual intervention is needed. return ctrl.Result{}, nil } + rosaScope.ControlPlane.Status.FailureMessage = nil cluster, err := ocmClient.GetCluster(rosaScope.ControlPlane.Spec.RosaClusterName, creator) if err != nil && weberr.GetType(err) != weberr.NotFound { diff --git a/docs/book/cmd/amilist/main.go b/docs/book/cmd/amilist/main.go index 33cc0113e8..a6e5513bbe 100644 --- a/docs/book/cmd/amilist/main.go +++ b/docs/book/cmd/amilist/main.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package main provides a Lambda function to list AMIs and upload them to an S3 bucket. package main import ( diff --git a/docs/book/cmd/clusterawsadmdocs/main.go b/docs/book/cmd/clusterawsadmdocs/main.go index 05c6de2866..69c7c1d42d 100644 --- a/docs/book/cmd/clusterawsadmdocs/main.go +++ b/docs/book/cmd/clusterawsadmdocs/main.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package main provides a way to generate a command reference for clusterawsadm. package main import ( diff --git a/docs/triage-party/triage-party-deployment.go b/docs/triage-party/triage-party-deployment.go index d7c278521d..53af6beac9 100644 --- a/docs/triage-party/triage-party-deployment.go +++ b/docs/triage-party/triage-party-deployment.go @@ -18,11 +18,9 @@ package main import ( "fmt" - - "github.com/aws/aws-cdk-go/awscdk" - "os" + "github.com/aws/aws-cdk-go/awscdk" "github.com/aws/aws-cdk-go/awscdk/awsecs" "github.com/aws/aws-cdk-go/awscdk/awsecspatterns" "github.com/aws/aws-cdk-go/awscdk/awselasticloadbalancingv2" diff --git a/exp/api/v1beta1/conversion.go b/exp/api/v1beta1/conversion.go index ff55f3b930..16cf651fdf 100644 --- a/exp/api/v1beta1/conversion.go +++ b/exp/api/v1beta1/conversion.go @@ -18,12 +18,11 @@ package v1beta1 import ( apiconversion "k8s.io/apimachinery/pkg/conversion" - utilconversion "sigs.k8s.io/cluster-api/util/conversion" - "sigs.k8s.io/controller-runtime/pkg/conversion" - infrav1beta1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta1" infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2" infrav1exp "sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2" + utilconversion "sigs.k8s.io/cluster-api/util/conversion" + "sigs.k8s.io/controller-runtime/pkg/conversion" ) // ConvertTo converts the v1beta1 AWSMachinePool receiver to a v1beta2 AWSMachinePool. diff --git a/exp/api/v1beta1/conversion_test.go b/exp/api/v1beta1/conversion_test.go index 5992c664be..3cedcf3342 100644 --- a/exp/api/v1beta1/conversion_test.go +++ b/exp/api/v1beta1/conversion_test.go @@ -21,7 +21,6 @@ import ( . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/cluster-api-provider-aws/v2/exp/api/v1beta2" utilconversion "sigs.k8s.io/cluster-api/util/conversion" ) diff --git a/exp/api/v1beta2/awsmachinepool_webhook.go b/exp/api/v1beta2/awsmachinepool_webhook.go index 41af26b9e9..ab434ffb4b 100644 --- a/exp/api/v1beta2/awsmachinepool_webhook.go +++ b/exp/api/v1beta2/awsmachinepool_webhook.go @@ -141,7 +141,7 @@ func (r *AWSMachinePool) ValidateCreate() (admission.Warnings, error) { } // ValidateUpdate will do any extra validation when updating a AWSMachinePool. -func (r *AWSMachinePool) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { +func (r *AWSMachinePool) ValidateUpdate(_ runtime.Object) (admission.Warnings, error) { var allErrs field.ErrorList allErrs = append(allErrs, r.validateDefaultCoolDown()...) diff --git a/exp/api/v1beta2/groupversion_info.go b/exp/api/v1beta2/groupversion_info.go index a54b837a42..c1a5f0bed2 100644 --- a/exp/api/v1beta2/groupversion_info.go +++ b/exp/api/v1beta2/groupversion_info.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// package v1beta2 contains API Schema definitions for experimental v1beta2 API group +// Package v1beta2 contains API Schema definitions for experimental v1beta2 API group // +kubebuilder:object:generate=true // +groupName=infrastructure.cluster.x-k8s.io package v1beta2 diff --git a/exp/api/v1beta2/rosacluster_types.go b/exp/api/v1beta2/rosacluster_types.go index ed08317c50..1b3ffa5d77 100644 --- a/exp/api/v1beta2/rosacluster_types.go +++ b/exp/api/v1beta2/rosacluster_types.go @@ -22,13 +22,14 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) +// ROSAClusterSpec defines the desired state of ROSACluster. type ROSAClusterSpec struct { // ControlPlaneEndpoint represents the endpoint used to communicate with the control plane. // +optional ControlPlaneEndpoint clusterv1.APIEndpoint `json:"controlPlaneEndpoint"` } -// ROSAClusterStatus defines the observed state of ROSACluster +// ROSAClusterStatus defines the observed state of ROSACluster. type ROSAClusterStatus struct { // Ready is when the ROSAControlPlane has a API server URL. // +optional @@ -47,6 +48,7 @@ type ROSAClusterStatus struct { // +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.ready",description="Control plane infrastructure is ready for worker nodes" // +kubebuilder:printcolumn:name="Endpoint",type="string",JSONPath=".spec.controlPlaneEndpoint.host",description="API Endpoint",priority=1 +// ROSACluster is the Schema for the ROSAClusters API. type ROSACluster struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1beta2/rosamachinepool_types.go b/exp/api/v1beta2/rosamachinepool_types.go index 67a9769950..1facd90116 100644 --- a/exp/api/v1beta2/rosamachinepool_types.go +++ b/exp/api/v1beta2/rosamachinepool_types.go @@ -91,6 +91,7 @@ type RosaMachinePoolSpec struct { ProviderIDList []string `json:"providerIDList,omitempty"` } +// RosaTaint represents a taint to be applied to a node. type RosaTaint struct { // The taint key to be applied to a node. // diff --git a/exp/controlleridentitycreator/awscontrolleridentity_controller.go b/exp/controlleridentitycreator/awscontrolleridentity_controller.go index 0060d712de..bc3a557529 100644 --- a/exp/controlleridentitycreator/awscontrolleridentity_controller.go +++ b/exp/controlleridentitycreator/awscontrolleridentity_controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controlleridentitycreator provides a way to reconcile AWSClusterControllerIdentity instance. package controlleridentitycreator import ( diff --git a/exp/controllers/awsmachinepool_controller.go b/exp/controllers/awsmachinepool_controller.go index 1a30c90314..8114604c7a 100644 --- a/exp/controllers/awsmachinepool_controller.go +++ b/exp/controllers/awsmachinepool_controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package controllers provides experimental API controllers. package controllers import ( diff --git a/exp/controllers/awsmachinepool_controller_test.go b/exp/controllers/awsmachinepool_controller_test.go index 447ecd3fab..4448fb94f3 100644 --- a/exp/controllers/awsmachinepool_controller_test.go +++ b/exp/controllers/awsmachinepool_controller_test.go @@ -773,7 +773,7 @@ func TestAWSMachinePoolReconciler(t *testing.T) { }) } -//TODO: This was taken from awsmachine_controller_test, i think it should be moved to elsewhere in both locations like test/helpers +//TODO: This was taken from awsmachine_controller_test, i think it should be moved to elsewhere in both locations like test/helpers. type conditionAssertion struct { conditionType clusterv1.ConditionType diff --git a/exp/controllers/rosamachinepool_controller.go b/exp/controllers/rosamachinepool_controller.go index 88bf270bdd..8d1936c309 100644 --- a/exp/controllers/rosamachinepool_controller.go +++ b/exp/controllers/rosamachinepool_controller.go @@ -197,9 +197,8 @@ func (r *ROSAMachinePoolReconciler) reconcileNormal(ctx context.Context, machinePoolScope.RosaMachinePool.Status.FailureMessage = failureMessage // dont' requeue because input is invalid and manual intervention is needed. return ctrl.Result{}, nil - } else { - machinePoolScope.RosaMachinePool.Status.FailureMessage = nil } + machinePoolScope.RosaMachinePool.Status.FailureMessage = nil rosaMachinePool := machinePoolScope.RosaMachinePool machinePool := machinePoolScope.MachinePool diff --git a/exp/doc.go b/exp/doc.go index 1c9b3ddc0b..84020d8a62 100644 --- a/exp/doc.go +++ b/exp/doc.go @@ -14,4 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package exp provides experimental code that is not ready for production use. package exp diff --git a/exp/instancestate/awsinstancestate_controller.go b/exp/instancestate/awsinstancestate_controller.go index c04f8687c4..15464eae61 100644 --- a/exp/instancestate/awsinstancestate_controller.go +++ b/exp/instancestate/awsinstancestate_controller.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package instancestate provides a controller that listens +// for EC2 instance state change notifications and updates the corresponding AWSMachine's status. package instancestate import ( diff --git a/feature/feature.go b/feature/feature.go index 8180138e2b..916aebb640 100644 --- a/feature/feature.go +++ b/feature/feature.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package feature provides a feature-gate implementation for capa. package feature import ( diff --git a/hack/boilerplate/test/fail.go b/hack/boilerplate/test/fail.go index fd911e499c..fa814ad151 100644 --- a/hack/boilerplate/test/fail.go +++ b/hack/boilerplate/test/fail.go @@ -16,4 +16,5 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package test provides a test package for boilerplate. package test diff --git a/hack/tools/Makefile b/hack/tools/Makefile index c530239c9b..15df974f60 100644 --- a/hack/tools/Makefile +++ b/hack/tools/Makefile @@ -165,15 +165,6 @@ YQ := $(BIN_DIR)/$(YQ_BIN) $(YQ): CGO_ENABLED=0 go build -tags=tools -o $@ github.com/mikefarah/yq/v4 -GOLANGCI_LINT_BIN := golangci-lint -GOLANGCI_LINT := $(BIN_DIR)/$(GOLANGCI_LINT_BIN) -GOLANGCI_LINT_PKG := github.com/golangci/golangci-lint/cmd/golangci-lint -.PHONY: $(GOLANGCI_LINT_BIN) -$(GOLANGCI_LINT_BIN): $(GOLANGCI_LINT) ## Build a local copy of golangci-lint. - -$(GOLANGCI_LINT): # Build golangci-lint from tools folder. - GOBIN=$(abspath $(BIN_DIR)) go install $(GOLANGCI_LINT_PKG)@$(GOLANGCI_LINT_VERSION) - RELEASE_NOTES_BIN := release-notes RELEASE_NOTES := $(BIN_DIR)/$(RELEASE_NOTES_BIN) RELEASE_NOTES_PKG := k8s.io/release/cmd/release-notes diff --git a/hack/tools/third_party/conversion-gen/generators/conversion.go b/hack/tools/third_party/conversion-gen/generators/conversion.go index f6d6c782c4..a4b127aea4 100644 --- a/hack/tools/third_party/conversion-gen/generators/conversion.go +++ b/hack/tools/third_party/conversion-gen/generators/conversion.go @@ -25,15 +25,13 @@ import ( "sort" "strings" + conversionargs "k8s.io/code-generator/cmd/conversion-gen/args" + genutil "k8s.io/code-generator/pkg/util" "k8s.io/gengo/args" "k8s.io/gengo/generator" "k8s.io/gengo/namer" "k8s.io/gengo/types" - "k8s.io/klog/v2" - - conversionargs "k8s.io/code-generator/cmd/conversion-gen/args" - genutil "k8s.io/code-generator/pkg/util" ) // These are the comment tags that carry parameters for conversion generation. diff --git a/hack/tools/third_party/conversion-gen/main.go b/hack/tools/third_party/conversion-gen/main.go index eae9db7eac..c8d859612d 100644 --- a/hack/tools/third_party/conversion-gen/main.go +++ b/hack/tools/third_party/conversion-gen/main.go @@ -63,7 +63,7 @@ limitations under the License. // fundamentally differently typed fields. // // `conversion-gen` will scan its `--input-dirs`, looking at the -// package defined in each of those directories for comment tags that +// Package defined in each of those directories for comment tags that // define a conversion code generation task. A package requests // conversion code generation by including one or more comment in the // package's `doc.go` file (currently anywhere in that file is @@ -73,7 +73,7 @@ limitations under the License. // // +k8s:conversion-gen= // // This introduces a conversion task, for which the destination -// package is the one containing the file with the tag and the tag +// Package is the one containing the file with the tag and the tag // identifies a package containing internal types. If there is also a // tag of the form // @@ -98,9 +98,8 @@ import ( "flag" "github.com/spf13/pflag" - "k8s.io/klog/v2" - generatorargs "k8s.io/code-generator/cmd/conversion-gen/args" + "k8s.io/klog/v2" "sigs.k8s.io/cluster-api-provider-aws/hack/tools/third_party/conversion-gen/generators" ) diff --git a/iam/api/v1beta1/types.go b/iam/api/v1beta1/types.go index 3147969066..527c857be9 100644 --- a/iam/api/v1beta1/types.go +++ b/iam/api/v1beta1/types.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package v1beta1 contains API Schema definitions for the iam v1beta1 API group. // +k8s:deepcopy-gen=package,register // +k8s:defaulter-gen=TypeMeta // +groupName=iam.aws.infrastructure.cluster.x-k8s.io diff --git a/main.go b/main.go index 8f38b3f49f..35d324dcc6 100644 --- a/main.go +++ b/main.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package main contains the main entrypoint for the AWS provider components. package main import ( diff --git a/pkg/annotations/annotations.go b/pkg/annotations/annotations.go index debcd25153..8bc4a00ff3 100644 --- a/pkg/annotations/annotations.go +++ b/pkg/annotations/annotations.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package annotations provides utility functions for working with annotations. package annotations import ( diff --git a/pkg/cloud/awserrors/errors.go b/pkg/cloud/awserrors/errors.go index b7ff53b654..5312e4fe42 100644 --- a/pkg/cloud/awserrors/errors.go +++ b/pkg/cloud/awserrors/errors.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package awserrors provides a way to generate AWS errors. package awserrors import ( @@ -102,6 +103,7 @@ func NewConflict(msg string) error { } } +// IsBucketAlreadyOwnedByYou checks if the bucket is already owned. func IsBucketAlreadyOwnedByYou(err error) bool { if code, ok := Code(err); ok { return code == BucketAlreadyOwnedByYou diff --git a/pkg/cloud/converters/eks.go b/pkg/cloud/converters/eks.go index d9bc45d8a8..d9985f4693 100644 --- a/pkg/cloud/converters/eks.go +++ b/pkg/cloud/converters/eks.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package converters provides conversion functions for AWS SDK types to CAPA types. package converters import ( @@ -146,6 +147,7 @@ func TaintEffectFromSDK(effect string) (expinfrav1.TaintEffect, error) { } } +// ConvertSDKToIdentityProvider is used to convert an AWS SDK OIDCIdentityProviderConfig to a CAPA OidcIdentityProviderConfig. func ConvertSDKToIdentityProvider(in *ekscontrolplanev1.OIDCIdentityProviderConfig) *identityprovider.OidcIdentityProviderConfig { if in != nil { if in.RequiredClaims == nil { diff --git a/pkg/cloud/endpoints/endpoints.go b/pkg/cloud/endpoints/endpoints.go index e7092ec714..33a87b11cc 100644 --- a/pkg/cloud/endpoints/endpoints.go +++ b/pkg/cloud/endpoints/endpoints.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package endpoints contains aws endpoint related utilities. package endpoints import ( diff --git a/pkg/cloud/filter/types.go b/pkg/cloud/filter/types.go index 3193efc74b..3c704200d3 100644 --- a/pkg/cloud/filter/types.go +++ b/pkg/cloud/filter/types.go @@ -14,4 +14,5 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package filter contains the ec2 sdk related filters. package filter diff --git a/pkg/cloud/identity/identity.go b/pkg/cloud/identity/identity.go index c14a667e24..29a57a7337 100644 --- a/pkg/cloud/identity/identity.go +++ b/pkg/cloud/identity/identity.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package identity provides the AWSPrincipalTypeProvider interface and its implementations. package identity import ( @@ -79,7 +80,7 @@ func GetAssumeRoleCredentials(roleIdentityProvider *AWSRolePrincipalTypeProvider } // NewAWSRolePrincipalTypeProvider will create a new AWSRolePrincipalTypeProvider from an AWSClusterRoleIdentity. -func NewAWSRolePrincipalTypeProvider(identity *infrav1.AWSClusterRoleIdentity, sourceProvider *AWSPrincipalTypeProvider, log logger.Wrapper) *AWSRolePrincipalTypeProvider { +func NewAWSRolePrincipalTypeProvider(identity *infrav1.AWSClusterRoleIdentity, sourceProvider AWSPrincipalTypeProvider, log logger.Wrapper) *AWSRolePrincipalTypeProvider { return &AWSRolePrincipalTypeProvider{ credentials: nil, stsClient: nil, @@ -129,7 +130,7 @@ func (p *AWSStaticPrincipalTypeProvider) IsExpired() bool { type AWSRolePrincipalTypeProvider struct { Principal *infrav1.AWSClusterRoleIdentity credentials *credentials.Credentials - sourceProvider *AWSPrincipalTypeProvider + sourceProvider AWSPrincipalTypeProvider log logger.Wrapper stsClient stsiface.STSAPI } @@ -155,7 +156,7 @@ func (p *AWSRolePrincipalTypeProvider) Retrieve() (credentials.Value, error) { if p.credentials == nil || p.IsExpired() { awsConfig := aws.NewConfig() if p.sourceProvider != nil { - sourceCreds, err := (*p.sourceProvider).Retrieve() + sourceCreds, err := p.sourceProvider.Retrieve() if err != nil { return credentials.Value{}, err } diff --git a/pkg/cloud/identity/identity_test.go b/pkg/cloud/identity/identity_test.go index 29cd0ee826..8c204be9f4 100644 --- a/pkg/cloud/identity/identity_test.go +++ b/pkg/cloud/identity/identity_test.go @@ -45,7 +45,7 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { }, } - var staticProvider AWSPrincipalTypeProvider = NewAWSStaticPrincipalTypeProvider(&infrav1.AWSClusterStaticIdentity{}, secret) + staticProvider := NewAWSStaticPrincipalTypeProvider(&infrav1.AWSClusterStaticIdentity{}, secret) stsMock := mock_stsiface.NewMockSTSAPI(mockCtrl) roleIdentity := &infrav1.AWSClusterRoleIdentity{ @@ -58,10 +58,10 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { }, } - var roleProvider AWSPrincipalTypeProvider = &AWSRolePrincipalTypeProvider{ + roleProvider := &AWSRolePrincipalTypeProvider{ credentials: nil, Principal: roleIdentity, - sourceProvider: &staticProvider, + sourceProvider: staticProvider, stsClient: stsMock, } @@ -75,10 +75,10 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { }, } - var roleProvider2 AWSPrincipalTypeProvider = &AWSRolePrincipalTypeProvider{ + roleProvider2 := &AWSRolePrincipalTypeProvider{ credentials: nil, Principal: roleIdentity2, - sourceProvider: &roleProvider, + sourceProvider: roleProvider, stsClient: stsMock, } @@ -167,8 +167,8 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { name: "Role provider with role provider source fails to retrieve when the source's source cannot assume source", provider: roleProvider2, expect: func(m *mock_stsiface.MockSTSAPIMockRecorder) { - roleProvider.(*AWSRolePrincipalTypeProvider).credentials.Expire() - roleProvider2.(*AWSRolePrincipalTypeProvider).credentials.Expire() + roleProvider.credentials.Expire() + roleProvider2.credentials.Expire() // AssumeRoleWithContext() call is not needed for roleIdentity as it has unexpired credentials m.AssumeRoleWithContext(gomock.Any(), &sts.AssumeRoleInput{ RoleArn: aws.String(roleIdentity.Spec.RoleArn), diff --git a/pkg/cloud/interfaces.go b/pkg/cloud/interfaces.go index 751d9603ea..0ebc12e383 100644 --- a/pkg/cloud/interfaces.go +++ b/pkg/cloud/interfaces.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cloud contains interfaces for working with AWS resources. package cloud import ( diff --git a/pkg/cloud/logs/logs.go b/pkg/cloud/logs/logs.go index d20c657347..af22708f12 100644 --- a/pkg/cloud/logs/logs.go +++ b/pkg/cloud/logs/logs.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package logs provides a wrapper for the logr.Logger to be used as an AWS Logger. package logs import ( diff --git a/pkg/cloud/metrics/metrics.go b/pkg/cloud/metrics/metrics.go index b2c763ee78..4c3e5e988d 100644 --- a/pkg/cloud/metrics/metrics.go +++ b/pkg/cloud/metrics/metrics.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package metrics provides a way to capture request metrics. package metrics import ( diff --git a/pkg/cloud/scope/cluster.go b/pkg/cloud/scope/cluster.go index 399b07f6e0..9fb9a4ce62 100644 --- a/pkg/cloud/scope/cluster.go +++ b/pkg/cloud/scope/cluster.go @@ -184,6 +184,7 @@ func (s *ClusterScope) ControlPlaneLoadBalancer() *infrav1.AWSLoadBalancerSpec { return s.AWSCluster.Spec.ControlPlaneLoadBalancer } +// ControlPlaneLoadBalancers returns load balancers configured for the control plane. func (s *ClusterScope) ControlPlaneLoadBalancers() []*infrav1.AWSLoadBalancerSpec { return []*infrav1.AWSLoadBalancerSpec{ s.AWSCluster.Spec.ControlPlaneLoadBalancer, @@ -199,6 +200,7 @@ func (s *ClusterScope) ControlPlaneLoadBalancerScheme() infrav1.ELBScheme { return infrav1.ELBSchemeInternetFacing } +// ControlPlaneLoadBalancerName returns the name of the control plane load balancer. func (s *ClusterScope) ControlPlaneLoadBalancerName() *string { if s.AWSCluster.Spec.ControlPlaneLoadBalancer != nil { return s.AWSCluster.Spec.ControlPlaneLoadBalancer.Name @@ -206,10 +208,12 @@ func (s *ClusterScope) ControlPlaneLoadBalancerName() *string { return nil } +// ControlPlaneEndpoint returns the cluster control plane endpoint. func (s *ClusterScope) ControlPlaneEndpoint() clusterv1.APIEndpoint { return s.AWSCluster.Spec.ControlPlaneEndpoint } +// Bucket returns the cluster bucket configuration. func (s *ClusterScope) Bucket() *infrav1.S3Bucket { return s.AWSCluster.Spec.S3Bucket } diff --git a/pkg/cloud/scope/global.go b/pkg/cloud/scope/global.go index cd02a81eef..2ecc9dbf50 100644 --- a/pkg/cloud/scope/global.go +++ b/pkg/cloud/scope/global.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package scope provides a global scope for CAPA controllers. package scope import ( diff --git a/pkg/cloud/scope/launchtemplate.go b/pkg/cloud/scope/launchtemplate.go index 676e255365..fb2df8b59f 100644 --- a/pkg/cloud/scope/launchtemplate.go +++ b/pkg/cloud/scope/launchtemplate.go @@ -51,11 +51,13 @@ type LaunchTemplateScope interface { logger.Wrapper } +// ResourceServiceToUpdate is a struct that contains the resource ID and the resource service to update. type ResourceServiceToUpdate struct { ResourceID *string ResourceService ResourceService } +// ResourceService defines the interface for resources. type ResourceService interface { UpdateResourceTags(resourceID *string, create, remove map[string]string) error } diff --git a/pkg/cloud/scope/machine.go b/pkg/cloud/scope/machine.go index ddbabe6376..f547f284cb 100644 --- a/pkg/cloud/scope/machine.go +++ b/pkg/cloud/scope/machine.go @@ -194,6 +194,7 @@ func (m *MachineScope) UseSecretsManager(userDataFormat string) bool { return !m.AWSMachine.Spec.CloudInit.InsecureSkipSecretsManager && !m.UseIgnition(userDataFormat) } +// UseIgnition returns true if the AWSMachine should use Ignition. func (m *MachineScope) UseIgnition(userDataFormat string) bool { return userDataFormat == "ignition" || (m.AWSMachine.Spec.Ignition != nil) } @@ -264,6 +265,7 @@ func (m *MachineScope) GetRawBootstrapData() ([]byte, error) { return data, err } +// GetRawBootstrapDataWithFormat returns the bootstrap data from the secret in the Machine's bootstrap.dataSecretName. func (m *MachineScope) GetRawBootstrapDataWithFormat() ([]byte, string, error) { if m.Machine.Spec.Bootstrap.DataSecretName == nil { return nil, "", errors.New("error retrieving bootstrap data: linked Machine's bootstrap.dataSecretName is nil") diff --git a/pkg/cloud/scope/machinepool.go b/pkg/cloud/scope/machinepool.go index 069c76a41b..00e8abeadc 100644 --- a/pkg/cloud/scope/machinepool.go +++ b/pkg/cloud/scope/machinepool.go @@ -234,34 +234,40 @@ func (m *MachinePoolScope) SetASGStatus(v expinfrav1.ASGStatus) { m.AWSMachinePool.Status.ASGStatus = &v } +// GetObjectMeta returns the AWSMachinePool ObjectMeta. func (m *MachinePoolScope) GetObjectMeta() *metav1.ObjectMeta { return &m.AWSMachinePool.ObjectMeta } +// GetSetter returns the AWSMachinePool object setter. func (m *MachinePoolScope) GetSetter() conditions.Setter { return m.AWSMachinePool } +// GetEC2Scope returns the EC2 scope. func (m *MachinePoolScope) GetEC2Scope() EC2Scope { return m.InfraCluster } +// GetLaunchTemplateIDStatus returns the launch template ID status. func (m *MachinePoolScope) GetLaunchTemplateIDStatus() string { return m.AWSMachinePool.Status.LaunchTemplateID } +// SetLaunchTemplateIDStatus sets the launch template ID status. func (m *MachinePoolScope) SetLaunchTemplateIDStatus(id string) { m.AWSMachinePool.Status.LaunchTemplateID = id } +// GetLaunchTemplateLatestVersionStatus returns the launch template latest version status. func (m *MachinePoolScope) GetLaunchTemplateLatestVersionStatus() string { if m.AWSMachinePool.Status.LaunchTemplateVersion != nil { return *m.AWSMachinePool.Status.LaunchTemplateVersion - } else { - return "" } + return "" } +// SetLaunchTemplateLatestVersionStatus sets the launch template latest version status. func (m *MachinePoolScope) SetLaunchTemplateLatestVersionStatus(version string) { m.AWSMachinePool.Status.LaunchTemplateVersion = &version } @@ -370,18 +376,22 @@ func nodeIsReady(node corev1.Node) bool { return false } +// GetLaunchTemplate returns the launch template. func (m *MachinePoolScope) GetLaunchTemplate() *expinfrav1.AWSLaunchTemplate { return &m.AWSMachinePool.Spec.AWSLaunchTemplate } +// GetMachinePool returns the machine pool object. func (m *MachinePoolScope) GetMachinePool() *expclusterv1.MachinePool { return m.MachinePool } +// LaunchTemplateName returns the name of the launch template. func (m *MachinePoolScope) LaunchTemplateName() string { return m.Name() } +// GetRuntimeObject returns the AWSMachinePool object, in runtime.Object form. func (m *MachinePoolScope) GetRuntimeObject() runtime.Object { return m.AWSMachinePool } diff --git a/pkg/cloud/scope/managedcontrolplane.go b/pkg/cloud/scope/managedcontrolplane.go index 948f3fa511..bc93cd49ba 100644 --- a/pkg/cloud/scope/managedcontrolplane.go +++ b/pkg/cloud/scope/managedcontrolplane.go @@ -407,6 +407,7 @@ func (s *ManagedControlPlaneScope) VpcCni() ekscontrolplanev1.VpcCni { return s.ControlPlane.Spec.VpcCni } +// OIDCIdentityProviderConfig returns the OIDC identity provider config. func (s *ManagedControlPlaneScope) OIDCIdentityProviderConfig() *ekscontrolplanev1.OIDCIdentityProviderConfig { return s.ControlPlane.Spec.OIDCIdentityProviderConfig } diff --git a/pkg/cloud/scope/managednodegroup.go b/pkg/cloud/scope/managednodegroup.go index 1950ea0221..e9421d7282 100644 --- a/pkg/cloud/scope/managednodegroup.go +++ b/pkg/cloud/scope/managednodegroup.go @@ -315,14 +315,17 @@ func (s *ManagedMachinePoolScope) NodegroupName() string { return s.ManagedMachinePool.Spec.EKSNodegroupName } +// Name returns the name of the AWSManagedMachinePool. func (s *ManagedMachinePoolScope) Name() string { return s.ManagedMachinePool.Name } +// Namespace returns the namespace of the AWSManagedMachinePool. func (s *ManagedMachinePoolScope) Namespace() string { return s.ManagedMachinePool.Namespace } +// GetRawBootstrapData returns the raw bootstrap data from the linked Machine's bootstrap.dataSecretName. func (s *ManagedMachinePoolScope) GetRawBootstrapData() ([]byte, *types.NamespacedName, error) { if s.MachinePool.Spec.Template.Spec.Bootstrap.DataSecretName == nil { return nil, nil, errors.New("error retrieving bootstrap data: linked Machine's bootstrap.dataSecretName is nil") @@ -343,58 +346,68 @@ func (s *ManagedMachinePoolScope) GetRawBootstrapData() ([]byte, *types.Namespac return value, &key, nil } +// GetObjectMeta returns the ObjectMeta for the AWSManagedMachinePool. func (s *ManagedMachinePoolScope) GetObjectMeta() *metav1.ObjectMeta { return &s.ManagedMachinePool.ObjectMeta } +// GetSetter returns the condition setter. func (s *ManagedMachinePoolScope) GetSetter() conditions.Setter { return s.ManagedMachinePool } +// GetEC2Scope returns the EC2Scope. func (s *ManagedMachinePoolScope) GetEC2Scope() EC2Scope { return s.EC2Scope } +// IsEKSManaged returns true if the control plane is managed by EKS. func (s *ManagedMachinePoolScope) IsEKSManaged() bool { return true } +// GetLaunchTemplateIDStatus returns the launch template ID status. func (s *ManagedMachinePoolScope) GetLaunchTemplateIDStatus() string { if s.ManagedMachinePool.Status.LaunchTemplateID != nil { return *s.ManagedMachinePool.Status.LaunchTemplateID - } else { - return "" } + return "" } +// SetLaunchTemplateIDStatus sets the launch template ID status. func (s *ManagedMachinePoolScope) SetLaunchTemplateIDStatus(id string) { s.ManagedMachinePool.Status.LaunchTemplateID = &id } +// GetLaunchTemplateLatestVersionStatus returns the launch template latest version status. func (s *ManagedMachinePoolScope) GetLaunchTemplateLatestVersionStatus() string { if s.ManagedMachinePool.Status.LaunchTemplateVersion != nil { return *s.ManagedMachinePool.Status.LaunchTemplateVersion - } else { - return "" } + return "" } +// SetLaunchTemplateLatestVersionStatus sets the launch template latest version status. func (s *ManagedMachinePoolScope) SetLaunchTemplateLatestVersionStatus(version string) { s.ManagedMachinePool.Status.LaunchTemplateVersion = &version } +// GetLaunchTemplate returns the launch template. func (s *ManagedMachinePoolScope) GetLaunchTemplate() *expinfrav1.AWSLaunchTemplate { return s.ManagedMachinePool.Spec.AWSLaunchTemplate } +// GetMachinePool returns the machine pool. func (s *ManagedMachinePoolScope) GetMachinePool() *expclusterv1.MachinePool { return s.MachinePool } +// LaunchTemplateName returns the launch template name. func (s *ManagedMachinePoolScope) LaunchTemplateName() string { return fmt.Sprintf("%s-%s", s.ControlPlane.Name, s.ManagedMachinePool.Name) } +// GetRuntimeObject returns the AWSManagedMachinePool, in runtime.Object form. func (s *ManagedMachinePoolScope) GetRuntimeObject() runtime.Object { return s.ManagedMachinePool } diff --git a/pkg/cloud/scope/rosacontrolplane.go b/pkg/cloud/scope/rosacontrolplane.go index 81b0d1843c..c533304c1e 100644 --- a/pkg/cloud/scope/rosacontrolplane.go +++ b/pkg/cloud/scope/rosacontrolplane.go @@ -37,6 +37,7 @@ import ( "sigs.k8s.io/cluster-api/util/patch" ) +// ROSAControlPlaneScopeParams defines the input parameters used to create a new ROSAControlPlaneScope. type ROSAControlPlaneScopeParams struct { Client client.Client Logger *logger.Logger @@ -46,6 +47,7 @@ type ROSAControlPlaneScopeParams struct { Endpoints []ServiceEndpoint } +// NewROSAControlPlaneScope creates a new ROSAControlPlaneScope from the supplied parameters. func NewROSAControlPlaneScope(params ROSAControlPlaneScopeParams) (*ROSAControlPlaneScope, error) { if params.Cluster == nil { return nil, errors.New("failed to generate new scope from nil Cluster") @@ -106,18 +108,22 @@ type ROSAControlPlaneScope struct { Identity *sts.GetCallerIdentityOutput } +// InfraCluster returns the AWSManagedControlPlane object. func (s *ROSAControlPlaneScope) InfraCluster() cloud.ClusterObject { return s.ControlPlane } +// IdentityRef returns the AWSIdentityReference object. func (s *ROSAControlPlaneScope) IdentityRef() *infrav1.AWSIdentityReference { return s.ControlPlane.Spec.IdentityRef } +// Session returns the AWS SDK session. Used for creating clients. func (s *ROSAControlPlaneScope) Session() awsclient.ConfigProvider { return s.session } +// ServiceLimiter returns the AWS SDK session. Used for creating clients. func (s *ROSAControlPlaneScope) ServiceLimiter(service string) *throttle.ServiceLimiter { if sl, ok := s.serviceLimiters[service]; ok { return sl @@ -125,6 +131,7 @@ func (s *ROSAControlPlaneScope) ServiceLimiter(service string) *throttle.Service return nil } +// ControllerName returns the name of the controller. func (s *ROSAControlPlaneScope) ControllerName() string { return s.controllerName } @@ -143,6 +150,7 @@ func (s *ROSAControlPlaneScope) InfraClusterName() string { return s.ControlPlane.Name } +// RosaClusterName returns the ROSA cluster name. func (s *ROSAControlPlaneScope) RosaClusterName() string { return s.ControlPlane.Spec.RosaClusterName } @@ -167,6 +175,7 @@ func (s *ROSAControlPlaneScope) CredentialsSecret() *corev1.Secret { } } +// ClusterAdminPasswordSecret returns the corev1.Secret object for the cluster admin password. func (s *ROSAControlPlaneScope) ClusterAdminPasswordSecret() *corev1.Secret { return &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ diff --git a/pkg/cloud/scope/rosamachinepool.go b/pkg/cloud/scope/rosamachinepool.go index b420838c54..00d480ca3e 100644 --- a/pkg/cloud/scope/rosamachinepool.go +++ b/pkg/cloud/scope/rosamachinepool.go @@ -156,6 +156,7 @@ func (s *RosaMachinePoolScope) ControllerName() string { return s.controllerName } +// GetSetter returns the condition setter for the RosaMachinePool. func (s *RosaMachinePoolScope) GetSetter() conditions.Setter { return s.RosaMachinePool } diff --git a/pkg/cloud/scope/session.go b/pkg/cloud/scope/session.go index cda46352f5..95f5e68662 100644 --- a/pkg/cloud/scope/session.go +++ b/pkg/cloud/scope/session.go @@ -313,11 +313,7 @@ func buildProvidersForRef( } } - if sourceProvider != nil { - provider = identity.NewAWSRolePrincipalTypeProvider(roleIdentity, &sourceProvider, log) - } else { - provider = identity.NewAWSRolePrincipalTypeProvider(roleIdentity, nil, log) - } + provider = identity.NewAWSRolePrincipalTypeProvider(roleIdentity, sourceProvider, log) providers = append(providers, provider) default: return providers, errors.Errorf("No such provider known: '%s'", ref.Kind) diff --git a/pkg/cloud/services/autoscaling/autoscalinggroup.go b/pkg/cloud/services/autoscaling/autoscalinggroup.go index 6e24cf22f9..9ddd4c086d 100644 --- a/pkg/cloud/services/autoscaling/autoscalinggroup.go +++ b/pkg/cloud/services/autoscaling/autoscalinggroup.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package asg provides a service for managing AWS AutoScalingGroups. package asg import ( @@ -471,6 +472,7 @@ func (s *Service) UpdateResourceTags(resourceID *string, create, remove map[stri return nil } +// SuspendProcesses suspends the processes for an autoscaling group. func (s *Service) SuspendProcesses(name string, processes []string) error { input := autoscaling.ScalingProcessQuery{ AutoScalingGroupName: aws.String(name), @@ -482,6 +484,7 @@ func (s *Service) SuspendProcesses(name string, processes []string) error { return nil } +// ResumeProcesses resumes the processes for an autoscaling group. func (s *Service) ResumeProcesses(name string, processes []string) error { input := autoscaling.ScalingProcessQuery{ AutoScalingGroupName: aws.String(name), diff --git a/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go b/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go index 522e4d3ab5..f664299d6d 100644 --- a/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go +++ b/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_autoscalingiface provides a mock implementation for the AutoScalingAPI interface. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination autoscalingapi_mock.go -package mock_autoscalingiface github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface AutoScalingAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt autoscalingapi_mock.go > _autoscalingapi_mock.go && mv _autoscalingapi_mock.go autoscalingapi_mock.go" - package mock_autoscalingiface //nolint:stylecheck diff --git a/pkg/cloud/services/awsnode/cni_test.go b/pkg/cloud/services/awsnode/cni_test.go index 1619d843ac..67c78d806b 100644 --- a/pkg/cloud/services/awsnode/cni_test.go +++ b/pkg/cloud/services/awsnode/cni_test.go @@ -263,7 +263,7 @@ type cachingClient struct { updateChain []client.Object } -func (c *cachingClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { +func (c *cachingClient) Get(_ context.Context, _ client.ObjectKey, obj client.Object, _ ...client.GetOption) error { if _, ok := obj.(*v1.DaemonSet); ok { daemonset, _ := obj.(*v1.DaemonSet) *daemonset = *c.getValue.(*v1.DaemonSet) @@ -271,12 +271,12 @@ func (c *cachingClient) Get(ctx context.Context, key client.ObjectKey, obj clien return nil } -func (c *cachingClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error { +func (c *cachingClient) Update(_ context.Context, obj client.Object, _ ...client.UpdateOption) error { c.updateChain = append(c.updateChain, obj) return nil } -func (c *cachingClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { +func (c *cachingClient) List(_ context.Context, _ client.ObjectList, _ ...client.ListOption) error { return nil } @@ -297,7 +297,7 @@ func (s *mockScope) VpcCni() ekscontrolplanev1.VpcCni { return s.cni } -func (s *mockScope) Info(msg string, keysAndValues ...interface{}) { +func (s *mockScope) Info(_ string, _ ...interface{}) { } diff --git a/pkg/cloud/services/awsnode/service.go b/pkg/cloud/services/awsnode/service.go index 892a703429..ddc8d52251 100644 --- a/pkg/cloud/services/awsnode/service.go +++ b/pkg/cloud/services/awsnode/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package awsnode provides a way to interact with AWS nodes. package awsnode import ( diff --git a/pkg/cloud/services/ec2/instances.go b/pkg/cloud/services/ec2/instances.go index 36e6661f29..dde96bd8a1 100644 --- a/pkg/cloud/services/ec2/instances.go +++ b/pkg/cloud/services/ec2/instances.go @@ -98,11 +98,11 @@ func (s *Service) InstanceIfExists(id *string) (*infrav1.Instance, error) { if len(out.Reservations) > 0 && len(out.Reservations[0].Instances) > 0 { return s.SDKToInstance(out.Reservations[0].Instances[0]) - } else { - // Failed to find instance with provider id. - record.Eventf(s.scope.InfraCluster(), "FailedFindInstances", "failed to find instance by providerId %q: %v", *id, err) - return nil, ErrInstanceNotFoundByID } + + // Failed to find instance with provider id. + record.Eventf(s.scope.InfraCluster(), "FailedFindInstances", "failed to find instance by providerId %q: %v", *id, err) + return nil, ErrInstanceNotFoundByID } // CreateInstance runs an ec2 instance. diff --git a/pkg/cloud/services/ec2/launchtemplate.go b/pkg/cloud/services/ec2/launchtemplate.go index 356433ed91..bb04605475 100644 --- a/pkg/cloud/services/ec2/launchtemplate.go +++ b/pkg/cloud/services/ec2/launchtemplate.go @@ -187,6 +187,7 @@ func (s *Service) ReconcileLaunchTemplate( return nil } +// ReconcileTags reconciles the tags for the AWSMachinePool instances. func (s *Service) ReconcileTags(scope scope.LaunchTemplateScope, resourceServicesToUpdate []scope.ResourceServiceToUpdate) error { additionalTags := scope.AdditionalTags() @@ -226,6 +227,7 @@ func (s *Service) ensureTags(scope scope.LaunchTemplateScope, resourceServicesTo return changed, nil } +// MachinePoolAnnotationJSON returns the annotation's json value as a map. func MachinePoolAnnotationJSON(lts scope.LaunchTemplateScope, annotation string) (map[string]interface{}, error) { out := map[string]interface{}{} @@ -246,6 +248,7 @@ func machinePoolAnnotation(lts scope.LaunchTemplateScope, annotation string) str return lts.GetObjectMeta().GetAnnotations()[annotation] } +// UpdateMachinePoolAnnotationJSON updates the annotation with the given content. func UpdateMachinePoolAnnotationJSON(lts scope.LaunchTemplateScope, annotation string, content map[string]interface{}) error { b, err := json.Marshal(content) if err != nil { @@ -618,6 +621,7 @@ func (s *Service) PruneLaunchTemplateVersions(id string) error { return s.deleteLaunchTemplateVersion(id, versionToPrune) } +// GetLaunchTemplateLatestVersion returns the latest version of a launch template. func (s *Service) GetLaunchTemplateLatestVersion(id string) (string, error) { input := &ec2.DescribeLaunchTemplateVersionsInput{ LaunchTemplateId: aws.String(id), @@ -854,6 +858,7 @@ func (s *Service) DiscoverLaunchTemplateAMI(scope scope.LaunchTemplateScope) (*s return aws.String(lookupAMI), nil } +// GetAdditionalSecurityGroupsIDs returns the security group IDs for the additional security groups. func (s *Service) GetAdditionalSecurityGroupsIDs(securityGroups []infrav1.AWSResourceReference) ([]string, error) { var additionalSecurityGroupsIDs []string diff --git a/pkg/cloud/services/ec2/service.go b/pkg/cloud/services/ec2/service.go index f303f1a095..b085ee86c8 100644 --- a/pkg/cloud/services/ec2/service.go +++ b/pkg/cloud/services/ec2/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package ec2 provides a way to interact with the AWS EC2 API. package ec2 import ( diff --git a/pkg/cloud/services/eks/cluster.go b/pkg/cloud/services/eks/cluster.go index c7d786a690..6fe0fd5a34 100644 --- a/pkg/cloud/services/eks/cluster.go +++ b/pkg/cloud/services/eks/cluster.go @@ -275,11 +275,11 @@ func makeVpcConfig(subnets infrav1.Subnets, endpointAccess ekscontrolplanev1.End return nil, awserrors.NewFailedDependency("subnets in at least 2 different az's are required") } - subnetIds := make([]*string, 0) + subnetIDs := make([]*string, 0) for i := range subnets { subnet := subnets[i] subnetID := subnet.GetResourceID() - subnetIds = append(subnetIds, &subnetID) + subnetIDs = append(subnetIDs, &subnetID) } cidrs := make([]*string, 0) @@ -295,7 +295,7 @@ func makeVpcConfig(subnets infrav1.Subnets, endpointAccess ekscontrolplanev1.End vpcConfig := &eks.VpcConfigRequest{ EndpointPublicAccess: endpointAccess.Public, EndpointPrivateAccess: endpointAccess.Private, - SubnetIds: subnetIds, + SubnetIds: subnetIDs, } if len(cidrs) > 0 { diff --git a/pkg/cloud/services/eks/cluster_test.go b/pkg/cloud/services/eks/cluster_test.go index eeb92bbac0..0441a80ab9 100644 --- a/pkg/cloud/services/eks/cluster_test.go +++ b/pkg/cloud/services/eks/cluster_test.go @@ -524,10 +524,10 @@ func TestCreateCluster(t *testing.T) { }, }, }) - subnetIds := make([]*string, 0) + subnetIDs := make([]*string, 0) for i := range tc.subnets { subnet := tc.subnets[i] - subnetIds = append(subnetIds, &subnet.ID) + subnetIDs = append(subnetIDs, &subnet.ID) } if !tc.expectError { @@ -537,7 +537,7 @@ func TestCreateCluster(t *testing.T) { Name: aws.String(clusterName), EncryptionConfig: []*eks.EncryptionConfig{}, ResourcesVpcConfig: &eks.VpcConfigRequest{ - SubnetIds: subnetIds, + SubnetIds: subnetIDs, }, RoleArn: tc.role, Tags: tc.tags, diff --git a/pkg/cloud/services/eks/eks.go b/pkg/cloud/services/eks/eks.go index 7b0c81a374..958230bccd 100644 --- a/pkg/cloud/services/eks/eks.go +++ b/pkg/cloud/services/eks/eks.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package eks provides a service to reconcile EKS control plane and nodegroups. package eks import ( diff --git a/pkg/cloud/services/eks/iam/iam.go b/pkg/cloud/services/eks/iam/iam.go index e8b13e4747..bb4db97670 100644 --- a/pkg/cloud/services/eks/iam/iam.go +++ b/pkg/cloud/services/eks/iam/iam.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package iam provides a service for managing IAM roles and policies. package iam import ( @@ -483,7 +484,7 @@ func (s *IAMService) FindAndVerifyOIDCProvider(cluster *eks.Cluster) (string, er func fetchRootCAThumbprint(issuerURL string, client *http.Client) (string, error) { // needed to appease noctx. - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, issuerURL, nil) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, issuerURL, http.NoBody) if err != nil { return "", err } diff --git a/pkg/cloud/services/eks/nodegroup.go b/pkg/cloud/services/eks/nodegroup.go index ec24f16fc3..4a9563b553 100644 --- a/pkg/cloud/services/eks/nodegroup.go +++ b/pkg/cloud/services/eks/nodegroup.go @@ -257,7 +257,7 @@ func (s *NodegroupService) createNodegroup() (*eks.Nodegroup, error) { if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { - // TODO + // TODO: handle other errors case eks.ErrCodeResourceNotFoundException: return nil, nil default: @@ -301,7 +301,7 @@ func (s *NodegroupService) deleteNodegroupAndWait() (reterr error) { if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { - // TODO + // TODO handle other errors case eks.ErrCodeResourceNotFoundException: return nil default: diff --git a/pkg/cloud/services/eks/service.go b/pkg/cloud/services/eks/service.go index 22684defdf..9160a398a1 100644 --- a/pkg/cloud/services/eks/service.go +++ b/pkg/cloud/services/eks/service.go @@ -52,6 +52,7 @@ type Service struct { STSClient stsiface.STSAPI } +// ServiceOpts defines the functional arguments for the service. type ServiceOpts func(s *Service) // WithIAMClient creates an access spec with a custom http client. diff --git a/pkg/cloud/services/elb/loadbalancer.go b/pkg/cloud/services/elb/loadbalancer.go index 0d03adbfcc..9dfd312ef9 100644 --- a/pkg/cloud/services/elb/loadbalancer.go +++ b/pkg/cloud/services/elb/loadbalancer.go @@ -812,7 +812,7 @@ func (s *Service) RegisterInstanceWithAPIServerLB(instance *infrav1.Instance, lb return errors.Wrapf(err, "error describing ELB's target groups %q", name) } if len(targetGroups.TargetGroups) == 0 { - return errors.New(fmt.Sprintf("no target groups found for load balancer with arn '%s'", out.ARN)) + return fmt.Errorf("no target groups found for load balancer with arn '%s'", out.ARN) } // Since TargetGroups and Listeners don't care, or are not aware, of subnets before registration, we ignore that check. // Also, registering with AZ is not supported using the an InstanceID. @@ -1248,27 +1248,28 @@ func (s *Service) listByTag(tag string) ([]string, error) { err := s.ResourceTaggingClient.GetResourcesPages(&input, func(r *rgapi.GetResourcesOutput, last bool) bool { for _, tagmapping := range r.ResourceTagMappingList { - if tagmapping.ResourceARN != nil { - parsedARN, err := arn.Parse(*tagmapping.ResourceARN) - if err != nil { - s.scope.Info("failed to parse ARN", "arn", *tagmapping.ResourceARN, "tag", tag) - continue - } - if strings.Contains(parsedARN.Resource, "loadbalancer/net/") { - s.scope.Info("ignoring nlb created by service, consider enabling garbage collection", "arn", *tagmapping.ResourceARN, "tag", tag) - continue - } - if strings.Contains(parsedARN.Resource, "loadbalancer/app/") { - s.scope.Info("ignoring alb created by service, consider enabling garbage collection", "arn", *tagmapping.ResourceARN, "tag", tag) - continue - } - name := strings.ReplaceAll(parsedARN.Resource, "loadbalancer/", "") - if name == "" { - s.scope.Info("failed to parse ARN", "arn", *tagmapping.ResourceARN, "tag", tag) - continue - } - names = append(names, name) + if tagmapping.ResourceARN == nil { + continue + } + parsedARN, err := arn.Parse(*tagmapping.ResourceARN) + if err != nil { + s.scope.Info("failed to parse ARN", "arn", *tagmapping.ResourceARN, "tag", tag) + continue + } + if strings.Contains(parsedARN.Resource, "loadbalancer/net/") { + s.scope.Info("ignoring nlb created by service, consider enabling garbage collection", "arn", *tagmapping.ResourceARN, "tag", tag) + continue + } + if strings.Contains(parsedARN.Resource, "loadbalancer/app/") { + s.scope.Info("ignoring alb created by service, consider enabling garbage collection", "arn", *tagmapping.ResourceARN, "tag", tag) + continue + } + name := strings.ReplaceAll(parsedARN.Resource, "loadbalancer/", "") + if name == "" { + s.scope.Info("failed to parse ARN", "arn", *tagmapping.ResourceARN, "tag", tag) + continue } + names = append(names, name) } return true }) @@ -1527,17 +1528,17 @@ func fromSDKTypeToClassicELB(v *elb.LoadBalancerDescription, attrs *elb.LoadBala } func fromSDKTypeToLB(v *elbv2.LoadBalancer, attrs []*elbv2.LoadBalancerAttribute, tags []*elbv2.Tag) *infrav1.LoadBalancer { - subnetIds := make([]*string, len(v.AvailabilityZones)) + subnetIDs := make([]*string, len(v.AvailabilityZones)) availabilityZones := make([]*string, len(v.AvailabilityZones)) for i, az := range v.AvailabilityZones { - subnetIds[i] = az.SubnetId + subnetIDs[i] = az.SubnetId availabilityZones[i] = az.ZoneName } res := &infrav1.LoadBalancer{ ARN: aws.StringValue(v.LoadBalancerArn), Name: aws.StringValue(v.LoadBalancerName), Scheme: infrav1.ELBScheme(aws.StringValue(v.Scheme)), - SubnetIDs: aws.StringValueSlice(subnetIds), + SubnetIDs: aws.StringValueSlice(subnetIDs), SecurityGroupIDs: aws.StringValueSlice(v.SecurityGroups), AvailabilityZones: aws.StringValueSlice(availabilityZones), DNSName: aws.StringValue(v.DNSName), diff --git a/pkg/cloud/services/elb/loadbalancer_test.go b/pkg/cloud/services/elb/loadbalancer_test.go index 4762edc251..593cbc3625 100644 --- a/pkg/cloud/services/elb/loadbalancer_test.go +++ b/pkg/cloud/services/elb/loadbalancer_test.go @@ -2180,7 +2180,7 @@ func TestReconcileLoadbalancers(t *testing.T) { } func TestDeleteAPIServerELB(t *testing.T) { - clusterName := "bar" //nolint:goconst // does not need to be a package-level const + clusterName := "bar" elbName := "bar-apiserver" tests := []struct { name string diff --git a/pkg/cloud/services/elb/service.go b/pkg/cloud/services/elb/service.go index b1b78ca358..c0717c6f25 100644 --- a/pkg/cloud/services/elb/service.go +++ b/pkg/cloud/services/elb/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package elb provides a service for managing AWS load balancers. package elb import ( diff --git a/pkg/cloud/services/gc/ec2.go b/pkg/cloud/services/gc/ec2.go index 817dbd78a1..823163dddc 100644 --- a/pkg/cloud/services/gc/ec2.go +++ b/pkg/cloud/services/gc/ec2.go @@ -72,7 +72,7 @@ func (s *Service) deleteSecurityGroup(ctx context.Context, securityGroupID strin } // getProviderOwnedSecurityGroups gets cloud provider created security groups of ELBs for this cluster, filtering by tag: kubernetes.io/cluster/:owned and VPC Id. -func (s *Service) getProviderOwnedSecurityGroups(ctx context.Context) ([]*AWSResource, error) { +func (s *Service) getProviderOwnedSecurityGroups(_ context.Context) ([]*AWSResource, error) { input := &ec2.DescribeSecurityGroupsInput{ Filters: []*ec2.Filter{ filter.EC2.ProviderOwned(s.scope.KubernetesClusterName()), diff --git a/pkg/cloud/services/gc/options.go b/pkg/cloud/services/gc/options.go index c2ebb49af7..445977bcd3 100644 --- a/pkg/cloud/services/gc/options.go +++ b/pkg/cloud/services/gc/options.go @@ -54,6 +54,7 @@ func withEC2Client(client ec2iface.EC2API) ServiceOption { } } +// WithGCStrategy is an option for specifying using the alternative GC strategy. func WithGCStrategy(alternativeGCStrategy bool) ServiceOption { if alternativeGCStrategy { return func(s *Service) { diff --git a/pkg/cloud/services/gc/service.go b/pkg/cloud/services/gc/service.go index 9eb9f789a6..27b48d653e 100644 --- a/pkg/cloud/services/gc/service.go +++ b/pkg/cloud/services/gc/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package gc provides a way to perform gc operations against a tenant/workload/child cluster. package gc import ( diff --git a/pkg/cloud/services/iamauth/mock_iamauth/doc.go b/pkg/cloud/services/iamauth/mock_iamauth/doc.go index 15669ccb8f..d33311cf0a 100644 --- a/pkg/cloud/services/iamauth/mock_iamauth/doc.go +++ b/pkg/cloud/services/iamauth/mock_iamauth/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_iamauth provides a mock implementation for the IAMAPI interface. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination iamauth_mock.go -package mock_iamauth github.com/aws/aws-sdk-go/service/iam/iamiface IAMAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt iamauth_mock.go > _iamauth_mock.go && mv _iamauth_mock.go iamauth_mock.go" - package mock_iamauth //nolint:stylecheck diff --git a/pkg/cloud/services/iamauth/service.go b/pkg/cloud/services/iamauth/service.go index 477e7c4928..27241b0c69 100644 --- a/pkg/cloud/services/iamauth/service.go +++ b/pkg/cloud/services/iamauth/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package iamauth provides a way to interact with AWS IAM. package iamauth import ( diff --git a/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go b/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go index 877fd9feb0..9d3af84e3b 100644 --- a/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go +++ b/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go @@ -18,4 +18,5 @@ limitations under the License. //go:generate ../../../../../hack/tools/bin/mockgen -destination eventbridgeiface_mock.go -package mock_eventbridgeiface github.com/aws/aws-sdk-go/service/eventbridge/eventbridgeiface EventBridgeAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt eventbridgeiface_mock.go > _eventbridgeiface_mock.go && mv _eventbridgeiface_mock.go eventbridgeiface_mock.go" +// Package mock_eventbridgeiface provides a mock implementation for the EventBridgeAPI interface. package mock_eventbridgeiface //nolint:stylecheck diff --git a/pkg/cloud/services/instancestate/mock_sqsiface/doc.go b/pkg/cloud/services/instancestate/mock_sqsiface/doc.go index 356d813633..57fb6a9347 100644 --- a/pkg/cloud/services/instancestate/mock_sqsiface/doc.go +++ b/pkg/cloud/services/instancestate/mock_sqsiface/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_sqsiface provides a mock implementation for the SQSAPI interface. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination sqsiface_mock.go -package mock_sqsiface github.com/aws/aws-sdk-go/service/sqs/sqsiface SQSAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt sqsiface_mock.go > _sqsiface_mock.go && mv _sqsiface_mock.go sqsiface_mock.go" - package mock_sqsiface //nolint:stylecheck diff --git a/pkg/cloud/services/instancestate/service.go b/pkg/cloud/services/instancestate/service.go index 62ea5be2f1..b798967ffc 100644 --- a/pkg/cloud/services/instancestate/service.go +++ b/pkg/cloud/services/instancestate/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package instancestate provides a way to interact with the EC2 instance state. package instancestate import ( diff --git a/pkg/cloud/services/interfaces.go b/pkg/cloud/services/interfaces.go index 893c5ae278..ebee62a9a8 100644 --- a/pkg/cloud/services/interfaces.go +++ b/pkg/cloud/services/interfaces.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package services contains the interfaces for the AWS services. package services import ( diff --git a/pkg/cloud/services/kubeproxy/service.go b/pkg/cloud/services/kubeproxy/service.go index 16fbf38eed..17a4bd73af 100644 --- a/pkg/cloud/services/kubeproxy/service.go +++ b/pkg/cloud/services/kubeproxy/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package kubeproxy provides a way to interact with the kube-proxy service. package kubeproxy import ( diff --git a/pkg/cloud/services/mock_services/doc.go b/pkg/cloud/services/mock_services/doc.go index 04493e0002..9c5380ce19 100644 --- a/pkg/cloud/services/mock_services/doc.go +++ b/pkg/cloud/services/mock_services/doc.go @@ -14,7 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_services provides a way to generate mock services for the cloud provider. // Run go generate to regenerate this mock. //nolint:revive +// //go:generate ../../../../hack/tools/bin/mockgen -destination ec2_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/services EC2Interface //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt ec2_interface_mock.go > _ec2_interface_mock.go && mv _ec2_interface_mock.go ec2_interface_mock.go" //go:generate ../../../../hack/tools/bin/mockgen -destination reconcile_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/services MachinePoolReconcileInterface @@ -31,5 +33,4 @@ limitations under the License. //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt network_interface_mock.go > _network_interface_mock.go && mv _network_interface_mock.go network_interface_mock.go" //go:generate ../../../../hack/tools/bin/mockgen -destination security_group_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/services SecurityGroupInterface //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt security_group_interface_mock.go > _security_group_interface_mock.go && mv _security_group_interface_mock.go security_group_interface_mock.go" - package mock_services //nolint:stylecheck diff --git a/pkg/cloud/services/network/natgateways.go b/pkg/cloud/services/network/natgateways.go index 8038b42290..807594f604 100644 --- a/pkg/cloud/services/network/natgateways.go +++ b/pkg/cloud/services/network/natgateways.go @@ -298,7 +298,7 @@ func (s *Service) deleteNatGateway(id string) error { } if out == nil || len(out.NatGateways) == 0 { - return false, errors.New(fmt.Sprintf("no NAT gateway returned for id %q", id)) + return false, fmt.Errorf("no NAT gateway returned for id %q", id) } ng := out.NatGateways[0] diff --git a/pkg/cloud/services/network/service.go b/pkg/cloud/services/network/service.go index 32f6d8131a..8c223c5e6d 100644 --- a/pkg/cloud/services/network/service.go +++ b/pkg/cloud/services/network/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package network provides a service to manage AWS network resources. package network import ( diff --git a/pkg/cloud/services/network/subnets.go b/pkg/cloud/services/network/subnets.go index c4b7a0c44f..65a70e7445 100644 --- a/pkg/cloud/services/network/subnets.go +++ b/pkg/cloud/services/network/subnets.go @@ -146,12 +146,12 @@ func (s *Service) reconcileSubnets() error { if !unmanagedVPC { record.Warnf(s.scope.InfraCluster(), "FailedTagSubnet", "Failed tagging managed Subnet %q: %v", existingSubnet.GetResourceID(), err) return errors.Wrapf(err, "failed to ensure tags on subnet %q", existingSubnet.GetResourceID()) - } else { - // We may not have a permission to tag unmanaged subnets. - // When tagging unmanaged subnet fails, record an event and proceed. - record.Warnf(s.scope.InfraCluster(), "FailedTagSubnet", "Failed tagging unmanaged Subnet %q: %v", existingSubnet.GetResourceID(), err) - break } + + // We may not have a permission to tag unmanaged subnets. + // When tagging unmanaged subnet fails, record an event and proceed. + record.Warnf(s.scope.InfraCluster(), "FailedTagSubnet", "Failed tagging unmanaged Subnet %q: %v", existingSubnet.GetResourceID(), err) + break } // TODO(vincepri): check if subnet needs to be updated. @@ -590,10 +590,10 @@ func (s *Service) getSubnetTagParams(unmanagedVPC bool, id string, public bool, Role: aws.String(role), Additional: additionalTags, } - } else { - return infrav1.BuildParams{ - ResourceID: id, - Additional: additionalTags, - } + } + + return infrav1.BuildParams{ + ResourceID: id, + Additional: additionalTags, } } diff --git a/pkg/cloud/services/network/subnets_test.go b/pkg/cloud/services/network/subnets_test.go index f7c02d4359..840583a37c 100644 --- a/pkg/cloud/services/network/subnets_test.go +++ b/pkg/cloud/services/network/subnets_test.go @@ -2677,7 +2677,7 @@ func TestDeleteSubnets(t *testing.T) { } } -// Test helpers +// Test helpers. type ScopeBuilder interface { Build() (scope.NetworkScope, error) diff --git a/pkg/cloud/services/network/vpc_test.go b/pkg/cloud/services/network/vpc_test.go index a48bec80ca..403707b8ec 100644 --- a/pkg/cloud/services/network/vpc_test.go +++ b/pkg/cloud/services/network/vpc_test.go @@ -38,7 +38,7 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) -func describeVpcAttributeTrue(ctx context.Context, input *ec2.DescribeVpcAttributeInput, requestOptions ...request.Option) (*ec2.DescribeVpcAttributeOutput, error) { +func describeVpcAttributeTrue(_ context.Context, input *ec2.DescribeVpcAttributeInput, _ ...request.Option) (*ec2.DescribeVpcAttributeOutput, error) { result := &ec2.DescribeVpcAttributeOutput{ VpcId: input.VpcId, } @@ -51,7 +51,7 @@ func describeVpcAttributeTrue(ctx context.Context, input *ec2.DescribeVpcAttribu return result, nil } -func describeVpcAttributeFalse(ctx context.Context, input *ec2.DescribeVpcAttributeInput, requestOptions ...request.Option) (*ec2.DescribeVpcAttributeOutput, error) { +func describeVpcAttributeFalse(_ context.Context, input *ec2.DescribeVpcAttributeInput, _ ...request.Option) (*ec2.DescribeVpcAttributeOutput, error) { result := &ec2.DescribeVpcAttributeOutput{ VpcId: input.VpcId, } @@ -573,9 +573,8 @@ func TestReconcileVPC(t *testing.T) { g.Expect(err).ToNot(BeNil()) g.Expect(err.Error()).To(ContainSubstring(*tc.wantErrContaining)) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) g.Expect(tc.want).To(Equal(&clusterScope.AWSCluster.Spec.NetworkSpec.VPC)) }) } diff --git a/pkg/cloud/services/s3/mock_s3iface/doc.go b/pkg/cloud/services/s3/mock_s3iface/doc.go index d507db6d37..4b8b857f37 100644 --- a/pkg/cloud/services/s3/mock_s3iface/doc.go +++ b/pkg/cloud/services/s3/mock_s3iface/doc.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_s3iface provides a mock implementation of the s3iface.S3API interface // Run go generate to regenerate this mock. // //go:generate ../../../../../hack/tools/bin/mockgen -destination s3api_mock.go -package mock_s3iface github.com/aws/aws-sdk-go/service/s3/s3iface S3API diff --git a/pkg/cloud/services/s3/mock_stsiface/doc.go b/pkg/cloud/services/s3/mock_stsiface/doc.go index 82065f4ad7..429a95b586 100644 --- a/pkg/cloud/services/s3/mock_stsiface/doc.go +++ b/pkg/cloud/services/s3/mock_stsiface/doc.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_stsiface provides a mock implementation for the STSAPI interface. // Run go generate to regenerate this mock. // //go:generate ../../../../../hack/tools/bin/mockgen -destination stsapi_mock.go -package mock_stsiface github.com/aws/aws-sdk-go/service/sts/stsiface STSAPI diff --git a/pkg/cloud/services/s3/s3.go b/pkg/cloud/services/s3/s3.go index b7e9a658ac..b6695fd006 100644 --- a/pkg/cloud/services/s3/s3.go +++ b/pkg/cloud/services/s3/s3.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package s3 provides a way to interact with AWS S3. package s3 import ( @@ -62,6 +63,7 @@ func NewService(s3Scope scope.S3Scope) *Service { } } +// ReconcileBucket reconciles the S3 bucket. func (s *Service) ReconcileBucket() error { if !s.bucketManagementEnabled() { return nil @@ -84,6 +86,7 @@ func (s *Service) ReconcileBucket() error { return nil } +// DeleteBucket deletes the S3 bucket. func (s *Service) DeleteBucket() error { if !s.bucketManagementEnabled() { return nil @@ -119,6 +122,7 @@ func (s *Service) DeleteBucket() error { return nil } +// Create creates an object in the S3 bucket. func (s *Service) Create(m *scope.MachineScope, data []byte) (string, error) { if !s.bucketManagementEnabled() { return "", errors.New("requested object creation but bucket management is not enabled") @@ -164,6 +168,7 @@ func (s *Service) Create(m *scope.MachineScope, data []byte) (string, error) { return objectURL.String(), nil } +// Delete deletes the object from the S3 bucket. func (s *Service) Delete(m *scope.MachineScope) error { if !s.bucketManagementEnabled() { return errors.New("requested object creation but bucket management is not enabled") diff --git a/pkg/cloud/services/s3/s3_test.go b/pkg/cloud/services/s3/s3_test.go index b74922f0f8..baa44ff875 100644 --- a/pkg/cloud/services/s3/s3_test.go +++ b/pkg/cloud/services/s3/s3_test.go @@ -290,7 +290,7 @@ func TestReconcileBucket(t *testing.T) { mockCtrl := gomock.NewController(t) stsMock := mock_stsiface.NewMockSTSAPI(mockCtrl) - stsMock.EXPECT().GetCallerIdentity(gomock.Any()).Return(nil, fmt.Errorf(t.Name())).AnyTimes() + stsMock.EXPECT().GetCallerIdentity(gomock.Any()).Return(nil, errors.New(t.Name())).AnyTimes() svc.STSClient = stsMock if err := svc.ReconcileBucket(); err == nil { diff --git a/pkg/cloud/services/secretsmanager/mock_secretsmanageriface/doc.go b/pkg/cloud/services/secretsmanager/mock_secretsmanageriface/doc.go index 6f9493872e..88f2878984 100644 --- a/pkg/cloud/services/secretsmanager/mock_secretsmanageriface/doc.go +++ b/pkg/cloud/services/secretsmanager/mock_secretsmanageriface/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_secretsmanageriface provides a mock interface for the SecretsManager API client. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination secretsmanagerapi_mock.go -package mock_secretsmanageriface github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface SecretsManagerAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt secretsmanagerapi_mock.go > _secretsmanagerapi_mock.go && mv _secretsmanagerapi_mock.go secretsmanagerapi_mock.go" - package mock_secretsmanageriface //nolint:stylecheck diff --git a/pkg/cloud/services/secretsmanager/service.go b/pkg/cloud/services/secretsmanager/service.go index 02e844919d..c9a06510f6 100644 --- a/pkg/cloud/services/secretsmanager/service.go +++ b/pkg/cloud/services/secretsmanager/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package secretsmanager provides a way to interact with AWS Secrets Manager. package secretsmanager import ( diff --git a/pkg/cloud/services/securitygroup/securitygroups.go b/pkg/cloud/services/securitygroup/securitygroups.go index 1a3c9440e1..b6e9bcabc4 100644 --- a/pkg/cloud/services/securitygroup/securitygroups.go +++ b/pkg/cloud/services/securitygroup/securitygroups.go @@ -207,7 +207,7 @@ func (s *Service) securityGroupIsAnOverride(securityGroupID string) bool { } func (s *Service) describeSecurityGroupOverridesByID() (map[infrav1.SecurityGroupRole]*ec2.SecurityGroup, error) { - securityGroupIds := map[infrav1.SecurityGroupRole]*string{} + securityGroupIDs := map[infrav1.SecurityGroupRole]*string{} input := &ec2.DescribeSecurityGroupsInput{} overrides := s.scope.SecurityGroupOverrides() @@ -221,7 +221,7 @@ func (s *Service) describeSecurityGroupOverridesByID() (map[infrav1.SecurityGrou for _, role := range s.roles { securityGroupID, ok := s.scope.SecurityGroupOverrides()[role] if ok { - securityGroupIds[role] = aws.String(securityGroupID) + securityGroupIDs[role] = aws.String(securityGroupID) input.GroupIds = append(input.GroupIds, aws.String(securityGroupID)) } } @@ -235,10 +235,10 @@ func (s *Service) describeSecurityGroupOverridesByID() (map[infrav1.SecurityGrou res := make(map[infrav1.SecurityGroupRole]*ec2.SecurityGroup, len(out.SecurityGroups)) for _, role := range s.roles { for _, ec2sg := range out.SecurityGroups { - if securityGroupIds[role] == nil { + if securityGroupIDs[role] == nil { continue } - if *ec2sg.GroupId == *securityGroupIds[role] { + if *ec2sg.GroupId == *securityGroupIDs[role] { s.scope.Debug("found security group override", "role", role, "security group", *ec2sg.GroupName) res[role] = ec2sg @@ -285,7 +285,7 @@ func (s *Service) DeleteSecurityGroups() error { for i := range clusterGroups { sg := clusterGroups[i] current := sg.IngressRules - if err := s.revokeAllSecurityGroupIngressRules(sg.ID); awserrors.IsIgnorableSecurityGroupError(err) != nil { + if err := s.revokeAllSecurityGroupIngressRules(sg.ID); awserrors.IsIgnorableSecurityGroupError(err) != nil { //nolint:gocritic conditions.MarkFalse(s.scope.InfraCluster(), infrav1.ClusterSecurityGroupsReadyCondition, "DeletingFailed", clusterv1.ConditionSeverityWarning, err.Error()) return err } @@ -311,7 +311,7 @@ func (s *Service) deleteSecurityGroup(sg *infrav1.SecurityGroup, typ string) err GroupId: aws.String(sg.ID), } - if _, err := s.EC2Client.DeleteSecurityGroupWithContext(context.TODO(), input); awserrors.IsIgnorableSecurityGroupError(err) != nil { + if _, err := s.EC2Client.DeleteSecurityGroupWithContext(context.TODO(), input); awserrors.IsIgnorableSecurityGroupError(err) != nil { //nolint:gocritic record.Warnf(s.scope.InfraCluster(), "FailedDeleteSecurityGroup", "Failed to delete %s SecurityGroup %q with name %q: %v", typ, sg.ID, sg.Name, err) return errors.Wrapf(err, "failed to delete security group %q with name %q", sg.ID, sg.Name) } diff --git a/pkg/cloud/services/securitygroup/securitygroups_test.go b/pkg/cloud/services/securitygroup/securitygroups_test.go index 50fe7007dc..31466058d8 100644 --- a/pkg/cloud/services/securitygroup/securitygroups_test.go +++ b/pkg/cloud/services/securitygroup/securitygroups_test.go @@ -1050,24 +1050,25 @@ func TestAdditionalControlPlaneSecurityGroup(t *testing.T) { found := false for _, r := range rules { - if r.Description == "test" { - found = true + if r.Description != "test" { + continue + } + found = true - if r.Protocol != tc.expectedAdditionalIngresRule.Protocol { - t.Fatalf("Expected protocol %s, got %s", tc.expectedAdditionalIngresRule.Protocol, r.Protocol) - } + if r.Protocol != tc.expectedAdditionalIngresRule.Protocol { + t.Fatalf("Expected protocol %s, got %s", tc.expectedAdditionalIngresRule.Protocol, r.Protocol) + } - if r.FromPort != tc.expectedAdditionalIngresRule.FromPort { - t.Fatalf("Expected from port %d, got %d", tc.expectedAdditionalIngresRule.FromPort, r.FromPort) - } + if r.FromPort != tc.expectedAdditionalIngresRule.FromPort { + t.Fatalf("Expected from port %d, got %d", tc.expectedAdditionalIngresRule.FromPort, r.FromPort) + } - if r.ToPort != tc.expectedAdditionalIngresRule.ToPort { - t.Fatalf("Expected to port %d, got %d", tc.expectedAdditionalIngresRule.ToPort, r.ToPort) - } + if r.ToPort != tc.expectedAdditionalIngresRule.ToPort { + t.Fatalf("Expected to port %d, got %d", tc.expectedAdditionalIngresRule.ToPort, r.ToPort) + } - if !sets.New[string](tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs...).Equal(sets.New[string](tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs...)) { - t.Fatalf("Expected source security group IDs %v, got %v", tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs, r.SourceSecurityGroupIDs) - } + if !sets.New[string](tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs...).Equal(sets.New[string](tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs...)) { + t.Fatalf("Expected source security group IDs %v, got %v", tc.expectedAdditionalIngresRule.SourceSecurityGroupIDs, r.SourceSecurityGroupIDs) } } diff --git a/pkg/cloud/services/securitygroup/service.go b/pkg/cloud/services/securitygroup/service.go index 68c82d0752..63231ea260 100644 --- a/pkg/cloud/services/securitygroup/service.go +++ b/pkg/cloud/services/securitygroup/service.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package securitygroup provides a service to manage AWS security group resources. package securitygroup import ( diff --git a/pkg/cloud/services/ssm/cloudinit.go b/pkg/cloud/services/ssm/cloudinit.go index f507d1a1fb..4159238fba 100644 --- a/pkg/cloud/services/ssm/cloudinit.go +++ b/pkg/cloud/services/ssm/cloudinit.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package ssm provides a service to generate userdata for AWS Systems Manager. package ssm import ( diff --git a/pkg/cloud/services/ssm/mock_ssmiface/doc.go b/pkg/cloud/services/ssm/mock_ssmiface/doc.go index e71c785bf9..8188fc99d5 100644 --- a/pkg/cloud/services/ssm/mock_ssmiface/doc.go +++ b/pkg/cloud/services/ssm/mock_ssmiface/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_ssmiface provides a mock interface for the SSM API client. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination ssmapi_mock.go -package mock_ssmiface github.com/aws/aws-sdk-go/service/ssm/ssmiface SSMAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt ssmapi_mock.go > _ssmapi_mock.go && mv _ssmapi_mock.go ssmapi_mock.go" - package mock_ssmiface //nolint:stylecheck diff --git a/pkg/cloud/services/sts/mock_stsiface/doc.go b/pkg/cloud/services/sts/mock_stsiface/doc.go index 900464f08d..1c576fa536 100644 --- a/pkg/cloud/services/sts/mock_stsiface/doc.go +++ b/pkg/cloud/services/sts/mock_stsiface/doc.go @@ -14,8 +14,9 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mock_stsiface provides a mock implementation for the STSAPI interface. // Run go generate to regenerate this mock. +// //go:generate ../../../../../hack/tools/bin/mockgen -destination stsiface_mock.go -package mock_stsiface github.com/aws/aws-sdk-go/service/sts/stsiface STSAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt stsiface_mock.go > _stsiface_mock.go && mv _stsiface_mock.go stsiface_mock.go" - package mock_stsiface //nolint:stylecheck diff --git a/pkg/cloud/services/userdata/userdata.go b/pkg/cloud/services/userdata/userdata.go index 6b565dfbc3..f7953b6b09 100644 --- a/pkg/cloud/services/userdata/userdata.go +++ b/pkg/cloud/services/userdata/userdata.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package userdata provides a way to generate user data for cloud instances. package userdata import ( diff --git a/pkg/cloud/services/wait/wait.go b/pkg/cloud/services/wait/wait.go index f9b9bf7a27..b725fa6b14 100644 --- a/pkg/cloud/services/wait/wait.go +++ b/pkg/cloud/services/wait/wait.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package wait provides a set of utilities for polling and waiting. package wait import ( diff --git a/pkg/cloud/tags/tags.go b/pkg/cloud/tags/tags.go index 7f97616c5b..42c8bfd843 100644 --- a/pkg/cloud/tags/tags.go +++ b/pkg/cloud/tags/tags.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package tags provides a way to tag cloud resources. package tags import ( diff --git a/pkg/cloud/throttle/throttle.go b/pkg/cloud/throttle/throttle.go index c0e2321997..77511952b7 100644 --- a/pkg/cloud/throttle/throttle.go +++ b/pkg/cloud/throttle/throttle.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package throttle provides a way to limit the number of requests to AWS services. package throttle import ( @@ -60,7 +61,7 @@ func (o *OperationLimiter) Match(r *request.Request) (bool, error) { return false, err } } - return o.regexp.Match([]byte(r.Operation.Name)), nil + return o.regexp.MatchString(r.Operation.Name), nil } // LimitRequest will limit a request. diff --git a/pkg/cloudtest/cloudtest.go b/pkg/cloudtest/cloudtest.go index 482fd54f5f..3264405784 100644 --- a/pkg/cloudtest/cloudtest.go +++ b/pkg/cloudtest/cloudtest.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cloudtest provides utilities for testing. package cloudtest import ( @@ -42,23 +43,24 @@ func RuntimeRawExtension(t *testing.T, p interface{}) *runtime.RawExtension { // test log messages. type Log struct{} -func (l *Log) Init(info logr.RuntimeInfo) { +// Init initializes the logger. +func (l *Log) Init(_ logr.RuntimeInfo) { } // Error implements Log errors. -func (l *Log) Error(err error, msg string, keysAndValues ...interface{}) {} +func (l *Log) Error(_ error, _ string, _ ...interface{}) {} // V returns the Logger's log level. -func (l *Log) V(level int) logr.LogSink { return l } +func (l *Log) V(_ int) logr.LogSink { return l } // WithValues returns logs with specific values. -func (l *Log) WithValues(keysAndValues ...interface{}) logr.LogSink { return l } +func (l *Log) WithValues(_ ...interface{}) logr.LogSink { return l } // WithName returns the logger with a specific name. -func (l *Log) WithName(name string) logr.LogSink { return l } +func (l *Log) WithName(_ string) logr.LogSink { return l } // Info implements info messages for the logger. -func (l *Log) Info(level int, msg string, keysAndValues ...interface{}) {} +func (l *Log) Info(_ int, _ string, _ ...interface{}) {} // Enabled returns the state of the logger. -func (l *Log) Enabled(level int) bool { return false } +func (l *Log) Enabled(_ int) bool { return false } diff --git a/pkg/eks/addons/plan.go b/pkg/eks/addons/plan.go index ae4425dc1f..22d46e2ab8 100644 --- a/pkg/eks/addons/plan.go +++ b/pkg/eks/addons/plan.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package addons provides a plan to manage EKS addons. package addons import ( @@ -45,7 +46,7 @@ type plan struct { } // Create will create the plan (i.e. list of procedures) for managing EKS addons. -func (a *plan) Create(ctx context.Context) ([]planner.Procedure, error) { +func (a *plan) Create(_ context.Context) ([]planner.Procedure, error) { procedures := []planner.Procedure{} // Handle create and update @@ -54,8 +55,10 @@ func (a *plan) Create(ctx context.Context) ([]planner.Procedure, error) { installed := a.getInstalled(*desired.Name) if installed == nil { // Need to add the addon - procedures = append(procedures, &CreateAddonProcedure{plan: a, name: *desired.Name}) - procedures = append(procedures, &WaitAddonActiveProcedure{plan: a, name: *desired.Name, includeDegraded: true}) + procedures = append(procedures, + &CreateAddonProcedure{plan: a, name: *desired.Name}, + &WaitAddonActiveProcedure{plan: a, name: *desired.Name, includeDegraded: true}, + ) } else { // Check if its just the tags that need updating diffTags := desired.Tags.Difference(installed.Tags) @@ -64,8 +67,10 @@ func (a *plan) Create(ctx context.Context) ([]planner.Procedure, error) { } // Check if we also need to update the addon if !desired.IsEqual(installed, false) { - procedures = append(procedures, &UpdateAddonProcedure{plan: a, name: *installed.Name}) - procedures = append(procedures, &WaitAddonActiveProcedure{plan: a, name: *desired.Name, includeDegraded: true}) + procedures = append(procedures, + &UpdateAddonProcedure{plan: a, name: *installed.Name}, + &WaitAddonActiveProcedure{plan: a, name: *desired.Name, includeDegraded: true}, + ) } else if *installed.Status != eks.AddonStatusActive { // If the desired and installed are the same make sure its active procedures = append(procedures, &WaitAddonActiveProcedure{plan: a, name: *desired.Name, includeDegraded: true}) diff --git a/pkg/eks/addons/procedures.go b/pkg/eks/addons/procedures.go index a57435f014..82f24f56ac 100644 --- a/pkg/eks/addons/procedures.go +++ b/pkg/eks/addons/procedures.go @@ -43,7 +43,7 @@ type DeleteAddonProcedure struct { } // Do implements the logic for the procedure. -func (p *DeleteAddonProcedure) Do(ctx context.Context) error { +func (p *DeleteAddonProcedure) Do(_ context.Context) error { input := &eks.DeleteAddonInput{ AddonName: aws.String(p.name), ClusterName: aws.String(p.plan.clusterName), @@ -68,7 +68,7 @@ type UpdateAddonProcedure struct { } // Do implements the logic for the procedure. -func (p *UpdateAddonProcedure) Do(ctx context.Context) error { +func (p *UpdateAddonProcedure) Do(_ context.Context) error { desired := p.plan.getDesired(p.name) if desired == nil { @@ -103,7 +103,7 @@ type UpdateAddonTagsProcedure struct { } // Do implements the logic for the procedure. -func (p *UpdateAddonTagsProcedure) Do(ctx context.Context) error { +func (p *UpdateAddonTagsProcedure) Do(_ context.Context) error { desired := p.plan.getDesired(p.name) installed := p.plan.getInstalled(p.name) @@ -138,7 +138,7 @@ type CreateAddonProcedure struct { } // Do implements the logic for the procedure. -func (p *CreateAddonProcedure) Do(ctx context.Context) error { +func (p *CreateAddonProcedure) Do(_ context.Context) error { desired := p.plan.getDesired(p.name) if desired == nil { return fmt.Errorf("getting desired addon %s: %w", p.name, ErrAddonNotFound) @@ -181,7 +181,7 @@ type WaitAddonActiveProcedure struct { } // Do implements the logic for the procedure. -func (p *WaitAddonActiveProcedure) Do(ctx context.Context) error { +func (p *WaitAddonActiveProcedure) Do(_ context.Context) error { input := &eks.DescribeAddonInput{ AddonName: aws.String(p.name), ClusterName: aws.String(p.plan.clusterName), @@ -222,7 +222,7 @@ type WaitAddonDeleteProcedure struct { } // Do implements the logic for the procedure. -func (p *WaitAddonDeleteProcedure) Do(ctx context.Context) error { +func (p *WaitAddonDeleteProcedure) Do(_ context.Context) error { input := &eks.DescribeAddonInput{ AddonName: aws.String(p.name), ClusterName: aws.String(p.plan.clusterName), diff --git a/pkg/eks/eks.go b/pkg/eks/eks.go index ebbe442ef5..df25b1b42e 100644 --- a/pkg/eks/eks.go +++ b/pkg/eks/eks.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package eks contains the EKS API implementation. package eks import ( diff --git a/pkg/eks/identityprovider/plan.go b/pkg/eks/identityprovider/plan.go index 1aeaaf125d..fa7975ed1a 100644 --- a/pkg/eks/identityprovider/plan.go +++ b/pkg/eks/identityprovider/plan.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package identityprovider provides a plan to manage EKS OIDC identity provider association. package identityprovider import ( @@ -46,7 +47,8 @@ type plan struct { clusterName string } -func (p *plan) Create(ctx context.Context) ([]planner.Procedure, error) { +// Create will create the plan (i.e. list of procedures) for managing EKS OIDC identity provider association. +func (p *plan) Create(_ context.Context) ([]planner.Procedure, error) { procedures := []planner.Procedure{} if p.desiredIdentityProvider == nil && p.currentIdentityProvider == nil { diff --git a/pkg/eks/identityprovider/procedures.go b/pkg/eks/identityprovider/procedures.go index 20f01ebf6f..ee12f9f9ed 100644 --- a/pkg/eks/identityprovider/procedures.go +++ b/pkg/eks/identityprovider/procedures.go @@ -28,14 +28,17 @@ import ( var oidcType = aws.String("oidc") +// WaitIdentityProviderAssociatedProcedure waits for the identity provider to be associated. type WaitIdentityProviderAssociatedProcedure struct { plan *plan } +// Name returns the name of the procedure. func (w *WaitIdentityProviderAssociatedProcedure) Name() string { return "wait_identity_provider_association" } +// Do waits for the identity provider to be associated. func (w *WaitIdentityProviderAssociatedProcedure) Do(ctx context.Context) error { if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { out, err := w.plan.eksClient.DescribeIdentityProviderConfigWithContext(ctx, &eks.DescribeIdentityProviderConfigInput{ @@ -62,14 +65,17 @@ func (w *WaitIdentityProviderAssociatedProcedure) Do(ctx context.Context) error return nil } +// DisassociateIdentityProviderConfig disassociates the identity provider. type DisassociateIdentityProviderConfig struct { plan *plan } +// Name returns the name of the procedure. func (d *DisassociateIdentityProviderConfig) Name() string { return "dissociate_identity_provider" } +// Do disassociates the identity provider. func (d *DisassociateIdentityProviderConfig) Do(ctx context.Context) error { if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { _, err := d.plan.eksClient.DisassociateIdentityProviderConfigWithContext(ctx, &eks.DisassociateIdentityProviderConfigInput{ @@ -92,14 +98,17 @@ func (d *DisassociateIdentityProviderConfig) Do(ctx context.Context) error { return nil } +// AssociateIdentityProviderProcedure associates the identity provider. type AssociateIdentityProviderProcedure struct { plan *plan } +// Name returns the name of the procedure. func (a *AssociateIdentityProviderProcedure) Name() string { return "associate_identity_provider" } +// Do associates the identity provider. func (a *AssociateIdentityProviderProcedure) Do(ctx context.Context) error { oidc := a.plan.desiredIdentityProvider input := &eks.AssociateIdentityProviderConfigInput{ @@ -128,15 +137,18 @@ func (a *AssociateIdentityProviderProcedure) Do(ctx context.Context) error { return nil } +// UpdatedIdentityProviderTagsProcedure updates the tags for the identity provider. type UpdatedIdentityProviderTagsProcedure struct { plan *plan } +// Name returns the name of the procedure. func (u *UpdatedIdentityProviderTagsProcedure) Name() string { return "update_identity_provider_tags" } -func (u *UpdatedIdentityProviderTagsProcedure) Do(ctx context.Context) error { +// Do updates the tags for the identity provider. +func (u *UpdatedIdentityProviderTagsProcedure) Do(_ context.Context) error { arn := u.plan.currentIdentityProvider.IdentityProviderConfigArn _, err := u.plan.eksClient.TagResource(&eks.TagResourceInput{ ResourceArn: &arn, @@ -150,15 +162,18 @@ func (u *UpdatedIdentityProviderTagsProcedure) Do(ctx context.Context) error { return nil } +// RemoveIdentityProviderTagsProcedure removes the tags from the identity provider. type RemoveIdentityProviderTagsProcedure struct { plan *plan } +// Name returns the name of the procedure. func (r *RemoveIdentityProviderTagsProcedure) Name() string { return "remove_identity_provider_tags" } -func (r *RemoveIdentityProviderTagsProcedure) Do(ctx context.Context) error { +// Do removes the tags from the identity provider. +func (r *RemoveIdentityProviderTagsProcedure) Do(_ context.Context) error { keys := make([]*string, 0, len(r.plan.currentIdentityProvider.Tags)) for key := range r.plan.currentIdentityProvider.Tags { diff --git a/pkg/eks/identityprovider/types.go b/pkg/eks/identityprovider/types.go index e7e5868f95..940e8870e5 100644 --- a/pkg/eks/identityprovider/types.go +++ b/pkg/eks/identityprovider/types.go @@ -39,6 +39,7 @@ type OidcIdentityProviderConfig struct { UsernamePrefix string } +// IsEqual returns true if the OidcIdentityProviderConfig is equal to the supplied one. func (o *OidcIdentityProviderConfig) IsEqual(other *OidcIdentityProviderConfig) bool { if o == other { return true diff --git a/pkg/hash/base36.go b/pkg/hash/base36.go index 386b5adfc5..f03f515001 100644 --- a/pkg/hash/base36.go +++ b/pkg/hash/base36.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package hash provides a consistent hash function using blake2b. package hash import ( diff --git a/pkg/internal/bytes/bytes.go b/pkg/internal/bytes/bytes.go index 401a194d57..a9aa86df6e 100644 --- a/pkg/internal/bytes/bytes.go +++ b/pkg/internal/bytes/bytes.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package bytes provides utilities for working with byte arrays. package bytes import ( diff --git a/pkg/internal/cidr/cidr.go b/pkg/internal/cidr/cidr.go index dd56ee5e75..30f0ee4596 100644 --- a/pkg/internal/cidr/cidr.go +++ b/pkg/internal/cidr/cidr.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cidr provides utilities for working with CIDR blocks. package cidr import ( diff --git a/pkg/internal/cmp/slice.go b/pkg/internal/cmp/slice.go index b2ff2d50db..6d36faa626 100644 --- a/pkg/internal/cmp/slice.go +++ b/pkg/internal/cmp/slice.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cmp provides a set of comparison functions. package cmp import ( @@ -22,20 +23,25 @@ import ( "k8s.io/utils/ptr" ) +// ByPtrValue is a type to sort a slice of pointers to strings. type ByPtrValue []*string +// Len returns the length of the slice. func (s ByPtrValue) Len() int { return len(s) } +// Swap swaps the elements with indexes i and j. func (s ByPtrValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +// Less returns true if the element with index i should sort before the element with index j. func (s ByPtrValue) Less(i, j int) bool { return *s[i] < *s[j] } +// Equals returns true if the two slices of pointers to strings are equal. func Equals(slice1, slice2 []*string) bool { sort.Sort(ByPtrValue(slice1)) sort.Sort(ByPtrValue(slice2)) diff --git a/pkg/internal/mime/mime.go b/pkg/internal/mime/mime.go index 1324482f9f..7f7b23aa8b 100644 --- a/pkg/internal/mime/mime.go +++ b/pkg/internal/mime/mime.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mime provides a function to generate a multipart MIME document. package mime import ( diff --git a/pkg/internal/rate/rate.go b/pkg/internal/rate/rate.go index 7528cfcad2..607f13f799 100644 --- a/pkg/internal/rate/rate.go +++ b/pkg/internal/rate/rate.go @@ -195,7 +195,7 @@ func (r *Reservation) CancelAt(now time.Time) { r.lim.tokens = tokens if r.timeToAct == r.lim.lastEvent { prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens))) - if !prevEvent.Before(now) { + if prevEvent.After(now) { r.lim.lastEvent = prevEvent } } diff --git a/pkg/internal/tristate/tristate.go b/pkg/internal/tristate/tristate.go index 6aafa52dc4..eeaae0ed86 100644 --- a/pkg/internal/tristate/tristate.go +++ b/pkg/internal/tristate/tristate.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package tristate provides a helper for working with bool pointers. package tristate // withDefault evaluates a pointer to a bool with a default value. diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index c2cd0ebde2..fa05ff5427 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package logger +// Package logger provides a convenient interface to use to log. package logger import ( @@ -69,35 +69,42 @@ func FromContext(ctx context.Context) *Logger { var _ Wrapper = &Logger{} +// Info logs a message at the info level. func (c *Logger) Info(msg string, keysAndValues ...any) { c.callStackHelper() c.logger.Info(msg, keysAndValues...) } +// Debug logs a message at the debug level. func (c *Logger) Debug(msg string, keysAndValues ...any) { c.callStackHelper() c.logger.V(logLevelDebug).Info(msg, keysAndValues...) } +// Warn logs a message at the warn level. func (c *Logger) Warn(msg string, keysAndValues ...any) { c.callStackHelper() c.logger.V(logLevelWarn).Info(msg, keysAndValues...) } +// Trace logs a message at the trace level. func (c *Logger) Trace(msg string, keysAndValues ...any) { c.callStackHelper() c.logger.V(logLevelTrace).Info(msg, keysAndValues...) } +// Error logs a message at the error level. func (c *Logger) Error(err error, msg string, keysAndValues ...any) { c.callStackHelper() c.logger.Error(err, msg, keysAndValues...) } +// GetLogger returns the underlying logr.Logger. func (c *Logger) GetLogger() logr.Logger { return c.logger } +// WithValues adds some key-value pairs of context to a logger. func (c *Logger) WithValues(keysAndValues ...any) *Logger { return &Logger{ callStackHelper: c.callStackHelper, @@ -105,6 +112,7 @@ func (c *Logger) WithValues(keysAndValues ...any) *Logger { } } +// WithName adds a new element to the logger's name. func (c *Logger) WithName(name string) *Logger { return &Logger{ callStackHelper: c.callStackHelper, diff --git a/pkg/planner/planner.go b/pkg/planner/planner.go index 9010b31edb..74ea078e2d 100644 --- a/pkg/planner/planner.go +++ b/pkg/planner/planner.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package planner provides a simple interface for creating and executing plans. package planner import "context" diff --git a/pkg/record/recorder.go b/pkg/record/recorder.go index 7591249a9b..df9a299264 100644 --- a/pkg/record/recorder.go +++ b/pkg/record/recorder.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package record provides a way to record Kubernetes events. package record import ( diff --git a/pkg/rosa/client.go b/pkg/rosa/client.go index 8d027f89ce..67c066238f 100644 --- a/pkg/rosa/client.go +++ b/pkg/rosa/client.go @@ -1,3 +1,4 @@ +// Package rosa provides a way to interact with the Red Hat OpenShift Service on AWS (ROSA) API. package rosa import ( @@ -18,6 +19,7 @@ const ( ocmAPIURLKey = "ocmApiUrl" ) +// NewOCMClient creates a new OCM client. func NewOCMClient(ctx context.Context, rosaScope *scope.ROSAControlPlaneScope) (*ocm.Client, error) { token, url, err := ocmCredentials(ctx, rosaScope) if err != nil { diff --git a/pkg/rosa/idps.go b/pkg/rosa/idps.go index 72e0562d92..bfa9fce65e 100644 --- a/pkg/rosa/idps.go +++ b/pkg/rosa/idps.go @@ -97,17 +97,19 @@ func findExistingClusterAdminIDP(client *ocm.Client, clusterID string) ( } for _, idp := range idps { - if idp.Name() == clusterAdminIDPname { - itemUserList, err := client.GetHTPasswdUserList(clusterID, idp.ID()) - if err != nil { - reterr = fmt.Errorf("failed to get user list of the HTPasswd IDP of '%s: %s': %v", idp.Name(), clusterID, err) - return - } - - htpasswdIDP = idp - userList = itemUserList + if idp.Name() != clusterAdminIDPname { + continue + } + + itemUserList, err := client.GetHTPasswdUserList(clusterID, idp.ID()) + if err != nil { + reterr = fmt.Errorf("failed to get user list of the HTPasswd IDP of '%s: %s': %v", idp.Name(), clusterID, err) return } + + htpasswdIDP = idp + userList = itemUserList + return } return diff --git a/pkg/rosa/oauth.go b/pkg/rosa/oauth.go index 110f638392..299dfb01d3 100644 --- a/pkg/rosa/oauth.go +++ b/pkg/rosa/oauth.go @@ -14,6 +14,7 @@ import ( restclient "k8s.io/client-go/rest" ) +// TokenResponse contains the access token and the duration until it expires. type TokenResponse struct { AccessToken string ExpiresIn time.Duration @@ -29,7 +30,7 @@ func RequestToken(ctx context.Context, apiURL, username, password string, config } tokenReqURL := fmt.Sprintf("%s/oauth/authorize?response_type=token&client_id=%s", oauthURL, clientID) - request, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenReqURL, nil) + request, err := http.NewRequestWithContext(ctx, http.MethodGet, tokenReqURL, http.NoBody) if err != nil { return nil, err } diff --git a/pkg/rosa/versions.go b/pkg/rosa/versions.go index 44d6fcecdb..d300adbf96 100644 --- a/pkg/rosa/versions.go +++ b/pkg/rosa/versions.go @@ -9,6 +9,7 @@ import ( "github.com/openshift/rosa/pkg/ocm" ) +// MinSupportedVersion is the minimum supported version for ROSA. var MinSupportedVersion = semver.MustParse("4.14.0") // CheckExistingScheduledUpgrade checks and returns the current upgrade schedule if any. @@ -79,6 +80,8 @@ func ScheduleNodePoolUpgrade(client *ocm.Client, clusterID string, nodePool *cmv // machinepools can be created with a minimal of two minor versions from the control plane. const minorVersionsAllowedDeviation = 2 +// MachinePoolSupportedVersionsRange returns the supported range of versions +// for a machine pool based on the control plane version. func MachinePoolSupportedVersionsRange(controlPlaneVersion string) (*semver.Version, *semver.Version, error) { maxVersion, err := semver.Parse(controlPlaneVersion) if err != nil { diff --git a/scripts/go_install.sh b/scripts/go_install.sh index 12ce444224..a07b8e0f11 100755 --- a/scripts/go_install.sh +++ b/scripts/go_install.sh @@ -37,7 +37,7 @@ if [ -z "${GOBIN}" ]; then exit 1 fi -rm "${GOBIN}/${2}"* || true +rm -f "${GOBIN}/${2}"* || true # install the golang module specified as the first argument go install "${1}@${3}" diff --git a/test/e2e/shared/aws.go b/test/e2e/shared/aws.go index 95b469780e..d42837a68e 100644 --- a/test/e2e/shared/aws.go +++ b/test/e2e/shared/aws.go @@ -953,7 +953,8 @@ func (s *ServiceQuota) updateServiceQuotaRequestStatus(serviceQuotasClient *serv } } -func DumpEKSClusters(ctx context.Context, e2eCtx *E2EContext) { +// DumpEKSClusters dumps the EKS clusters in the environment. +func DumpEKSClusters(_ context.Context, e2eCtx *E2EContext) { name := "no-bootstrap-cluster" if e2eCtx.Environment.BootstrapClusterProxy != nil { name = e2eCtx.Environment.BootstrapClusterProxy.GetName() @@ -1014,7 +1015,7 @@ func dumpEKSCluster(cluster *eks.Cluster, logPath string) { } // To calculate how much resources a test consumes, these helper functions below can be used. -// ListVpcInternetGateways, ListNATGateways, ListRunningEC2, ListVPC +// ListVpcInternetGateways, ListNATGateways, ListRunningEC2, ListVPC. func ListVpcInternetGateways(e2eCtx *E2EContext) ([]*ec2.InternetGateway, error) { ec2Svc := ec2.New(e2eCtx.AWSSession) @@ -1052,7 +1053,8 @@ func ListNATGateways(e2eCtx *E2EContext) (map[string]*ec2.NatGateway, error) { return gateways, nil } -func ListRunningEC2(e2eCtx *E2EContext) ([]instance, error) { +// listRunningEC2 returns a list of running EC2 instances. +func listRunningEC2(e2eCtx *E2EContext) ([]instance, error) { //nolint:unused ec2Svc := ec2.New(e2eCtx.AWSSession) resp, err := ec2Svc.DescribeInstancesWithContext(context.TODO(), &ec2.DescribeInstancesInput{ diff --git a/test/e2e/shared/common.go b/test/e2e/shared/common.go index 8cc2d9a6b4..c11e1d82f3 100644 --- a/test/e2e/shared/common.go +++ b/test/e2e/shared/common.go @@ -92,12 +92,13 @@ func DumpSpecResourcesAndCleanup(ctx context.Context, specName string, namespace delete(e2eCtx.Environment.Namespaces, namespace) } +// AWSStackLogCollector collects logs from the AWS stack. type AWSStackLogCollector struct { E2EContext *E2EContext } // CollectInfrastructureLogs collects log from the infrastructure. -func (k AWSStackLogCollector) CollectInfrastructureLogs(ctx context.Context, managementClusterClient crclient.Client, c *clusterv1.Cluster, outputPath string) error { +func (k AWSStackLogCollector) CollectInfrastructureLogs(_ context.Context, _ crclient.Client, _ *clusterv1.Cluster, _ string) error { return nil } diff --git a/test/e2e/shared/defaults.go b/test/e2e/shared/defaults.go index c67c5538a5..13e77c84f7 100644 --- a/test/e2e/shared/defaults.go +++ b/test/e2e/shared/defaults.go @@ -73,37 +73,51 @@ const ( MultiTenancy = "MULTI_TENANCY_" ) +// ResourceQuotaFilePath is the path to the file that contains the resource usage. var ResourceQuotaFilePath = "/tmp/capa-e2e-resource-usage.lock" + var ( + // MultiTenancySimpleRole is the simple role for multi-tenancy test. MultiTenancySimpleRole = MultitenancyRole("Simple") - MultiTenancyJumpRole = MultitenancyRole("Jump") + // MultiTenancyJumpRole is the jump role for multi-tenancy test. + MultiTenancyJumpRole = MultitenancyRole("Jump") + // MultiTenancyNestedRole is the nested role for multi-tenancy test. MultiTenancyNestedRole = MultitenancyRole("Nested") - MultiTenancyRoles = []MultitenancyRole{MultiTenancySimpleRole, MultiTenancyJumpRole, MultiTenancyNestedRole} - roleLookupCache = make(map[string]string) + + // MultiTenancyRoles is the list of multi-tenancy roles. + MultiTenancyRoles = []MultitenancyRole{MultiTenancySimpleRole, MultiTenancyJumpRole, MultiTenancyNestedRole} + roleLookupCache = make(map[string]string) ) +// MultitenancyRole is the role of the test. type MultitenancyRole string +// EnvVarARN returns the environment variable name for the role ARN. func (m MultitenancyRole) EnvVarARN() string { return MultiTenancy + strings.ToUpper(string(m)) + "_ROLE_ARN" } +// EnvVarName returns the environment variable name for the role name. func (m MultitenancyRole) EnvVarName() string { return MultiTenancy + strings.ToUpper(string(m)) + "_ROLE_NAME" } +// EnvVarIdentity returns the environment variable name for the identity name. func (m MultitenancyRole) EnvVarIdentity() string { return MultiTenancy + strings.ToUpper(string(m)) + "_IDENTITY_NAME" } +// IdentityName returns the identity name. func (m MultitenancyRole) IdentityName() string { return strings.ToLower(m.RoleName()) } +// RoleName returns the role name. func (m MultitenancyRole) RoleName() string { return "CAPAMultiTenancy" + string(m) } +// SetEnvVars sets the environment variables for the role. func (m MultitenancyRole) SetEnvVars(prov client.ConfigProvider) error { arn, err := m.RoleARN(prov) if err != nil { @@ -115,6 +129,7 @@ func (m MultitenancyRole) SetEnvVars(prov client.ConfigProvider) error { return nil } +// RoleARN returns the role ARN. func (m MultitenancyRole) RoleARN(prov client.ConfigProvider) (string, error) { if roleARN, ok := roleLookupCache[m.RoleName()]; ok { return roleARN, nil diff --git a/test/e2e/shared/gpu.go b/test/e2e/shared/gpu.go index 3bbdeed267..b871b2f010 100644 --- a/test/e2e/shared/gpu.go +++ b/test/e2e/shared/gpu.go @@ -103,7 +103,7 @@ type jobsClientAdapter struct { } // Get fetches the job named by the key and updates the provided object. -func (c jobsClientAdapter) Get(ctx context.Context, key crclient.ObjectKey, obj crclient.Object, opts ...crclient.GetOption) error { +func (c jobsClientAdapter) Get(ctx context.Context, key crclient.ObjectKey, obj crclient.Object, _ ...crclient.GetOption) error { job, err := c.client.Get(ctx, key.Name, metav1.GetOptions{}) if jobObj, ok := obj.(*batchv1.Job); ok { job.DeepCopyInto(jobObj) diff --git a/test/e2e/shared/suite.go b/test/e2e/shared/suite.go index 07e83fe0da..bd52878487 100644 --- a/test/e2e/shared/suite.go +++ b/test/e2e/shared/suite.go @@ -17,6 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package shared provides common utilities, setup and teardown for the e2e tests. package shared import ( @@ -118,8 +119,11 @@ func Node1BeforeSuite(e2eCtx *E2EContext) []byte { if prov.Name != "aws" { continue } - e2eCtx.E2EConfig.Providers[i].Files = append(e2eCtx.E2EConfig.Providers[i].Files, clusterctlCITemplate) - e2eCtx.E2EConfig.Providers[i].Files = append(e2eCtx.E2EConfig.Providers[i].Files, clusterctlCITemplateForUpgrade) + e2eCtx.E2EConfig.Providers[i].Files = append( + e2eCtx.E2EConfig.Providers[i].Files, + clusterctlCITemplate, + clusterctlCITemplateForUpgrade, + ) } } diff --git a/test/e2e/shared/template.go b/test/e2e/shared/template.go index caa16917e9..72c4884412 100644 --- a/test/e2e/shared/template.go +++ b/test/e2e/shared/template.go @@ -154,7 +154,7 @@ func renderCustomCloudFormation(t *cfn_bootstrap.Template) *cloudformation.Templ return cloudformationTemplate } -func appendMultiTenancyRoles(t *cfn_bootstrap.Template, cfnt *cloudformation.Template) { +func appendMultiTenancyRoles(_ *cfn_bootstrap.Template, cfnt *cloudformation.Template) { controllersPolicy := cfnt.Resources[string(cfn_bootstrap.ControllersPolicy)].(*cfn_iam.ManagedPolicy) controllersPolicy.Roles = append( controllersPolicy.Roles, diff --git a/test/e2e/suites/managed/cluster.go b/test/e2e/suites/managed/cluster.go index 1edae3adec..46829a2bcb 100644 --- a/test/e2e/suites/managed/cluster.go +++ b/test/e2e/suites/managed/cluster.go @@ -17,6 +17,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package managed implements a test for creating a managed cluster using CAPA. package managed import ( diff --git a/test/e2e/suites/managed/machine_deployment.go b/test/e2e/suites/managed/machine_deployment.go index 89a17c772a..79d26d3355 100644 --- a/test/e2e/suites/managed/machine_deployment.go +++ b/test/e2e/suites/managed/machine_deployment.go @@ -100,10 +100,6 @@ func MachineDeploymentSpec(ctx context.Context, inputGetter func() MachineDeploy Deleter: input.BootstrapClusterProxy.GetClient(), MachineDeployment: md[0], }) - // deleteMachine(ctx, deleteMachineInput{ - // Deleter: input.BootstrapClusterProxy.GetClient(), - // Machine: &workerMachines[0], - // }) waitForMachineDeploymentDeleted(ctx, waitForMachineDeploymentDeletedInput{ Getter: input.BootstrapClusterProxy.GetClient(), diff --git a/test/e2e/suites/unmanaged/helpers_test.go b/test/e2e/suites/unmanaged/helpers_test.go index 39457e481c..03c6870384 100644 --- a/test/e2e/suites/unmanaged/helpers_test.go +++ b/test/e2e/suites/unmanaged/helpers_test.go @@ -418,7 +418,7 @@ func getSubnetID(filterKey, filterValue, clusterName string) *string { return subnetOutput.Subnets[0].SubnetId } -func getVolumeIds(info statefulSetInfo, k8sclient crclient.Client) []*string { +func getVolumeIDs(info statefulSetInfo, k8sclient crclient.Client) []*string { ginkgo.By("Retrieving IDs of dynamically provisioned volumes.") statefulset := &appsv1.StatefulSet{} err := k8sclient.Get(context.TODO(), apimachinerytypes.NamespacedName{Namespace: info.namespace, Name: info.name}, statefulset) @@ -683,11 +683,11 @@ func verifyElbExists(elbName string, exists bool) { } } -func verifyVolumesExists(awsVolumeIds []*string) { +func verifyVolumesExists(awsVolumeIDs []*string) { ginkgo.By("Ensuring dynamically provisioned volumes exists") ec2Client := ec2.New(e2eCtx.AWSSession) input := &ec2.DescribeVolumesInput{ - VolumeIds: awsVolumeIds, + VolumeIds: awsVolumeIDs, } _, err := ec2Client.DescribeVolumes(input) Expect(err).NotTo(HaveOccurred()) diff --git a/test/e2e/suites/unmanaged/unmanaged_functional_test.go b/test/e2e/suites/unmanaged/unmanaged_functional_test.go index aed9e02309..a4e6a49404 100644 --- a/test/e2e/suites/unmanaged/unmanaged_functional_test.go +++ b/test/e2e/suites/unmanaged/unmanaged_functional_test.go @@ -319,8 +319,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { clusterClient := e2eCtx.Environment.BootstrapClusterProxy.GetWorkloadCluster(ctx, namespace.Name, cluster1Name).GetClient() createStatefulSet(nginxStatefulsetInfo, clusterClient) - awsVolIds := getVolumeIds(nginxStatefulsetInfo, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs := getVolumeIDs(nginxStatefulsetInfo, clusterClient) + verifyVolumesExists(awsVolIDs) kubernetesUgradeVersion := e2eCtx.E2EConfig.GetVariable(shared.PostCSIKubernetesVer) configCluster.KubernetesVersion = kubernetesUgradeVersion @@ -348,8 +348,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { ginkgo.By("Deploying StatefulSet on infra when K8s >= 1.23") createStatefulSet(nginxStatefulsetInfo2, clusterClient) - awsVolIds = getVolumeIds(nginxStatefulsetInfo2, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs = getVolumeIDs(nginxStatefulsetInfo2, clusterClient) + verifyVolumesExists(awsVolIDs) ginkgo.By("Deleting LB service") deleteLBService(metav1.NamespaceDefault, lbServiceName, clusterClient) @@ -358,7 +358,7 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { deleteCluster(ctx, cluster2) ginkgo.By("Deleting retained dynamically provisioned volumes") - deleteRetainedVolumes(awsVolIds) + deleteRetainedVolumes(awsVolIDs) ginkgo.By("PASSED!") }) }) @@ -388,8 +388,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { clusterClient := e2eCtx.Environment.BootstrapClusterProxy.GetWorkloadCluster(ctx, namespace.Name, cluster1Name).GetClient() createStatefulSet(nginxStatefulsetInfo, clusterClient) - awsVolIds := getVolumeIds(nginxStatefulsetInfo, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs := getVolumeIDs(nginxStatefulsetInfo, clusterClient) + verifyVolumesExists(awsVolIDs) kubernetesUgradeVersion := e2eCtx.E2EConfig.GetVariable(shared.PostCSIKubernetesVer) @@ -418,8 +418,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { ginkgo.By("Deploying StatefulSet on infra when K8s >= 1.23") createStatefulSet(nginxStatefulsetInfo2, clusterClient) - awsVolIds = getVolumeIds(nginxStatefulsetInfo2, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs = getVolumeIDs(nginxStatefulsetInfo2, clusterClient) + verifyVolumesExists(awsVolIDs) ginkgo.By("Deleting LB service") deleteLBService(metav1.NamespaceDefault, lbServiceName, clusterClient) @@ -428,7 +428,7 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { deleteCluster(ctx, cluster2) ginkgo.By("Deleting retained dynamically provisioned volumes") - deleteRetainedVolumes(awsVolIds) + deleteRetainedVolumes(awsVolIDs) ginkgo.By("PASSED!") }) }) @@ -459,8 +459,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { clusterClient := e2eCtx.Environment.BootstrapClusterProxy.GetWorkloadCluster(ctx, namespace.Name, cluster1Name).GetClient() createStatefulSet(nginxStatefulsetInfo, clusterClient) - awsVolIds := getVolumeIds(nginxStatefulsetInfo, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs := getVolumeIDs(nginxStatefulsetInfo, clusterClient) + verifyVolumesExists(awsVolIDs) kubernetesUgradeVersion := e2eCtx.E2EConfig.GetVariable(shared.PostCSIKubernetesVer) configCluster.KubernetesVersion = kubernetesUgradeVersion @@ -488,8 +488,8 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { ginkgo.By("Deploying StatefulSet on infra when K8s >= 1.23") createStatefulSet(nginxStatefulsetInfo2, clusterClient) - awsVolIds = getVolumeIds(nginxStatefulsetInfo2, clusterClient) - verifyVolumesExists(awsVolIds) + awsVolIDs = getVolumeIDs(nginxStatefulsetInfo2, clusterClient) + verifyVolumesExists(awsVolIDs) ginkgo.By("Deleting LB service") deleteLBService(metav1.NamespaceDefault, lbServiceName, clusterClient) @@ -498,7 +498,7 @@ var _ = ginkgo.Context("[unmanaged] [functional]", func() { deleteCluster(ctx, cluster2) ginkgo.By("Deleting retained dynamically provisioned volumes") - deleteRetainedVolumes(awsVolIds) + deleteRetainedVolumes(awsVolIDs) ginkgo.By("PASSED!") }) }) diff --git a/test/helpers/envtest.go b/test/helpers/envtest.go index 098a280d69..43f0618b0c 100644 --- a/test/helpers/envtest.go +++ b/test/helpers/envtest.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package helpers provides a set of utilities for testing controllers. package helpers import ( @@ -83,7 +84,7 @@ func init() { utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) // Get the root of the current file to use in CRD paths. - _, filename, _, _ := goruntime.Caller(0) //nolint + _, filename, _, _ := goruntime.Caller(0) //nolint:dogsled root = path.Join(path.Dir(filename), "..", "..") } @@ -237,7 +238,7 @@ func buildModifiedWebhook(tag string, relativeFilePath string) (admissionv1.Muta if o.GetKind() == mutatingWebhookKind { // update the name in metadata if o.GetName() == defaultMutatingWebhookName { - o.SetName(strings.Join([]string{defaultMutatingWebhookName, "-", tag}, "")) + o.SetName(defaultMutatingWebhookName + "-" + tag) if err := scheme.Scheme.Convert(&o, &mutatingWebhook, nil); err != nil { klog.Fatalf("failed to convert MutatingWebhookConfiguration %s", o.GetName()) } @@ -246,7 +247,7 @@ func buildModifiedWebhook(tag string, relativeFilePath string) (admissionv1.Muta if o.GetKind() == validatingWebhookKind { // update the name in metadata if o.GetName() == defaultValidatingWebhookName { - o.SetName(strings.Join([]string{defaultValidatingWebhookName, "-", tag}, "")) + o.SetName(defaultValidatingWebhookName + "-" + tag) if err := scheme.Scheme.Convert(&o, &validatingWebhook, nil); err != nil { klog.Fatalf("failed to convert ValidatingWebhookConfiguration %s", o.GetName()) } diff --git a/test/helpers/external/cluster.go b/test/helpers/external/cluster.go index 051fb88391..524c775e0d 100644 --- a/test/helpers/external/cluster.go +++ b/test/helpers/external/cluster.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package external provides mock CRDs for use in tests. package external import ( diff --git a/test/mocks/generate_aws.go b/test/mocks/generate_aws.go index 5c5e5a7f02..f3b08973ec 100644 --- a/test/mocks/generate_aws.go +++ b/test/mocks/generate_aws.go @@ -14,16 +14,14 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package mocks provides a way to generate mock objects for AWS services. +// //go:generate ../../hack/tools/bin/mockgen -destination aws_elbv2_mock.go -package mocks github.com/aws/aws-sdk-go/service/elbv2/elbv2iface ELBV2API //go:generate /usr/bin/env bash -c "cat ../../hack/boilerplate/boilerplate.generatego.txt aws_elbv2_mock.go > _aws_elbv2_mock.go && mv _aws_elbv2_mock.go aws_elbv2_mock.go" - //go:generate ../../hack/tools/bin/mockgen -destination aws_elb_mock.go -package mocks github.com/aws/aws-sdk-go/service/elb/elbiface ELBAPI //go:generate /usr/bin/env bash -c "cat ../../hack/boilerplate/boilerplate.generatego.txt aws_elb_mock.go > _aws_elb_mock.go && mv _aws_elb_mock.go aws_elb_mock.go" - //go:generate ../../hack/tools/bin/mockgen -destination aws_rgtagging_mock.go -package mocks github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/resourcegroupstaggingapiiface ResourceGroupsTaggingAPIAPI //go:generate /usr/bin/env bash -c "cat ../../hack/boilerplate/boilerplate.generatego.txt aws_rgtagging_mock.go > _aws_rgtagging_mock.go && mv _aws_rgtagging_mock.go aws_rgtagging_mock.go" - //go:generate ../../hack/tools/bin/mockgen -destination aws_ec2api_mock.go -package mocks github.com/aws/aws-sdk-go/service/ec2/ec2iface EC2API //go:generate /usr/bin/env bash -c "cat ../../hack/boilerplate/boilerplate.generatego.txt aws_ec2api_mock.go > _aws_ec2api_mock.go && mv _aws_ec2api_mock.go aws_ec2api_mock.go" - package mocks diff --git a/util/conditions/helper.go b/util/conditions/helper.go index c4e4ad7a2a..2acb09093e 100644 --- a/util/conditions/helper.go +++ b/util/conditions/helper.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package conditions provides helper functions for working with conditions. package conditions import ( diff --git a/util/system/util.go b/util/system/util.go index 786150950d..0b6eb9507c 100644 --- a/util/system/util.go +++ b/util/system/util.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package system contains utiilities for the system namespace. package system import ( diff --git a/version/version.go b/version/version.go index 4132c9f016..b895ae2daf 100644 --- a/version/version.go +++ b/version/version.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package version provides the version of the manager. package version import (