diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 0000000000..2cf235d808 --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,23 @@ +name: golangci-lint +on: + pull_request: + types: [opened, edited, synchronize, reopened] + branches: + - main + - master +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + strategy: + matrix: + working-directory: + - "" + - tools/setup-envtest + steps: + - uses: actions/checkout@v2 + - name: golangci-lint + uses: golangci/golangci-lint-action@v2 + with: + version: v1.40.1 + working-directory: ${{matrix.working-directory}} diff --git a/.golangci.yml b/.golangci.yml index 5aa700429d..a5a5dad615 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,36 +1,130 @@ -run: - deadline: 5m -linters-settings: - lll: - line-length: 170 - dupl: - threshold: 400 -issues: - # don't skip warning about doc comments - exclude-use-default: false - - # restore some of the defaults - # (fill in the rest as needed) - exclude-rules: - - linters: [errcheck] - text: "Error return value of .((os\\.)?std(out|err)\\..*|.*Close|.*Flush|os\\.Remove(All)?|.*printf?|os\\.(Un)?Setenv). is not checked" linters: disable-all: true enable: - - misspell - - structcheck - - golint - - govet + - asciicheck + - bodyclose - deadcode + - depguard + - dogsled - errcheck - - varcheck - - unparam - - ineffassign - - nakedret + - exportloopref + - goconst + - gocritic - gocyclo - - dupl + - godot + - gofmt - goimports - - golint - # disabled: - # - goconst is overly aggressive - # - lll generally just complains about flag help & error strings that are human-readable + - goprintffuncname + - gosec + - gosimple + - govet + - ifshort + - importas + - ineffassign + - misspell + - nakedret + - nilerr + - nolintlint + - prealloc + - revive + - rowserrcheck + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + - unparam + - varcheck + - whitespace + +linters-settings: + ifshort: + # Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax. + max-decl-chars: 50 + importas: + no-unaliased: true + alias: + # Kubernetes + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 + alias: apiextensionsv1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: kerrors + # Controller Runtime + - pkg: sigs.k8s.io/controller-runtime + alias: ctrl + staticcheck: + go: "1.16" + stylecheck: + go: "1.16" + +issues: + max-same-issues: 0 + max-issues-per-linter: 0 + # We are disabling default golangci exclusions because we want to help reviewers to focus on reviewing the most relevant + # changes in PRs and avoid nitpicking. + exclude-use-default: false + # List of regexps of issue texts to exclude, empty list by default. + exclude: + # The following are being worked on to remove their exclusion. This list should be reduced or go away all together over time. + # If it is decided they will not be addressed they should be moved above this comment. + - Subprocess launch(ed with variable|ing should be audited) + - (G204|G104|G307) + - "ST1000: at least one file in a package should have a package comment" + exclude-rules: + - linters: + - gosec + text: "G108: Profiling endpoint is automatically exposed on /debug/pprof" + - 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 + # With Go 1.16, the new embed directive can be used with an un-named import, + # revive (previously, golint) only allows these to be imported in a main.go, which wouldn't work for us. + # This directive allows the embed package to be imported with an underscore everywhere. + - linters: + - revive + source: _ "embed" + # 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 + source: (func|type).*Fake.* + - linters: + - revive + text: exported (method|function|type|const) (.+) should have comment or be unexported + path: fake_\.go + # Disable unparam "always receives" which might not be really + # useful when building libraries. + - linters: + - unparam + text: always receives + # Dot imports for gomega or ginkgo are allowed + # within test files. + - path: _test\.go + text: should not use dot imports + - path: _test\.go + text: cyclomatic complexity + - path: _test\.go + text: "G107: Potential HTTP request made with variable url" + # Append should be able to assign to a different var/slice. + - linters: + - gocritic + text: "appendAssign: append result not assigned to the same slice" + - linters: + - gocritic + text: "singleCaseSwitch: should rewrite switch statement to if statement" + +run: + timeout: 10m + skip-files: + - "zz_generated.*\\.go$" + - ".*conversion.*\\.go$" + allow-parallel-runners: true diff --git a/Makefile b/Makefile index 8541f2a2fc..f2cd38cad8 100644 --- a/Makefile +++ b/Makefile @@ -65,29 +65,29 @@ test-tools: ## tests the tools codebase (setup-envtest) ## Binaries ## -------------------------------------- -$(GOLANGCI_LINT): $(TOOLS_DIR)/go.mod # Build golangci-lint from tools folder. - cd $(TOOLS_DIR) && go build -tags=tools -o bin/golangci-lint github.com/golangci/golangci-lint/cmd/golangci-lint - $(GO_APIDIFF): $(TOOLS_DIR)/go.mod # Build go-apidiff from tools folder. cd $(TOOLS_DIR) && go build -tags=tools -o bin/go-apidiff github.com/joelanford/go-apidiff $(CONTROLLER_GEN): $(TOOLS_DIR)/go.mod # Build controller-gen from tools folder. cd $(TOOLS_DIR) && go build -tags=tools -o bin/controller-gen sigs.k8s.io/controller-tools/cmd/controller-gen +$(GOLANGCI_LINT): .github/workflows/golangci-lint.yml # Download golanci-lint using hack script into tools folder. + hack/ensure-golangci-lint.sh \ + -b $(TOOLS_BIN_DIR) \ + $(shell cat .github/workflows/golangci-lint.yml | grep version | sed 's/.*version: //') + ## -------------------------------------- ## Linting ## -------------------------------------- -.PHONY: lint-libs -lint-libs: $(GOLANGCI_LINT) ## Lint library codebase. - $(GOLANGCI_LINT) run -v - -.PHONY: lint-tools -lint-tools: $(GOLANGCI_LINT) ## Lint tools codebase. - cd tools/setup-envtest && $(GOLANGCI_LINT) run -v - .PHONY: lint -lint: lint-libs lint-tools +lint: $(GOLANGCI_LINT) ## Lint codebase + $(GOLANGCI_LINT) run -v $(GOLANGCI_LINT_EXTRA_ARGS) + cd tools/setup-envtest; $(GOLANGCI_LINT) run -v $(GOLANGCI_LINT_EXTRA_ARGS) + +.PHONY: lint-fix +lint-fix: $(GOLANGCI_LINT) ## Lint the codebase and run auto-fixers if supported by the linter. + GOLANGCI_LINT_EXTRA_ARGS=--fix $(MAKE) lint ## -------------------------------------- ## Generate diff --git a/alias.go b/alias.go index 9bda96616e..29f964dcbe 100644 --- a/alias.go +++ b/alias.go @@ -45,7 +45,7 @@ type Result = reconcile.Result // A Manager is required to create Controllers. type Manager = manager.Manager -// Options are the arguments for creating a new Manager +// Options are the arguments for creating a new Manager. type Options = manager.Options // SchemeBuilder builds a new Scheme for mapping go types to Kubernetes GroupVersionKinds. @@ -55,7 +55,7 @@ type SchemeBuilder = scheme.Builder type GroupVersion = schema.GroupVersion // GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying -// concepts during lookup stages without having partially valid types +// concepts during lookup stages without having partially valid types. type GroupResource = schema.GroupResource // TypeMeta describes an individual object in an API response or request @@ -89,7 +89,7 @@ var ( // // * In-cluster config if running in cluster // - // * $HOME/.kube/config if exists + // * $HOME/.kube/config if exists. GetConfig = config.GetConfig // ConfigFile returns the cfg.File function for deferred config file loading, @@ -97,10 +97,10 @@ var ( // the manager. ConfigFile = cfg.File - // NewControllerManagedBy returns a new controller builder that will be started by the provided Manager + // NewControllerManagedBy returns a new controller builder that will be started by the provided Manager. NewControllerManagedBy = builder.ControllerManagedBy - // NewWebhookManagedBy returns a new webhook builder that will be started by the provided Manager + // NewWebhookManagedBy returns a new webhook builder that will be started by the provided Manager. NewWebhookManagedBy = builder.WebhookManagedBy // NewManager returns a new Manager for creating Controllers. diff --git a/doc.go b/doc.go index 61ffc3e568..758662085d 100644 --- a/doc.go +++ b/doc.go @@ -28,7 +28,7 @@ limitations under the License. // The main entrypoint for controller-runtime is this root package, which // contains all of the common types needed to get started building controllers: // import ( -// controllers "sigs.k8s.io/controller-runtime" +// ctrl "sigs.k8s.io/controller-runtime" // ) // // The examples in this package walk through a basic controller setup. The diff --git a/example_test.go b/example_test.go index 5b23a88fd6..de4ae736a5 100644 --- a/example_test.go +++ b/example_test.go @@ -24,7 +24,7 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - controllers "sigs.k8s.io/controller-runtime" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -34,17 +34,17 @@ import ( // ReplicaSetReconciler. // // * Start the application. -// TODO(pwittrock): Update this example when we have better dependency injection support +// TODO(pwittrock): Update this example when we have better dependency injection support. func Example() { - var log = controllers.Log.WithName("builder-examples") + var log = ctrl.Log.WithName("builder-examples") - manager, err := controllers.NewManager(controllers.GetConfigOrDie(), controllers.Options{}) + manager, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{}) if err != nil { log.Error(err, "could not create manager") os.Exit(1) } - err = controllers. + err = ctrl. NewControllerManagedBy(manager). // Create the Controller For(&appsv1.ReplicaSet{}). // ReplicaSet is the Application API Owns(&corev1.Pod{}). // ReplicaSet owns Pods created by it @@ -54,7 +54,7 @@ func Example() { os.Exit(1) } - if err := manager.Start(controllers.SetupSignalHandler()); err != nil { + if err := manager.Start(ctrl.SetupSignalHandler()); err != nil { log.Error(err, "could not start manager") os.Exit(1) } @@ -72,15 +72,15 @@ func Example() { // ReplicaSetReconciler. // // * Start the application. -// TODO(pwittrock): Update this example when we have better dependency injection support +// TODO(pwittrock): Update this example when we have better dependency injection support. func Example_updateLeaderElectionDurations() { - var log = controllers.Log.WithName("builder-examples") + var log = ctrl.Log.WithName("builder-examples") leaseDuration := 100 * time.Second renewDeadline := 80 * time.Second retryPeriod := 20 * time.Second - manager, err := controllers.NewManager( - controllers.GetConfigOrDie(), - controllers.Options{ + manager, err := ctrl.NewManager( + ctrl.GetConfigOrDie(), + ctrl.Options{ LeaseDuration: &leaseDuration, RenewDeadline: &renewDeadline, RetryPeriod: &retryPeriod, @@ -90,7 +90,7 @@ func Example_updateLeaderElectionDurations() { os.Exit(1) } - err = controllers. + err = ctrl. NewControllerManagedBy(manager). // Create the Controller For(&appsv1.ReplicaSet{}). // ReplicaSet is the Application API Owns(&corev1.Pod{}). // ReplicaSet owns Pods created by it @@ -100,7 +100,7 @@ func Example_updateLeaderElectionDurations() { os.Exit(1) } - if err := manager.Start(controllers.SetupSignalHandler()); err != nil { + if err := manager.Start(ctrl.SetupSignalHandler()); err != nil { log.Error(err, "could not start manager") os.Exit(1) } @@ -117,28 +117,28 @@ type ReplicaSetReconciler struct { // // * Read the ReplicaSet // * Read the Pods -// * Set a Label on the ReplicaSet with the Pod count -func (a *ReplicaSetReconciler) Reconcile(ctx context.Context, req controllers.Request) (controllers.Result, error) { +// * Set a Label on the ReplicaSet with the Pod count. +func (a *ReplicaSetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // Read the ReplicaSet rs := &appsv1.ReplicaSet{} err := a.Get(ctx, req.NamespacedName, rs) if err != nil { - return controllers.Result{}, err + return ctrl.Result{}, err } // List the Pods matching the PodTemplate Labels pods := &corev1.PodList{} err = a.List(ctx, pods, client.InNamespace(req.Namespace), client.MatchingLabels(rs.Spec.Template.Labels)) if err != nil { - return controllers.Result{}, err + return ctrl.Result{}, err } // Update the ReplicaSet rs.Labels["pod-count"] = fmt.Sprintf("%v", len(pods.Items)) err = a.Update(context.TODO(), rs) if err != nil { - return controllers.Result{}, err + return ctrl.Result{}, err } - return controllers.Result{}, nil + return ctrl.Result{}, nil } diff --git a/hack/ensure-golangci-lint.sh b/hack/ensure-golangci-lint.sh new file mode 100755 index 0000000000..9e9ef03167 --- /dev/null +++ b/hack/ensure-golangci-lint.sh @@ -0,0 +1,422 @@ +#!/usr/bin/env bash + +# Copyright 2021 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# NOTE: This script is copied from from https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh. + +set -e + +usage() { + this=$1 + cat </dev/null +} +echoerr() { + echo "$@" 1>&2 +} +log_prefix() { + echo "$0" +} +_logp=6 +log_set_priority() { + _logp="$1" +} +log_priority() { + if test -z "$1"; then + echo "$_logp" + return + fi + [ "$1" -le "$_logp" ] +} +log_tag() { + case $1 in + 0) echo "emerg" ;; + 1) echo "alert" ;; + 2) echo "crit" ;; + 3) echo "err" ;; + 4) echo "warning" ;; + 5) echo "notice" ;; + 6) echo "info" ;; + 7) echo "debug" ;; + *) echo "$1" ;; + esac +} +log_debug() { + log_priority 7 || return 0 + echoerr "$(log_prefix)" "$(log_tag 7)" "$@" +} +log_info() { + log_priority 6 || return 0 + echoerr "$(log_prefix)" "$(log_tag 6)" "$@" +} +log_err() { + log_priority 3 || return 0 + echoerr "$(log_prefix)" "$(log_tag 3)" "$@" +} +log_crit() { + log_priority 2 || return 0 + echoerr "$(log_prefix)" "$(log_tag 2)" "$@" +} +uname_os() { + os=$(uname -s | tr '[:upper:]' '[:lower:]') + case "$os" in + cygwin_nt*) os="windows" ;; + mingw*) os="windows" ;; + msys_nt*) os="windows" ;; + esac + echo "$os" +} +uname_arch() { + arch=$(uname -m) + case $arch in + x86_64) arch="amd64" ;; + x86) arch="386" ;; + i686) arch="386" ;; + i386) arch="386" ;; + aarch64) arch="arm64" ;; + armv5*) arch="armv5" ;; + armv6*) arch="armv6" ;; + armv7*) arch="armv7" ;; + esac + echo ${arch} +} +uname_os_check() { + os=$(uname_os) + case "$os" in + darwin) return 0 ;; + dragonfly) return 0 ;; + freebsd) return 0 ;; + linux) return 0 ;; + android) return 0 ;; + nacl) return 0 ;; + netbsd) return 0 ;; + openbsd) return 0 ;; + plan9) return 0 ;; + solaris) return 0 ;; + windows) return 0 ;; + esac + log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib" + return 1 +} +uname_arch_check() { + arch=$(uname_arch) + case "$arch" in + 386) return 0 ;; + amd64) return 0 ;; + arm64) return 0 ;; + armv5) return 0 ;; + armv6) return 0 ;; + armv7) return 0 ;; + ppc64) return 0 ;; + ppc64le) return 0 ;; + mips) return 0 ;; + mipsle) return 0 ;; + mips64) return 0 ;; + mips64le) return 0 ;; + s390x) return 0 ;; + amd64p32) return 0 ;; + esac + log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib" + return 1 +} +untar() { + tarball=$1 + case "${tarball}" in + *.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}" ;; + *.tar) tar --no-same-owner -xf "${tarball}" ;; + *.zip) unzip "${tarball}" ;; + *) + log_err "untar unknown archive format for ${tarball}" + return 1 + ;; + esac +} +http_download_curl() { + local_file=$1 + source_url=$2 + header=$3 + if [ -z "$header" ]; then + code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url") + else + code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url") + fi + if [ "$code" != "200" ]; then + log_debug "http_download_curl received HTTP status $code" + return 1 + fi + return 0 +} +http_download_wget() { + local_file=$1 + source_url=$2 + header=$3 + if [ -z "$header" ]; then + wget -q -O "$local_file" "$source_url" + else + wget -q --header "$header" -O "$local_file" "$source_url" + fi +} +http_download() { + log_debug "http_download $2" + if is_command curl; then + http_download_curl "$@" + return + elif is_command wget; then + http_download_wget "$@" + return + fi + log_crit "http_download unable to find wget or curl" + return 1 +} +http_copy() { + tmp=$(mktemp) + http_download "${tmp}" "$1" "$2" || return 1 + body=$(cat "$tmp") + rm -f "${tmp}" + echo "$body" +} +github_release() { + owner_repo=$1 + version=$2 + test -z "$version" && version="latest" + giturl="https://github.com/${owner_repo}/releases/${version}" + json=$(http_copy "$giturl" "Accept:application/json") + test -z "$json" && return 1 + version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') + test -z "$version" && return 1 + echo "$version" +} +hash_sha256() { + TARGET=${1:-/dev/stdin} + if is_command gsha256sum; then + hash=$(gsha256sum "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command sha256sum; then + hash=$(sha256sum "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command shasum; then + hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1 + echo "$hash" | cut -d ' ' -f 1 + elif is_command openssl; then + hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1 + echo "$hash" | cut -d ' ' -f a + else + log_crit "hash_sha256 unable to find command to compute sha-256 hash" + return 1 + fi +} +hash_sha256_verify() { + TARGET=$1 + checksums=$2 + if [ -z "$checksums" ]; then + log_err "hash_sha256_verify checksum file not specified in arg2" + return 1 + fi + BASENAME=${TARGET##*/} + want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1) + if [ -z "$want" ]; then + log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'" + return 1 + fi + got=$(hash_sha256 "$TARGET") + if [ "$want" != "$got" ]; then + log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got" + return 1 + fi +} +cat /dev/null <}, &handler.EnqueueRequestForOwner{OwnerType: apiType, IsController: true}) +// Watches(&source.Kind{Type: }, &handler.EnqueueRequestForOwner{OwnerType: apiType, IsController: true}). func (blder *Builder) Owns(object client.Object, opts ...OwnsOption) *Builder { input := OwnsInput{object: object} for _, opt := range opts { diff --git a/pkg/builder/controller_test.go b/pkg/builder/controller_test.go index 683d87925b..ca486fbacd 100644 --- a/pkg/builder/controller_test.go +++ b/pkg/builder/controller_test.go @@ -362,7 +362,7 @@ var _ = Describe("application", func() { allPrct := predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { defer GinkgoRecover() - //check that it was called for all registered kinds + // check that it was called for all registered kinds Expect(e.Object).Should(Or( BeAssignableToTypeOf(&appsv1.Deployment{}), BeAssignableToTypeOf(&appsv1.ReplicaSet{}), @@ -499,7 +499,7 @@ func (c *nonTypedOnlyCache) GetInformerForKind(ctx context.Context, gvk schema.G } // TODO(directxman12): this function has too many arguments, and the whole -// "nameSuffix" think is a bit of a hack It should be cleaned up significantly by someone with a bit of time +// "nameSuffix" think is a bit of a hack It should be cleaned up significantly by someone with a bit of time. func doReconcileTest(ctx context.Context, nameSuffix string, blder *Builder, mgr manager.Manager, complete bool) { deployName := "deploy-name-" + nameSuffix rsName := "rs-name-" + nameSuffix @@ -594,7 +594,6 @@ func doReconcileTest(ctx context.Context, nameSuffix string, blder *Builder, mgr By("Waiting for the ReplicaSet Reconcile") Eventually(ch).Should(Receive(Equal(reconcile.Request{ NamespacedName: types.NamespacedName{Namespace: "default", Name: deployName}}))) - } var _ runtime.Object = &fakeType{} diff --git a/pkg/builder/example_test.go b/pkg/builder/example_test.go index 342bd13235..955c46b562 100644 --- a/pkg/builder/example_test.go +++ b/pkg/builder/example_test.go @@ -130,7 +130,7 @@ type ReplicaSetReconciler struct { // // * Read the ReplicaSet // * Read the Pods -// * Set a Label on the ReplicaSet with the Pod count +// * Set a Label on the ReplicaSet with the Pod count. func (a *ReplicaSetReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { // Read the ReplicaSet rs := &appsv1.ReplicaSet{} diff --git a/pkg/builder/webhook.go b/pkg/builder/webhook.go index 7ba398762a..d24877d303 100644 --- a/pkg/builder/webhook.go +++ b/pkg/builder/webhook.go @@ -38,7 +38,7 @@ type WebhookBuilder struct { config *rest.Config } -// WebhookManagedBy allows inform its manager.Manager +// WebhookManagedBy allows inform its manager.Manager. func WebhookManagedBy(m manager.Manager) *WebhookBuilder { return &WebhookBuilder{mgr: m} } @@ -86,7 +86,7 @@ func (blder *WebhookBuilder) registerWebhooks() error { return nil } -// registerDefaultingWebhook registers a defaulting webhook if th +// registerDefaultingWebhook registers a defaulting webhook if th. func (blder *WebhookBuilder) registerDefaultingWebhook() { defaulter, isDefaulter := blder.apiType.(admission.Defaulter) if !isDefaulter { @@ -157,11 +157,11 @@ func (blder *WebhookBuilder) isAlreadyHandled(path string) bool { } func generateMutatePath(gvk schema.GroupVersionKind) string { - return "/mutate-" + strings.Replace(gvk.Group, ".", "-", -1) + "-" + + return "/mutate-" + strings.ReplaceAll(gvk.Group, ".", "-") + "-" + gvk.Version + "-" + strings.ToLower(gvk.Kind) } func generateValidatePath(gvk schema.GroupVersionKind) string { - return "/validate-" + strings.Replace(gvk.Group, ".", "-", -1) + "-" + + return "/validate-" + strings.ReplaceAll(gvk.Group, ".", "-") + "-" + gvk.Version + "-" + strings.ToLower(gvk.Kind) } diff --git a/pkg/builder/webhook_test.go b/pkg/builder/webhook_test.go index c73210c73c..53fc95468d 100644 --- a/pkg/builder/webhook_test.go +++ b/pkg/builder/webhook_test.go @@ -114,7 +114,7 @@ func runTests(admissionReviewVersion string) { By("sending a request to a mutating webhook path") path := generateMutatePath(testDefaulterGVK) req := httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -128,7 +128,7 @@ func runTests(admissionReviewVersion string) { _, err = reader.Seek(0, 0) ExpectWithOffset(1, err).NotTo(HaveOccurred()) req = httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w = httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusNotFound)) @@ -190,7 +190,7 @@ func runTests(admissionReviewVersion string) { By("sending a request to a mutating webhook path that doesn't exist") path := generateMutatePath(testValidatorGVK) req := httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusNotFound)) @@ -200,7 +200,7 @@ func runTests(admissionReviewVersion string) { _, err = reader.Seek(0, 0) ExpectWithOffset(1, err).NotTo(HaveOccurred()) req = httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w = httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -263,7 +263,7 @@ func runTests(admissionReviewVersion string) { By("sending a request to a mutating webhook path") path := generateMutatePath(testDefaultValidatorGVK) req := httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -277,7 +277,7 @@ func runTests(admissionReviewVersion string) { _, err = reader.Seek(0, 0) ExpectWithOffset(1, err).NotTo(HaveOccurred()) req = httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w = httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -341,7 +341,7 @@ func runTests(admissionReviewVersion string) { By("sending a request to a validating webhook path to check for failed delete") path := generateValidatePath(testValidatorGVK) req := httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -375,7 +375,7 @@ func runTests(admissionReviewVersion string) { By("sending a request to a validating webhook path with correct request") path = generateValidatePath(testValidatorGVK) req = httptest.NewRequest("POST", "http://svc-name.svc-ns.svc"+path, reader) - req.Header.Add(http.CanonicalHeaderKey("Content-Type"), "application/json") + req.Header.Add("Content-Type", "application/json") w = httptest.NewRecorder() svr.WebhookMux.ServeHTTP(w, req) ExpectWithOffset(1, w.Code).To(Equal(http.StatusOK)) @@ -385,7 +385,7 @@ func runTests(admissionReviewVersion string) { }) } -// TestDefaulter +// TestDefaulter. var _ runtime.Object = &TestDefaulter{} type TestDefaulter struct { @@ -420,7 +420,7 @@ func (d *TestDefaulter) Default() { } } -// TestValidator +// TestValidator. var _ runtime.Object = &TestValidator{} type TestValidator struct { @@ -477,7 +477,7 @@ func (v *TestValidator) ValidateDelete() error { return nil } -// TestDefaultValidator +// TestDefaultValidator. var _ runtime.Object = &TestDefaultValidator{} type TestDefaultValidator struct { diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index dee523fe23..6862fd62bd 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -69,7 +69,7 @@ type Informers interface { client.FieldIndexer } -// Informer - informer allows you interact with the underlying informer +// Informer - informer allows you interact with the underlying informer. type Informer interface { // AddEventHandler adds an event handler to the shared informer using the shared informer's resync // period. Events to a single handler are delivered sequentially, but there is no coordination @@ -82,14 +82,14 @@ type Informer interface { // AddIndexers adds more indexers to this store. If you call this after you already have data // in the store, the results are undefined. AddIndexers(indexers toolscache.Indexers) error - //HasSynced return true if the informers underlying store has synced + // HasSynced return true if the informers underlying store has synced. HasSynced() bool } -// SelectorsByObject associate a client.Object's GVK to a field/label selector +// SelectorsByObject associate a client.Object's GVK to a field/label selector. type SelectorsByObject map[client.Object]internal.Selector -// Options are the optional arguments for creating a new InformersMap object +// Options are the optional arguments for creating a new InformersMap object. type Options struct { // Scheme is the scheme to use for mapping objects to GroupVersionKinds Scheme *runtime.Scheme diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 35cfd149de..49e8e97cfe 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -24,9 +24,9 @@ import ( . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" - kcorev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" @@ -46,20 +46,20 @@ const testNamespaceThree = "test-namespace-3" // TODO(community): Pull these helper functions into testenv. // Restart policy is included to allow indexing on that field. -func createPodWithLabels(name, namespace string, restartPolicy kcorev1.RestartPolicy, labels map[string]string) client.Object { +func createPodWithLabels(name, namespace string, restartPolicy corev1.RestartPolicy, labels map[string]string) client.Object { three := int64(3) if labels == nil { labels = map[string]string{} } labels["test-label"] = name - pod := &kcorev1.Pod{ - ObjectMeta: kmetav1.ObjectMeta{ + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, Labels: labels, }, - Spec: kcorev1.PodSpec{ - Containers: []kcorev1.Container{{Name: "nginx", Image: "nginx"}}, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{{Name: "nginx", Image: "nginx"}}, RestartPolicy: restartPolicy, ActiveDeadlineSeconds: &three, }, @@ -71,7 +71,7 @@ func createPodWithLabels(name, namespace string, restartPolicy kcorev1.RestartPo return pod } -func createPod(name, namespace string, restartPolicy kcorev1.RestartPolicy) client.Object { +func createPod(name, namespace string, restartPolicy corev1.RestartPolicy) client.Object { return createPodWithLabels(name, namespace, restartPolicy, nil) } @@ -89,7 +89,6 @@ var _ = Describe("Multi-Namespace Informer Cache", func() { CacheTest(cache.MultiNamespacedCacheBuilder([]string{testNamespaceOne, testNamespaceTwo, "default"})) }) -// nolint: gocyclo func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error)) { Describe("Cache test", func() { var ( @@ -120,12 +119,12 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca err = ensureNamespace(testNamespaceThree, cl) Expect(err).NotTo(HaveOccurred()) // Includes restart policy since these objects are indexed on this field. - knownPod1 = createPod("test-pod-1", testNamespaceOne, kcorev1.RestartPolicyNever) - knownPod2 = createPod("test-pod-2", testNamespaceTwo, kcorev1.RestartPolicyAlways) - knownPod3 = createPodWithLabels("test-pod-3", testNamespaceTwo, kcorev1.RestartPolicyOnFailure, map[string]string{"common-label": "common"}) - knownPod4 = createPodWithLabels("test-pod-4", testNamespaceThree, kcorev1.RestartPolicyNever, map[string]string{"common-label": "common"}) - knownPod5 = createPod("test-pod-5", testNamespaceOne, kcorev1.RestartPolicyNever) - knownPod6 = createPod("test-pod-6", testNamespaceTwo, kcorev1.RestartPolicyAlways) + knownPod1 = createPod("test-pod-1", testNamespaceOne, corev1.RestartPolicyNever) + knownPod2 = createPod("test-pod-2", testNamespaceTwo, corev1.RestartPolicyAlways) + knownPod3 = createPodWithLabels("test-pod-3", testNamespaceTwo, corev1.RestartPolicyOnFailure, map[string]string{"common-label": "common"}) + knownPod4 = createPodWithLabels("test-pod-4", testNamespaceThree, corev1.RestartPolicyNever, map[string]string{"common-label": "common"}) + knownPod5 = createPod("test-pod-5", testNamespaceOne, corev1.RestartPolicyNever) + knownPod6 = createPod("test-pod-6", testNamespaceTwo, corev1.RestartPolicyAlways) podGVK := schema.GroupVersionKind{ Kind: "Pod", @@ -165,18 +164,18 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Describe("as a Reader", func() { Context("with structured objects", func() { - It("should be able to list objects that haven't been watched previously", func() { By("listing all services in the cluster") - listObj := &kcorev1.ServiceList{} + listObj := &corev1.ServiceList{} Expect(informerCache.List(context.Background(), listObj)).To(Succeed()) By("verifying that the returned list contains the Kubernetes service") // NB: kubernetes default service is automatically created in testenv. Expect(listObj.Items).NotTo(BeEmpty()) hasKubeService := false - for _, svc := range listObj.Items { - if isKubeService(&svc) { + for i := range listObj.Items { + svc := &listObj.Items[i] + if isKubeService(svc) { hasKubeService = true break } @@ -186,7 +185,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should be able to get objects that haven't been watched previously", func() { By("getting the Kubernetes service") - svc := &kcorev1.Service{} + svc := &corev1.Service{} svcKey := client.ObjectKey{Namespace: "default", Name: "kubernetes"} Expect(informerCache.Get(context.Background(), svcKey, svc)).To(Succeed()) @@ -198,7 +197,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should support filtering by labels in a single namespace", func() { By("listing pods with a particular label") // NB: each pod has a "test-label": - out := kcorev1.PodList{} + out := corev1.PodList{} Expect(informerCache.List(context.Background(), &out, client.InNamespace(testNamespaceTwo), client.MatchingLabels(map[string]string{"test-label": "test-pod-2"}))).To(Succeed()) @@ -212,12 +211,12 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should support filtering by labels from multiple namespaces", func() { By("creating another pod with the same label but different namespace") - anotherPod := createPod("test-pod-2", testNamespaceOne, kcorev1.RestartPolicyAlways) + anotherPod := createPod("test-pod-2", testNamespaceOne, corev1.RestartPolicyAlways) defer deletePod(anotherPod) By("listing pods with a particular label") // NB: each pod has a "test-label": - out := kcorev1.PodList{} + out := corev1.PodList{} labels := map[string]string{"test-label": "test-pod-2"} Expect(informerCache.List(context.Background(), &out, client.MatchingLabels(labels))).To(Succeed()) @@ -231,20 +230,20 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should be able to list objects with GVK populated", func() { By("listing pods") - out := &kcorev1.PodList{} + out := &corev1.PodList{} Expect(informerCache.List(context.Background(), out)).To(Succeed()) By("verifying that the returned pods have GVK populated") Expect(out.Items).NotTo(BeEmpty()) Expect(out.Items).Should(SatisfyAny(HaveLen(5), HaveLen(6))) for _, p := range out.Items { - Expect(p.GroupVersionKind()).To(Equal(kcorev1.SchemeGroupVersion.WithKind("Pod"))) + Expect(p.GroupVersionKind()).To(Equal(corev1.SchemeGroupVersion.WithKind("Pod"))) } }) It("should be able to list objects by namespace", func() { By("listing pods in test-namespace-1") - listObj := &kcorev1.PodList{} + listObj := &corev1.PodList{} Expect(informerCache.List(context.Background(), listObj, client.InNamespace(testNamespaceOne))).To(Succeed()) @@ -258,7 +257,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should deep copy the object unless told otherwise", func() { By("retrieving a specific pod from the cache") - out := &kcorev1.Pod{} + out := &corev1.Pod{} podKey := client.ObjectKey{Name: "test-pod-2", Namespace: testNamespaceTwo} Expect(informerCache.Get(context.Background(), podKey, out)).To(Succeed()) @@ -274,18 +273,18 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should return an error if the object is not found", func() { By("getting a service that does not exists") - svc := &kcorev1.Service{} + svc := &corev1.Service{} svcKey := client.ObjectKey{Namespace: testNamespaceOne, Name: "unknown"} By("verifying that an error is returned") err := informerCache.Get(context.Background(), svcKey, svc) Expect(err).To(HaveOccurred()) - Expect(errors.IsNotFound(err)).To(BeTrue()) + Expect(apierrors.IsNotFound(err)).To(BeTrue()) }) It("should return an error if getting object in unwatched namespace", func() { By("getting a service that does not exists") - svc := &kcorev1.Service{} + svc := &corev1.Service{} svcKey := client.ObjectKey{Namespace: "unknown", Name: "unknown"} By("verifying that an error is returned") @@ -298,18 +297,18 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca informerCacheCancel() By("listing pods in test-namespace-1 with a cancelled context") - listObj := &kcorev1.PodList{} + listObj := &corev1.PodList{} err := informerCache.List(informerCacheCtx, listObj, client.InNamespace(testNamespaceOne)) By("verifying that an error is returned") Expect(err).To(HaveOccurred()) - Expect(errors.IsTimeout(err)).To(BeTrue()) + Expect(apierrors.IsTimeout(err)).To(BeTrue()) }) It("should set the Limit option and limit number of objects to Limit when List is called", func() { opts := &client.ListOptions{Limit: int64(3)} By("verifying that only Limit (3) number of objects are retrieved from the cache") - listObj := &kcorev1.PodList{} + listObj := &corev1.PodList{} Expect(informerCache.List(context.Background(), listObj, opts)).To(Succeed()) Expect(listObj.Items).Should(HaveLen(3)) }) @@ -331,8 +330,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca // NB: kubernetes default service is automatically created in testenv. Expect(listObj.Items).NotTo(BeEmpty()) hasKubeService := false - for _, svc := range listObj.Items { - if isKubeService(&svc) { + for i := range listObj.Items { + svc := &listObj.Items[i] + if isKubeService(svc) { hasKubeService = true break } @@ -378,7 +378,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should support filtering by labels from multiple namespaces", func() { By("creating another pod with the same label but different namespace") - anotherPod := createPod("test-pod-2", testNamespaceOne, kcorev1.RestartPolicyAlways) + anotherPod := createPod("test-pod-2", testNamespaceOne, corev1.RestartPolicyAlways) defer deletePod(anotherPod) By("listing pods with a particular label") @@ -399,7 +399,6 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca for _, actual := range out.Items { Expect(actual.GetLabels()["test-label"]).To(Equal("test-pod-2")) } - }) It("should be able to list objects by namespace", func() { @@ -515,11 +514,11 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca By("verifying that an error is returned") err := informerCache.Get(context.Background(), svcKey, svc) Expect(err).To(HaveOccurred()) - Expect(errors.IsNotFound(err)).To(BeTrue()) + Expect(apierrors.IsNotFound(err)).To(BeTrue()) }) It("should return an error if getting object in unwatched namespace", func() { By("getting a service that does not exists") - svc := &kcorev1.Service{} + svc := &corev1.Service{} svcKey := client.ObjectKey{Namespace: "unknown", Name: "unknown"} By("verifying that an error is returned") @@ -540,7 +539,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(m.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse()) By("should be able to fetch cluster scoped resource") - node := &kcorev1.Node{} + node := &corev1.Node{} By("verifying that getting the node works with an empty namespace") key1 := client.ObjectKey{Namespace: "", Name: testNodeOne} @@ -563,7 +562,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Context("with metadata-only objects", func() { It("should be able to list objects that haven't been watched previously", func() { By("listing all services in the cluster") - listObj := &kmetav1.PartialObjectMetadataList{} + listObj := &metav1.PartialObjectMetadataList{} listObj.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -576,8 +575,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca // NB: kubernetes default service is automatically created in testenv. Expect(listObj.Items).NotTo(BeEmpty()) hasKubeService := false - for _, svc := range listObj.Items { - if isKubeService(&svc) { + for i := range listObj.Items { + svc := &listObj.Items[i] + if isKubeService(svc) { hasKubeService = true break } @@ -586,7 +586,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca }) It("should be able to get objects that haven't been watched previously", func() { By("getting the Kubernetes service") - svc := &kmetav1.PartialObjectMetadata{} + svc := &metav1.PartialObjectMetadata{} svc.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -603,7 +603,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should support filtering by labels in a single namespace", func() { By("listing pods with a particular label") // NB: each pod has a "test-label": - out := kmetav1.PartialObjectMetadataList{} + out := metav1.PartialObjectMetadataList{} out.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -623,12 +623,12 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should support filtering by labels from multiple namespaces", func() { By("creating another pod with the same label but different namespace") - anotherPod := createPod("test-pod-2", testNamespaceOne, kcorev1.RestartPolicyAlways) + anotherPod := createPod("test-pod-2", testNamespaceOne, corev1.RestartPolicyAlways) defer deletePod(anotherPod) By("listing pods with a particular label") // NB: each pod has a "test-label": - out := kmetav1.PartialObjectMetadataList{} + out := metav1.PartialObjectMetadataList{} out.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -644,12 +644,11 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca for _, actual := range out.Items { Expect(actual.GetLabels()["test-label"]).To(Equal("test-pod-2")) } - }) It("should be able to list objects by namespace", func() { By("listing pods in test-namespace-1") - listObj := &kmetav1.PartialObjectMetadataList{} + listObj := &metav1.PartialObjectMetadataList{} listObj.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -679,7 +678,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(namespacedCache.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse()) By("listing pods in all namespaces") - out := &kmetav1.PartialObjectMetadataList{} + out := &metav1.PartialObjectMetadataList{} out.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -694,7 +693,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(item.Namespace).To(Equal(testNamespaceOne)) } By("listing all nodes - should still be able to list a cluster-scoped resource") - nodeList := &kmetav1.PartialObjectMetadataList{} + nodeList := &metav1.PartialObjectMetadataList{} nodeList.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -706,7 +705,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(nodeList.Items).NotTo(BeEmpty()) By("getting a node - should still be able to get a cluster-scoped resource") - node := &kmetav1.PartialObjectMetadata{} + node := &metav1.PartialObjectMetadata{} node.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -724,14 +723,14 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should deep copy the object unless told otherwise", func() { By("retrieving a specific pod from the cache") - out := &kmetav1.PartialObjectMetadata{} + out := &metav1.PartialObjectMetadata{} out.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", Kind: "Pod", }) - uKnownPod2 := &kmetav1.PartialObjectMetadata{} - knownPod2.(*kcorev1.Pod).ObjectMeta.DeepCopyInto(&uKnownPod2.ObjectMeta) + uKnownPod2 := &metav1.PartialObjectMetadata{} + knownPod2.(*corev1.Pod).ObjectMeta.DeepCopyInto(&uKnownPod2.ObjectMeta) uKnownPod2.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -753,7 +752,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca It("should return an error if the object is not found", func() { By("getting a service that does not exists") - svc := &kmetav1.PartialObjectMetadata{} + svc := &metav1.PartialObjectMetadata{} svc.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -764,11 +763,11 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca By("verifying that an error is returned") err := informerCache.Get(context.Background(), svcKey, svc) Expect(err).To(HaveOccurred()) - Expect(errors.IsNotFound(err)).To(BeTrue()) + Expect(apierrors.IsNotFound(err)).To(BeTrue()) }) It("should return an error if getting object in unwatched namespace", func() { By("getting a service that does not exists") - svc := &kcorev1.Service{} + svc := &corev1.Service{} svcKey := client.ObjectKey{Namespace: "unknown", Name: "unknown"} By("verifying that an error is returned") @@ -786,7 +785,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca builder := cache.BuilderWithOptions( cache.Options{ SelectorsByObject: cache.SelectorsByObject{ - &kcorev1.Pod{}: { + &corev1.Pod{}: { Label: labels.Set(tc.labelSelectors).AsSelector(), Field: fields.Set(tc.fieldSelectors).AsSelector(), }, @@ -804,9 +803,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(informer.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse()) By("Checking with structured") - obtainedStructuredPodList := kcorev1.PodList{} + obtainedStructuredPodList := corev1.PodList{} Expect(informer.List(context.Background(), &obtainedStructuredPodList)).To(Succeed()) - Expect(obtainedStructuredPodList.Items).Should(WithTransform(func(pods []kcorev1.Pod) []string { + Expect(obtainedStructuredPodList.Items).Should(WithTransform(func(pods []corev1.Pod) []string { obtainedPodNames := []string{} for _, pod := range pods { obtainedPodNames = append(obtainedPodNames, pod.Name) @@ -832,7 +831,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca }, ConsistOf(tc.expectedPods))) By("Checking with metadata") - obtainedMetadataPodList := kmetav1.PartialObjectMetadataList{} + obtainedMetadataPodList := metav1.PartialObjectMetadataList{} obtainedMetadataPodList.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", @@ -840,7 +839,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca }) err = informer.List(context.Background(), &obtainedMetadataPodList) Expect(err).To(Succeed()) - Expect(obtainedMetadataPodList.Items).Should(WithTransform(func(pods []kmetav1.PartialObjectMetadata) []string { + Expect(obtainedMetadataPodList.Items).Should(WithTransform(func(pods []metav1.PartialObjectMetadata) []string { obtainedPodNames := []string{} for _, pod := range pods { obtainedPodNames = append(obtainedPodNames, pod.Name) @@ -888,13 +887,13 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Context("with structured objects", func() { It("should be able to get informer for the object", func(done Done) { By("getting a shared index informer for a pod") - pod := &kcorev1.Pod{ - ObjectMeta: kmetav1.ObjectMeta{ + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ Name: "informer-obj", Namespace: "default", }, - Spec: kcorev1.PodSpec{ - Containers: []kcorev1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "nginx", Image: "nginx", @@ -942,13 +941,13 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca By("adding an object") cl, err := client.New(cfg, client.Options{}) Expect(err).NotTo(HaveOccurred()) - pod := &kcorev1.Pod{ - ObjectMeta: kmetav1.ObjectMeta{ + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ Name: "informer-gvk", Namespace: "default", }, - Spec: kcorev1.PodSpec{ - Containers: []kcorev1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "nginx", Image: "nginx", @@ -969,9 +968,9 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(err).NotTo(HaveOccurred()) By("indexing the restartPolicy field of the Pod object before starting") - pod := &kcorev1.Pod{} + pod := &corev1.Pod{} indexFunc := func(obj client.Object) []string { - return []string{string(obj.(*kcorev1.Pod).Spec.RestartPolicy)} + return []string{string(obj.(*corev1.Pod).Spec.RestartPolicy)} } Expect(informer.IndexField(context.TODO(), pod, "spec.restartPolicy", indexFunc)).To(Succeed()) @@ -983,7 +982,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(informer.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse()) By("listing Pods with restartPolicyOnFailure") - listObj := &kcorev1.PodList{} + listObj := &corev1.PodList{} Expect(informer.List(context.Background(), listObj, client.MatchingFields{"spec.restartPolicy": "OnFailure"})).To(Succeed()) By("verifying that the returned pods have correct restart policy") @@ -998,13 +997,13 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca informerCacheCancel() By("getting a shared index informer for a pod with a cancelled context") - pod := &kcorev1.Pod{ - ObjectMeta: kmetav1.ObjectMeta{ + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ Name: "informer-obj", Namespace: "default", }, - Spec: kcorev1.PodSpec{ - Containers: []kcorev1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "nginx", Image: "nginx", @@ -1015,7 +1014,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca sii, err := informerCache.GetInformer(informerCacheCtx, pod) Expect(err).To(HaveOccurred()) Expect(sii).To(BeNil()) - Expect(errors.IsTimeout(err)).To(BeTrue()) + Expect(apierrors.IsTimeout(err)).To(BeTrue()) }) It("should allow getting an informer by group/version/kind to be cancelled", func() { @@ -1027,7 +1026,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca sii, err := informerCache.GetInformerForKind(informerCacheCtx, gvk) Expect(err).To(HaveOccurred()) Expect(sii).To(BeNil()) - Expect(errors.IsTimeout(err)).To(BeTrue()) + Expect(apierrors.IsTimeout(err)).To(BeTrue()) }) }) Context("with unstructured objects", func() { @@ -1142,20 +1141,20 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca sii, err := informerCache.GetInformer(informerCacheCtx, pod) Expect(err).To(HaveOccurred()) Expect(sii).To(BeNil()) - Expect(errors.IsTimeout(err)).To(BeTrue()) + Expect(apierrors.IsTimeout(err)).To(BeTrue()) }) }) Context("with metadata-only objects", func() { It("should be able to get informer for the object", func(done Done) { By("getting a shared index informer for a pod") - pod := &kcorev1.Pod{ - ObjectMeta: kmetav1.ObjectMeta{ + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ Name: "informer-obj", Namespace: "default", }, - Spec: kcorev1.PodSpec{ - Containers: []kcorev1.Container{ + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ { Name: "nginx", Image: "nginx", @@ -1164,7 +1163,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca }, } - podMeta := &kmetav1.PartialObjectMetadata{} + podMeta := &metav1.PartialObjectMetadata{} pod.ObjectMeta.DeepCopyInto(&podMeta.ObjectMeta) podMeta.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", @@ -1203,14 +1202,14 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(err).NotTo(HaveOccurred()) By("indexing the restartPolicy field of the Pod object before starting") - pod := &kmetav1.PartialObjectMetadata{} + pod := &metav1.PartialObjectMetadata{} pod.SetGroupVersionKind(schema.GroupVersionKind{ Group: "", Version: "v1", Kind: "Pod", }) indexFunc := func(obj client.Object) []string { - metadata := obj.(*kmetav1.PartialObjectMetadata) + metadata := obj.(*metav1.PartialObjectMetadata) return []string{metadata.Labels["test-label"]} } Expect(informer.IndexField(context.TODO(), pod, "metadata.labels.test-label", indexFunc)).To(Succeed()) @@ -1223,7 +1222,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca Expect(informer.WaitForCacheSync(informerCacheCtx)).NotTo(BeFalse()) By("listing Pods with restartPolicyOnFailure") - listObj := &kmetav1.PartialObjectMetadataList{} + listObj := &metav1.PartialObjectMetadataList{} gvk := schema.GroupVersionKind{ Group: "", Version: "v1", @@ -1257,7 +1256,7 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca cancel() By("getting a shared index informer for a pod with a cancelled context") - pod := &kmetav1.PartialObjectMetadata{} + pod := &metav1.PartialObjectMetadata{} pod.SetName("informer-obj2") pod.SetNamespace("default") pod.SetGroupVersionKind(schema.GroupVersionKind{ @@ -1268,50 +1267,50 @@ func CacheTest(createCacheFunc func(config *rest.Config, opts cache.Options) (ca sii, err := informerCache.GetInformer(ctx, pod) Expect(err).To(HaveOccurred()) Expect(sii).To(BeNil()) - Expect(errors.IsTimeout(err)).To(BeTrue()) + Expect(apierrors.IsTimeout(err)).To(BeTrue()) }) }) }) }) } -// ensureNamespace installs namespace of a given name if not exists +// ensureNamespace installs namespace of a given name if not exists. func ensureNamespace(namespace string, client client.Client) error { - ns := kcorev1.Namespace{ - ObjectMeta: kmetav1.ObjectMeta{ + ns := corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ Name: namespace, }, - TypeMeta: kmetav1.TypeMeta{ + TypeMeta: metav1.TypeMeta{ Kind: "Namespace", APIVersion: "v1", }, } err := client.Create(context.TODO(), &ns) - if errors.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { return nil } return err } func ensureNode(name string, client client.Client) error { - node := kcorev1.Node{ - ObjectMeta: kmetav1.ObjectMeta{ + node := corev1.Node{ + ObjectMeta: metav1.ObjectMeta{ Name: name, }, - TypeMeta: kmetav1.TypeMeta{ + TypeMeta: metav1.TypeMeta{ Kind: "Node", APIVersion: "v1", }, } err := client.Create(context.TODO(), &node) - if errors.IsAlreadyExists(err) { + if apierrors.IsAlreadyExists(err) { return nil } return err } //nolint:interfacer -func isKubeService(svc kmetav1.Object) bool { +func isKubeService(svc metav1.Object) bool { // grumble grumble linters grumble grumble return svc.GetNamespace() == "default" && svc.GetName() == "kubernetes" } diff --git a/pkg/cache/informer_cache.go b/pkg/cache/informer_cache.go index 8ec3b921d9..90647c8e33 100644 --- a/pkg/cache/informer_cache.go +++ b/pkg/cache/informer_cache.go @@ -50,7 +50,7 @@ type informerCache struct { *internal.InformersMap } -// Get implements Reader +// Get implements Reader. func (ip *informerCache) Get(ctx context.Context, key client.ObjectKey, out client.Object) error { gvk, err := apiutil.GVKForObject(out, ip.Scheme) if err != nil { @@ -68,9 +68,8 @@ func (ip *informerCache) Get(ctx context.Context, key client.ObjectKey, out clie return cache.Reader.Get(ctx, key, out) } -// List implements Reader +// List implements Reader. func (ip *informerCache) List(ctx context.Context, out client.ObjectList, opts ...client.ListOption) error { - gvk, cacheTypeObj, err := ip.objectTypeForListObject(out) if err != nil { return err @@ -130,7 +129,7 @@ func (ip *informerCache) objectTypeForListObject(list client.ObjectList) (*schem return &gvk, cacheTypeObj, nil } -// GetInformerForKind returns the informer for the GroupVersionKind +// GetInformerForKind returns the informer for the GroupVersionKind. func (ip *informerCache) GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind) (Informer, error) { // Map the gvk to an object obj, err := ip.Scheme.New(gvk) @@ -145,7 +144,7 @@ func (ip *informerCache) GetInformerForKind(ctx context.Context, gvk schema.Grou return i.Informer, err } -// GetInformer returns the informer for the obj +// GetInformer returns the informer for the obj. func (ip *informerCache) GetInformer(ctx context.Context, obj client.Object) (Informer, error) { gvk, err := apiutil.GVKForObject(obj, ip.Scheme) if err != nil { @@ -160,7 +159,7 @@ func (ip *informerCache) GetInformer(ctx context.Context, obj client.Object) (In } // NeedLeaderElection implements the LeaderElectionRunnable interface -// to indicate that this can be started without requiring the leader lock +// to indicate that this can be started without requiring the leader lock. func (ip *informerCache) NeedLeaderElection() bool { return false } diff --git a/pkg/cache/informertest/fake_cache.go b/pkg/cache/informertest/fake_cache.go index eb78e0bb65..e115d380f7 100644 --- a/pkg/cache/informertest/fake_cache.go +++ b/pkg/cache/informertest/fake_cache.go @@ -30,7 +30,7 @@ import ( var _ cache.Cache = &FakeInformers{} -// FakeInformers is a fake implementation of Informers +// FakeInformers is a fake implementation of Informers. type FakeInformers struct { InformersByGVK map[schema.GroupVersionKind]toolscache.SharedIndexInformer Scheme *runtime.Scheme @@ -38,7 +38,7 @@ type FakeInformers struct { Synced *bool } -// GetInformerForKind implements Informers +// GetInformerForKind implements Informers. func (c *FakeInformers) GetInformerForKind(ctx context.Context, gvk schema.GroupVersionKind) (cache.Informer, error) { if c.Scheme == nil { c.Scheme = scheme.Scheme @@ -50,7 +50,7 @@ func (c *FakeInformers) GetInformerForKind(ctx context.Context, gvk schema.Group return c.informerFor(gvk, obj) } -// FakeInformerForKind implements Informers +// FakeInformerForKind implements Informers. func (c *FakeInformers) FakeInformerForKind(ctx context.Context, gvk schema.GroupVersionKind) (*controllertest.FakeInformer, error) { if c.Scheme == nil { c.Scheme = scheme.Scheme @@ -66,7 +66,7 @@ func (c *FakeInformers) FakeInformerForKind(ctx context.Context, gvk schema.Grou return i.(*controllertest.FakeInformer), nil } -// GetInformer implements Informers +// GetInformer implements Informers. func (c *FakeInformers) GetInformer(ctx context.Context, obj client.Object) (cache.Informer, error) { if c.Scheme == nil { c.Scheme = scheme.Scheme @@ -79,7 +79,7 @@ func (c *FakeInformers) GetInformer(ctx context.Context, obj client.Object) (cac return c.informerFor(gvk, obj) } -// WaitForCacheSync implements Informers +// WaitForCacheSync implements Informers. func (c *FakeInformers) WaitForCacheSync(ctx context.Context) bool { if c.Synced == nil { return true @@ -87,7 +87,7 @@ func (c *FakeInformers) WaitForCacheSync(ctx context.Context) bool { return *c.Synced } -// FakeInformerFor implements Informers +// FakeInformerFor implements Informers. func (c *FakeInformers) FakeInformerFor(obj runtime.Object) (*controllertest.FakeInformer, error) { if c.Scheme == nil { c.Scheme = scheme.Scheme @@ -120,22 +120,22 @@ func (c *FakeInformers) informerFor(gvk schema.GroupVersionKind, _ runtime.Objec return c.InformersByGVK[gvk], nil } -// Start implements Informers +// Start implements Informers. func (c *FakeInformers) Start(ctx context.Context) error { return c.Error } -// IndexField implements Cache +// IndexField implements Cache. func (c *FakeInformers) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error { return nil } -// Get implements Cache +// Get implements Cache. func (c *FakeInformers) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error { return nil } -// List implements Cache +// List implements Cache. func (c *FakeInformers) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { return nil } diff --git a/pkg/cache/internal/cache_reader.go b/pkg/cache/internal/cache_reader.go index bd546b934a..5a495693ed 100644 --- a/pkg/cache/internal/cache_reader.go +++ b/pkg/cache/internal/cache_reader.go @@ -21,7 +21,7 @@ import ( "fmt" "reflect" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" @@ -33,10 +33,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -// CacheReader is a client.Reader +// CacheReader is a client.Reader. var _ client.Reader = &CacheReader{} -// CacheReader wraps a cache.Index to implement the client.CacheReader interface for a single type +// CacheReader wraps a cache.Index to implement the client.CacheReader interface for a single type. type CacheReader struct { // indexer is the underlying indexer wrapped by this cache. indexer cache.Indexer @@ -48,7 +48,7 @@ type CacheReader struct { scopeName apimeta.RESTScopeName } -// Get checks the indexer for the object and writes a copy of it if found +// Get checks the indexer for the object and writes a copy of it if found. func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Object) error { if c.scopeName == apimeta.RESTScopeNameRoot { key.Namespace = "" @@ -64,7 +64,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob // Not found, return an error if !exists { // Resource gets transformed into Kind in the error anyway, so this is fine - return errors.NewNotFound(schema.GroupResource{ + return apierrors.NewNotFound(schema.GroupResource{ Group: c.groupVersionKind.Group, Resource: c.groupVersionKind.Kind, }, key.Name) @@ -93,7 +93,7 @@ func (c *CacheReader) Get(_ context.Context, key client.ObjectKey, out client.Ob return nil } -// List lists items out of the indexer and writes them to out +// List lists items out of the indexer and writes them to out. func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...client.ListOption) error { var objs []interface{} var err error @@ -101,7 +101,8 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli listOpts := client.ListOptions{} listOpts.ApplyOptions(opts) - if listOpts.FieldSelector != nil { + switch { + case listOpts.FieldSelector != nil: // TODO(directxman12): support more complicated field selectors by // combining multiple indices, GetIndexers, etc field, val, requiresExact := requiresExactMatch(listOpts.FieldSelector) @@ -112,9 +113,9 @@ func (c *CacheReader) List(_ context.Context, out client.ObjectList, opts ...cli // namespaced index key. Otherwise, ask for the non-namespaced variant by using the fake "all namespaces" // namespace. objs, err = c.indexer.ByIndex(FieldIndexName(field), KeyToNamespacedKey(listOpts.Namespace, val)) - } else if listOpts.Namespace != "" { + case listOpts.Namespace != "": objs, err = c.indexer.ByIndex(cache.NamespaceIndex, listOpts.Namespace) - } else { + default: objs = c.indexer.List() } if err != nil { @@ -186,7 +187,7 @@ func FieldIndexName(field string) string { return "field:" + field } -// noNamespaceNamespace is used as the "namespace" when we want to list across all namespaces +// noNamespaceNamespace is used as the "namespace" when we want to list across all namespaces. const allNamespacesNamespace = "__all_namespaces" // KeyToNamespacedKey prefixes the given index key with a namespace diff --git a/pkg/cache/internal/deleg_map.go b/pkg/cache/internal/deleg_map.go index 2242d9b674..841f1657eb 100644 --- a/pkg/cache/internal/deleg_map.go +++ b/pkg/cache/internal/deleg_map.go @@ -52,7 +52,6 @@ func NewInformersMap(config *rest.Config, namespace string, selectors SelectorsByGVK, ) *InformersMap { - return &InformersMap{ structured: newStructuredInformersMap(config, scheme, mapper, resync, namespace, selectors), unstructured: newUnstructuredInformersMap(config, scheme, mapper, resync, namespace, selectors), diff --git a/pkg/cache/internal/informers_map.go b/pkg/cache/internal/informers_map.go index 5c9bd0b0a0..bef54d302e 100644 --- a/pkg/cache/internal/informers_map.go +++ b/pkg/cache/internal/informers_map.go @@ -37,7 +37,11 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) -// clientListWatcherFunc knows how to create a ListWatcher +func init() { + rand.Seed(time.Now().UnixNano()) +} + +// clientListWatcherFunc knows how to create a ListWatcher. type createListWatcherFunc func(gvk schema.GroupVersionKind, ip *specificInformersMap) (*cache.ListWatch, error) // newSpecificInformersMap returns a new specificInformersMap (like @@ -65,7 +69,7 @@ func newSpecificInformersMap(config *rest.Config, return ip } -// MapEntry contains the cached data for an Informer +// MapEntry contains the cached data for an Informer. type MapEntry struct { // Informer is the cached informer Informer cache.SharedIndexInformer @@ -378,7 +382,7 @@ func createMetadataListWatch(gvk schema.GroupVersionKind, ip *specificInformersM func resyncPeriod(resync time.Duration) func() time.Duration { return func() time.Duration { // the factor will fall into [0.9, 1.1) - factor := rand.Float64()/5.0 + 0.9 + factor := rand.Float64()/5.0 + 0.9 //nolint:gosec return time.Duration(float64(resync.Nanoseconds()) * factor) } } diff --git a/pkg/cache/internal/selector.go b/pkg/cache/internal/selector.go index 0e872eaf02..cd9c580008 100644 --- a/pkg/cache/internal/selector.go +++ b/pkg/cache/internal/selector.go @@ -23,16 +23,16 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -// SelectorsByGVK associate a GroupVersionKind to a field/label selector +// SelectorsByGVK associate a GroupVersionKind to a field/label selector. type SelectorsByGVK map[schema.GroupVersionKind]Selector -// Selector specify the label/field selector to fill in ListOptions +// Selector specify the label/field selector to fill in ListOptions. type Selector struct { Label labels.Selector Field fields.Selector } -// ApplyToList fill in ListOptions LabelSelector and FieldSelector if needed +// ApplyToList fill in ListOptions LabelSelector and FieldSelector if needed. func (s Selector) ApplyToList(listOpts *metav1.ListOptions) { if s.Label != nil { listOpts.LabelSelector = s.Label.String() diff --git a/pkg/cache/multi_namespace_cache.go b/pkg/cache/multi_namespace_cache.go index f3520bf8d7..dc29651b01 100644 --- a/pkg/cache/multi_namespace_cache.go +++ b/pkg/cache/multi_namespace_cache.go @@ -22,7 +22,6 @@ import ( "time" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/meta" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -32,10 +31,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/internal/objectutil" ) -// NewCacheFunc - Function for creating a new cache from the options and a rest config +// NewCacheFunc - Function for creating a new cache from the options and a rest config. type NewCacheFunc func(config *rest.Config, opts Options) (Cache, error) -// a new global namespaced cache to handle cluster scoped resources +// a new global namespaced cache to handle cluster scoped resources. const globalCache = "_cluster-scope" // MultiNamespacedCacheBuilder - Builder function to create a new multi-namespaced cache. @@ -78,13 +77,13 @@ func MultiNamespacedCacheBuilder(namespaces []string) NewCacheFunc { type multiNamespaceCache struct { namespaceToCache map[string]Cache Scheme *runtime.Scheme - RESTMapper meta.RESTMapper + RESTMapper apimeta.RESTMapper clusterCache Cache } var _ Cache = &multiNamespaceCache{} -// Methods for multiNamespaceCache to conform to the Informers interface +// Methods for multiNamespaceCache to conform to the Informers interface. func (c *multiNamespaceCache) GetInformer(ctx context.Context, obj client.Object) (Informer, error) { informers := map[string]Informer{} @@ -186,7 +185,7 @@ func (c *multiNamespaceCache) WaitForCacheSync(ctx context.Context) bool { func (c *multiNamespaceCache) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error { isNamespaced, err := objectutil.IsAPINamespaced(obj, c.Scheme, c.RESTMapper) if err != nil { - return nil + return nil //nolint:nilerr } if !isNamespaced { @@ -242,7 +241,7 @@ func (c *multiNamespaceCache) List(ctx context.Context, list client.ObjectList, return cache.List(ctx, list, opts...) } - listAccessor, err := meta.ListAccessor(list) + listAccessor, err := apimeta.ListAccessor(list) if err != nil { return err } @@ -265,7 +264,7 @@ func (c *multiNamespaceCache) List(ctx context.Context, list client.ObjectList, if err != nil { return err } - accessor, err := meta.ListAccessor(listObj) + accessor, err := apimeta.ListAccessor(listObj) if err != nil { return fmt.Errorf("object: %T must be a list type", list) } @@ -289,28 +288,28 @@ func (c *multiNamespaceCache) List(ctx context.Context, list client.ObjectList, return apimeta.SetList(list, allItems) } -// multiNamespaceInformer knows how to handle interacting with the underlying informer across multiple namespaces +// multiNamespaceInformer knows how to handle interacting with the underlying informer across multiple namespaces. type multiNamespaceInformer struct { namespaceToInformer map[string]Informer } var _ Informer = &multiNamespaceInformer{} -// AddEventHandler adds the handler to each namespaced informer +// AddEventHandler adds the handler to each namespaced informer. func (i *multiNamespaceInformer) AddEventHandler(handler toolscache.ResourceEventHandler) { for _, informer := range i.namespaceToInformer { informer.AddEventHandler(handler) } } -// AddEventHandlerWithResyncPeriod adds the handler with a resync period to each namespaced informer +// AddEventHandlerWithResyncPeriod adds the handler with a resync period to each namespaced informer. func (i *multiNamespaceInformer) AddEventHandlerWithResyncPeriod(handler toolscache.ResourceEventHandler, resyncPeriod time.Duration) { for _, informer := range i.namespaceToInformer { informer.AddEventHandlerWithResyncPeriod(handler, resyncPeriod) } } -// AddIndexers adds the indexer for each namespaced informer +// AddIndexers adds the indexer for each namespaced informer. func (i *multiNamespaceInformer) AddIndexers(indexers toolscache.Indexers) error { for _, informer := range i.namespaceToInformer { err := informer.AddIndexers(indexers) @@ -321,7 +320,7 @@ func (i *multiNamespaceInformer) AddIndexers(indexers toolscache.Indexers) error return nil } -// HasSynced checks if each namespaced informer has synced +// HasSynced checks if each namespaced informer has synced. func (i *multiNamespaceInformer) HasSynced() bool { for _, informer := range i.namespaceToInformer { if ok := informer.HasSynced(); !ok { diff --git a/pkg/certwatcher/certwatcher_test.go b/pkg/certwatcher/certwatcher_test.go index 5761768381..287645df92 100644 --- a/pkg/certwatcher/certwatcher_test.go +++ b/pkg/certwatcher/certwatcher_test.go @@ -125,9 +125,7 @@ func writeCerts(certPath, keyPath, ip string) error { keyUsage |= x509.KeyUsageKeyEncipherment } - var notBefore time.Time - notBefore = time.Now() - + notBefore := time.Now() notAfter := notBefore.Add(1 * time.Hour) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) @@ -169,7 +167,7 @@ func writeCerts(certPath, keyPath, ip string) error { return err } - keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) //nolint:gosec if err != nil { return err } @@ -180,8 +178,5 @@ func writeCerts(certPath, keyPath, ip string) error { if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { return err } - if err := keyOut.Close(); err != nil { - return err - } - return nil + return keyOut.Close() } diff --git a/pkg/certwatcher/example_test.go b/pkg/certwatcher/example_test.go index 0af8f3e71b..cea5280125 100644 --- a/pkg/certwatcher/example_test.go +++ b/pkg/certwatcher/example_test.go @@ -48,6 +48,7 @@ func Example() { // Setup TLS listener using GetCertficate for fetching the cert when changes listener, err := tls.Listen("tcp", "localhost:9443", &tls.Config{ GetCertificate: watcher.GetCertificate, + MinVersion: tls.VersionTLS12, }) if err != nil { panic(err) diff --git a/pkg/client/apiutil/apimachinery.go b/pkg/client/apiutil/apimachinery.go index bb66a6dfdd..2611a20c64 100644 --- a/pkg/client/apiutil/apimachinery.go +++ b/pkg/client/apiutil/apimachinery.go @@ -80,7 +80,7 @@ func GVKForObject(obj runtime.Object, scheme *runtime.Scheme) (schema.GroupVersi // (unstructured, partial, etc) // check for PartialObjectMetadata, which is analogous to unstructured, but isn't handled by ObjectKinds - _, isPartial := obj.(*metav1.PartialObjectMetadata) + _, isPartial := obj.(*metav1.PartialObjectMetadata) //nolint:ifshort _, isPartialList := obj.(*metav1.PartialObjectMetadataList) if isPartial || isPartialList { // we require that the GVK be populated in order to recognize the object @@ -134,7 +134,7 @@ func (f serializerWithDecodedGVK) DecoderToVersion(serializer runtime.Decoder, _ return serializer } -//createRestConfig copies the base config and updates needed fields for a new rest config +// createRestConfig copies the base config and updates needed fields for a new rest config. func createRestConfig(gvk schema.GroupVersionKind, isUnstructured bool, baseConfig *rest.Config, codecs serializer.CodecFactory) *rest.Config { gv := gvk.GroupVersion() diff --git a/pkg/client/apiutil/dynamicrestmapper.go b/pkg/client/apiutil/dynamicrestmapper.go index 5e9a7b5f53..56a00371ff 100644 --- a/pkg/client/apiutil/dynamicrestmapper.go +++ b/pkg/client/apiutil/dynamicrestmapper.go @@ -41,7 +41,7 @@ type dynamicRESTMapper struct { initOnce sync.Once } -// DynamicRESTMapperOption is a functional option on the dynamicRESTMapper +// DynamicRESTMapperOption is a functional option on the dynamicRESTMapper. type DynamicRESTMapperOption func(*dynamicRESTMapper) error // WithLimiter sets the RESTMapper's underlying limiter to lim. diff --git a/pkg/client/client.go b/pkg/client/client.go index 3444ab52b4..bbe36c4673 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -49,7 +49,7 @@ type WarningHandlerOptions struct { AllowDuplicateLogs bool } -// Options are creation options for a Client +// Options are creation options for a Client. type Options struct { // Scheme, if provided, will be used to map go structs to GroupVersionKinds Scheme *runtime.Scheme @@ -178,7 +178,7 @@ func (c *client) RESTMapper() meta.RESTMapper { return c.mapper } -// Create implements client.Client +// Create implements client.Client. func (c *client) Create(ctx context.Context, obj Object, opts ...CreateOption) error { switch obj.(type) { case *unstructured.Unstructured: @@ -190,7 +190,7 @@ func (c *client) Create(ctx context.Context, obj Object, opts ...CreateOption) e } } -// Update implements client.Client +// Update implements client.Client. func (c *client) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { defer c.resetGroupVersionKind(obj, obj.GetObjectKind().GroupVersionKind()) switch obj.(type) { @@ -203,7 +203,7 @@ func (c *client) Update(ctx context.Context, obj Object, opts ...UpdateOption) e } } -// Delete implements client.Client +// Delete implements client.Client. func (c *client) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { switch obj.(type) { case *unstructured.Unstructured: @@ -215,7 +215,7 @@ func (c *client) Delete(ctx context.Context, obj Object, opts ...DeleteOption) e } } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (c *client) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { switch obj.(type) { case *unstructured.Unstructured: @@ -227,7 +227,7 @@ func (c *client) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllO } } -// Patch implements client.Client +// Patch implements client.Client. func (c *client) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { defer c.resetGroupVersionKind(obj, obj.GetObjectKind().GroupVersionKind()) switch obj.(type) { @@ -240,7 +240,7 @@ func (c *client) Patch(ctx context.Context, obj Object, patch Patch, opts ...Pat } } -// Get implements client.Client +// Get implements client.Client. func (c *client) Get(ctx context.Context, key ObjectKey, obj Object) error { switch obj.(type) { case *unstructured.Unstructured: @@ -254,7 +254,7 @@ func (c *client) Get(ctx context.Context, key ObjectKey, obj Object) error { } } -// List implements client.Client +// List implements client.Client. func (c *client) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { switch x := obj.(type) { case *unstructured.UnstructuredList: @@ -288,20 +288,20 @@ func (c *client) List(ctx context.Context, obj ObjectList, opts ...ListOption) e } } -// Status implements client.StatusClient +// Status implements client.StatusClient. func (c *client) Status() StatusWriter { return &statusWriter{client: c} } -// statusWriter is client.StatusWriter that writes status subresource +// statusWriter is client.StatusWriter that writes status subresource. type statusWriter struct { client *client } -// ensure statusWriter implements client.StatusWriter +// ensure statusWriter implements client.StatusWriter. var _ StatusWriter = &statusWriter{} -// Update implements client.StatusWriter +// Update implements client.StatusWriter. func (sw *statusWriter) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { defer sw.client.resetGroupVersionKind(obj, obj.GetObjectKind().GroupVersionKind()) switch obj.(type) { @@ -314,7 +314,7 @@ func (sw *statusWriter) Update(ctx context.Context, obj Object, opts ...UpdateOp } } -// Patch implements client.Client +// Patch implements client.Client. func (sw *statusWriter) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { defer sw.client.resetGroupVersionKind(obj, obj.GetObjectKind().GroupVersionKind()) switch obj.(type) { diff --git a/pkg/client/client_cache.go b/pkg/client/client_cache.go index b3493cb025..857a0b38a7 100644 --- a/pkg/client/client_cache.go +++ b/pkg/client/client_cache.go @@ -30,7 +30,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) -// clientCache creates and caches rest clients and metadata for Kubernetes types +// clientCache creates and caches rest clients and metadata for Kubernetes types. type clientCache struct { // config is the rest.Config to talk to an apiserver config *rest.Config @@ -107,7 +107,7 @@ func (c *clientCache) getResource(obj runtime.Object) (*resourceMeta, error) { return r, err } -// getObjMeta returns objMeta containing both type and object metadata and state +// getObjMeta returns objMeta containing both type and object metadata and state. func (c *clientCache) getObjMeta(obj runtime.Object) (*objMeta, error) { r, err := c.getResource(obj) if err != nil { @@ -130,17 +130,17 @@ type resourceMeta struct { mapping *meta.RESTMapping } -// isNamespaced returns true if the type is namespaced +// isNamespaced returns true if the type is namespaced. func (r *resourceMeta) isNamespaced() bool { return r.mapping.Scope.Name() != meta.RESTScopeNameRoot } -// resource returns the resource name of the type +// resource returns the resource name of the type. func (r *resourceMeta) resource() string { return r.mapping.Resource.Resource } -// objMeta stores type and object information about a Kubernetes type +// objMeta stores type and object information about a Kubernetes type. type objMeta struct { // resourceMeta contains type information for the object *resourceMeta diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index 617fae6f5a..ebd6e47744 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -3475,11 +3475,11 @@ type fakeReader struct { } func (f *fakeReader) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error { - f.Called = f.Called + 1 + f.Called++ return nil } func (f *fakeReader) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { - f.Called = f.Called + 1 + f.Called++ return nil } diff --git a/pkg/client/config/config.go b/pkg/client/config/config.go index 69f7dc6e4a..235a7e450b 100644 --- a/pkg/client/config/config.go +++ b/pkg/client/config/config.go @@ -55,7 +55,7 @@ func init() { // // * In-cluster config if running in cluster // -// * $HOME/.kube/config if exists +// * $HOME/.kube/config if exists. func GetConfig() (*rest.Config, error) { return GetConfigWithContext("") } @@ -75,7 +75,7 @@ func GetConfig() (*rest.Config, error) { // // * In-cluster config if running in cluster // -// * $HOME/.kube/config if exists +// * $HOME/.kube/config if exists. func GetConfigWithContext(context string) (*rest.Config, error) { cfg, err := loadConfig(context) if err != nil { @@ -95,9 +95,8 @@ func GetConfigWithContext(context string) (*rest.Config, error) { // test the precedence of loading the config. var loadInClusterConfig = rest.InClusterConfig -// loadConfig loads a REST Config as per the rules specified in GetConfig +// loadConfig loads a REST Config as per the rules specified in GetConfig. func loadConfig(context string) (*rest.Config, error) { - // If a flag is specified with the config location, use that if len(kubeconfig) > 0 { return loadConfigWithContext("", &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, context) diff --git a/pkg/client/config/config_test.go b/pkg/client/config/config_test.go index a352bd9109..ed9761e50f 100644 --- a/pkg/client/config/config_test.go +++ b/pkg/client/config/config_test.go @@ -192,7 +192,7 @@ func setConfigs(tc testCase, dir string) { func createFiles(files map[string]string, dir string) error { for path, data := range files { - if err := ioutil.WriteFile(filepath.Join(dir, path), []byte(data), 0644); err != nil { + if err := ioutil.WriteFile(filepath.Join(dir, path), []byte(data), 0644); err != nil { //nolint:gosec return err } } diff --git a/pkg/client/dryrun.go b/pkg/client/dryrun.go index 67e80e0551..ea25ea2530 100644 --- a/pkg/client/dryrun.go +++ b/pkg/client/dryrun.go @@ -46,47 +46,47 @@ func (c *dryRunClient) RESTMapper() meta.RESTMapper { return c.client.RESTMapper() } -// Create implements client.Client +// Create implements client.Client. func (c *dryRunClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { return c.client.Create(ctx, obj, append(opts, DryRunAll)...) } -// Update implements client.Client +// Update implements client.Client. func (c *dryRunClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { return c.client.Update(ctx, obj, append(opts, DryRunAll)...) } -// Delete implements client.Client +// Delete implements client.Client. func (c *dryRunClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { return c.client.Delete(ctx, obj, append(opts, DryRunAll)...) } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (c *dryRunClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { return c.client.DeleteAllOf(ctx, obj, append(opts, DryRunAll)...) } -// Patch implements client.Client +// Patch implements client.Client. func (c *dryRunClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { return c.client.Patch(ctx, obj, patch, append(opts, DryRunAll)...) } -// Get implements client.Client +// Get implements client.Client. func (c *dryRunClient) Get(ctx context.Context, key ObjectKey, obj Object) error { return c.client.Get(ctx, key, obj) } -// List implements client.Client +// List implements client.Client. func (c *dryRunClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { return c.client.List(ctx, obj, opts...) } -// Status implements client.StatusClient +// Status implements client.StatusClient. func (c *dryRunClient) Status() StatusWriter { return &dryRunStatusWriter{client: c.client.Status()} } -// ensure dryRunStatusWriter implements client.StatusWriter +// ensure dryRunStatusWriter implements client.StatusWriter. var _ StatusWriter = &dryRunStatusWriter{} // dryRunStatusWriter is client.StatusWriter that writes status subresource with dryRun mode @@ -95,12 +95,12 @@ type dryRunStatusWriter struct { client StatusWriter } -// Update implements client.StatusWriter +// Update implements client.StatusWriter. func (sw *dryRunStatusWriter) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { return sw.client.Update(ctx, obj, append(opts, DryRunAll)...) } -// Patch implements client.StatusWriter +// Patch implements client.StatusWriter. func (sw *dryRunStatusWriter) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { return sw.client.Patch(ctx, obj, patch, append(opts, DryRunAll)...) } diff --git a/pkg/client/fake/client_test.go b/pkg/client/fake/client_test.go index 6cf1e9b2ad..e59e68d3ad 100644 --- a/pkg/client/fake/client_test.go +++ b/pkg/client/fake/client_test.go @@ -29,7 +29,6 @@ import ( appsv1 "k8s.io/api/apps/v1" coordinationv1 "k8s.io/api/coordination/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -282,7 +281,7 @@ var _ = Describe("Fake client", func() { It("should support filtering by label existence", func() { By("Listing deployments with a particular label") list := &appsv1.DeploymentList{} - err := cl.List(nil, list, client.InNamespace("ns1"), + err := cl.List(context.Background(), list, client.InNamespace("ns1"), client.HasLabels{"test-label"}) Expect(err).To(BeNil()) Expect(list.Items).To(HaveLen(1)) @@ -385,12 +384,12 @@ var _ = Describe("Fake client", func() { }, }, } - err := cl.Create(nil, newcm) + err := cl.Create(context.Background(), newcm) Expect(err).To(BeNil()) By("Listing configmaps with a particular label") list := &corev1.ConfigMapList{} - err = cl.List(nil, list, client.InNamespace("ns2"), + err = cl.List(context.Background(), list, client.InNamespace("ns2"), client.MatchingLabels(map[string]string{ "test-label": "label-value", })) @@ -715,7 +714,7 @@ var _ = Describe("Fake client", func() { obj := &corev1.ConfigMap{} err = cl.Get(context.Background(), namespacedName, obj) Expect(err).To(HaveOccurred()) - Expect(errors.IsNotFound(err)).To(BeTrue()) + Expect(apierrors.IsNotFound(err)).To(BeTrue()) Expect(obj).NotTo(Equal(newcm)) }) diff --git a/pkg/client/interfaces.go b/pkg/client/interfaces.go index 0dfea4d6c5..58c2ece15b 100644 --- a/pkg/client/interfaces.go +++ b/pkg/client/interfaces.go @@ -30,7 +30,7 @@ import ( // ObjectKey identifies a Kubernetes Object. type ObjectKey = types.NamespacedName -// ObjectKeyFromObject returns the ObjectKey given a runtime.Object +// ObjectKeyFromObject returns the ObjectKey given a runtime.Object. func ObjectKeyFromObject(obj Object) ObjectKey { return ObjectKey{Namespace: obj.GetNamespace(), Name: obj.GetName()} } diff --git a/pkg/client/metadata_client.go b/pkg/client/metadata_client.go index c0fc72c5b7..59747463a4 100644 --- a/pkg/client/metadata_client.go +++ b/pkg/client/metadata_client.go @@ -49,7 +49,7 @@ func (mc *metadataClient) getResourceInterface(gvk schema.GroupVersionKind, ns s return mc.client.Resource(mapping.Resource).Namespace(ns), nil } -// Delete implements client.Client +// Delete implements client.Client. func (mc *metadataClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) if !ok { @@ -67,7 +67,7 @@ func (mc *metadataClient) Delete(ctx context.Context, obj Object, opts ...Delete return resInt.Delete(ctx, metadata.Name, *deleteOpts.AsDeleteOptions()) } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (mc *metadataClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) if !ok { @@ -85,7 +85,7 @@ func (mc *metadataClient) DeleteAllOf(ctx context.Context, obj Object, opts ...D return resInt.DeleteCollection(ctx, *deleteAllOfOpts.AsDeleteOptions(), *deleteAllOfOpts.AsListOptions()) } -// Patch implements client.Client +// Patch implements client.Client. func (mc *metadataClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) if !ok { @@ -115,7 +115,7 @@ func (mc *metadataClient) Patch(ctx context.Context, obj Object, patch Patch, op return nil } -// Get implements client.Client +// Get implements client.Client. func (mc *metadataClient) Get(ctx context.Context, key ObjectKey, obj Object) error { metadata, ok := obj.(*metav1.PartialObjectMetadata) if !ok { @@ -138,7 +138,7 @@ func (mc *metadataClient) Get(ctx context.Context, key ObjectKey, obj Object) er return nil } -// List implements client.Client +// List implements client.Client. func (mc *metadataClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { metadata, ok := obj.(*metav1.PartialObjectMetadataList) if !ok { diff --git a/pkg/client/namespaced_client.go b/pkg/client/namespaced_client.go index cedcfb5961..d73cc5135a 100644 --- a/pkg/client/namespaced_client.go +++ b/pkg/client/namespaced_client.go @@ -86,7 +86,7 @@ func isNamespaced(c Client, obj runtime.Object) (bool, error) { scope := restmapping.Scope.Name() if scope == "" { - return false, errors.New("Scope cannot be identified. Empty scope returned") + return false, errors.New("scope cannot be identified, empty scope returned") } if scope != meta.RESTScopeNameRoot { @@ -95,7 +95,7 @@ func isNamespaced(c Client, obj runtime.Object) (bool, error) { return false, nil } -// Create implements clinet.Client +// Create implements clinet.Client. func (n *namespacedClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -104,7 +104,7 @@ func (n *namespacedClient) Create(ctx context.Context, obj Object, opts ...Creat objectNamespace := obj.GetNamespace() if objectNamespace != n.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) } if isNamespaceScoped && objectNamespace == "" { @@ -113,7 +113,7 @@ func (n *namespacedClient) Create(ctx context.Context, obj Object, opts ...Creat return n.client.Create(ctx, obj, opts...) } -// Update implements client.Client +// Update implements client.Client. func (n *namespacedClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -122,7 +122,7 @@ func (n *namespacedClient) Update(ctx context.Context, obj Object, opts ...Updat objectNamespace := obj.GetNamespace() if objectNamespace != n.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) } if isNamespaceScoped && objectNamespace == "" { @@ -131,7 +131,7 @@ func (n *namespacedClient) Update(ctx context.Context, obj Object, opts ...Updat return n.client.Update(ctx, obj, opts...) } -// Delete implements client.Client +// Delete implements client.Client. func (n *namespacedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -140,7 +140,7 @@ func (n *namespacedClient) Delete(ctx context.Context, obj Object, opts ...Delet objectNamespace := obj.GetNamespace() if objectNamespace != n.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) } if isNamespaceScoped && objectNamespace == "" { @@ -149,7 +149,7 @@ func (n *namespacedClient) Delete(ctx context.Context, obj Object, opts ...Delet return n.client.Delete(ctx, obj, opts...) } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (n *namespacedClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -162,7 +162,7 @@ func (n *namespacedClient) DeleteAllOf(ctx context.Context, obj Object, opts ... return n.client.DeleteAllOf(ctx, obj, opts...) } -// Patch implements client.Client +// Patch implements client.Client. func (n *namespacedClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -171,7 +171,7 @@ func (n *namespacedClient) Patch(ctx context.Context, obj Object, patch Patch, o objectNamespace := obj.GetNamespace() if objectNamespace != n.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), n.namespace) } if isNamespaceScoped && objectNamespace == "" { @@ -180,7 +180,7 @@ func (n *namespacedClient) Patch(ctx context.Context, obj Object, patch Patch, o return n.client.Patch(ctx, obj, patch, opts...) } -// Get implements client.Client +// Get implements client.Client. func (n *namespacedClient) Get(ctx context.Context, key ObjectKey, obj Object) error { isNamespaceScoped, err := isNamespaced(n.client, obj) if err != nil { @@ -188,14 +188,14 @@ func (n *namespacedClient) Get(ctx context.Context, key ObjectKey, obj Object) e } if isNamespaceScoped { if key.Namespace != "" && key.Namespace != n.namespace { - return fmt.Errorf("Namespace %s provided for the object %s does not match the namesapce %s on the client", key.Namespace, obj.GetName(), n.namespace) + return fmt.Errorf("namespace %s provided for the object %s does not match the namesapce %s on the client", key.Namespace, obj.GetName(), n.namespace) } key.Namespace = n.namespace } return n.client.Get(ctx, key, obj) } -// List implements client.Client +// List implements client.Client. func (n *namespacedClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { if n.namespace != "" { opts = append(opts, InNamespace(n.namespace)) @@ -203,12 +203,12 @@ func (n *namespacedClient) List(ctx context.Context, obj ObjectList, opts ...Lis return n.client.List(ctx, obj, opts...) } -// Status implements client.StatusClient +// Status implements client.StatusClient. func (n *namespacedClient) Status() StatusWriter { return &namespacedClientStatusWriter{StatusClient: n.client.Status(), namespace: n.namespace, namespacedclient: n} } -// ensure namespacedClientStatusWriter implements client.StatusWriter +// ensure namespacedClientStatusWriter implements client.StatusWriter. var _ StatusWriter = &namespacedClientStatusWriter{} type namespacedClientStatusWriter struct { @@ -217,7 +217,7 @@ type namespacedClientStatusWriter struct { namespacedclient Client } -// Update implements client.StatusWriter +// Update implements client.StatusWriter. func (nsw *namespacedClientStatusWriter) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { isNamespaceScoped, err := isNamespaced(nsw.namespacedclient, obj) if err != nil { @@ -226,7 +226,7 @@ func (nsw *namespacedClientStatusWriter) Update(ctx context.Context, obj Object, objectNamespace := obj.GetNamespace() if objectNamespace != nsw.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), nsw.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), nsw.namespace) } if isNamespaceScoped && objectNamespace == "" { @@ -235,7 +235,7 @@ func (nsw *namespacedClientStatusWriter) Update(ctx context.Context, obj Object, return nsw.StatusClient.Update(ctx, obj, opts...) } -// Patch implements client.StatusWriter +// Patch implements client.StatusWriter. func (nsw *namespacedClientStatusWriter) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { isNamespaceScoped, err := isNamespaced(nsw.namespacedclient, obj) if err != nil { @@ -244,7 +244,7 @@ func (nsw *namespacedClientStatusWriter) Patch(ctx context.Context, obj Object, objectNamespace := obj.GetNamespace() if objectNamespace != nsw.namespace && objectNamespace != "" { - return fmt.Errorf("Namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), nsw.namespace) + return fmt.Errorf("namespace %s of the object %s does not match the namespace %s on the client", objectNamespace, obj.GetName(), nsw.namespace) } if isNamespaceScoped && objectNamespace == "" { diff --git a/pkg/client/options.go b/pkg/client/options.go index f253276466..aa2299eac0 100644 --- a/pkg/client/options.go +++ b/pkg/client/options.go @@ -158,7 +158,7 @@ func (o *CreateOptions) ApplyOptions(opts []CreateOption) *CreateOptions { return o } -// ApplyToCreate implements CreateOption +// ApplyToCreate implements CreateOption. func (o *CreateOptions) ApplyToCreate(co *CreateOptions) { if o.DryRun != nil { co.DryRun = o.DryRun @@ -239,7 +239,7 @@ func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) *DeleteOptions { var _ DeleteOption = &DeleteOptions{} -// ApplyToDelete implements DeleteOption +// ApplyToDelete implements DeleteOption. func (o *DeleteOptions) ApplyToDelete(do *DeleteOptions) { if o.GracePeriodSeconds != nil { do.GracePeriodSeconds = o.GracePeriodSeconds @@ -349,7 +349,7 @@ type ListOptions struct { var _ ListOption = &ListOptions{} -// ApplyToList implements ListOption for ListOptions +// ApplyToList implements ListOption for ListOptions. func (o *ListOptions) ApplyToList(lo *ListOptions) { if o.LabelSelector != nil { lo.LabelSelector = o.LabelSelector @@ -569,7 +569,7 @@ func (o *UpdateOptions) ApplyOptions(opts []UpdateOption) *UpdateOptions { var _ UpdateOption = &UpdateOptions{} -// ApplyToUpdate implements UpdateOption +// ApplyToUpdate implements UpdateOption. func (o *UpdateOptions) ApplyToUpdate(uo *UpdateOptions) { if o.DryRun != nil { uo.DryRun = o.DryRun @@ -636,7 +636,7 @@ func (o *PatchOptions) AsPatchOptions() *metav1.PatchOptions { var _ PatchOption = &PatchOptions{} -// ApplyToPatch implements PatchOptions +// ApplyToPatch implements PatchOptions. func (o *PatchOptions) ApplyToPatch(po *PatchOptions) { if o.DryRun != nil { po.DryRun = o.DryRun @@ -688,7 +688,7 @@ func (o *DeleteAllOfOptions) ApplyOptions(opts []DeleteAllOfOption) *DeleteAllOf var _ DeleteAllOfOption = &DeleteAllOfOptions{} -// ApplyToDeleteAllOf implements DeleteAllOfOption +// ApplyToDeleteAllOf implements DeleteAllOfOption. func (o *DeleteAllOfOptions) ApplyToDeleteAllOf(do *DeleteAllOfOptions) { o.ApplyToList(&do.ListOptions) o.ApplyToDelete(&do.DeleteOptions) diff --git a/pkg/client/typed_client.go b/pkg/client/typed_client.go index a1b32653ca..dde7b21f25 100644 --- a/pkg/client/typed_client.go +++ b/pkg/client/typed_client.go @@ -33,7 +33,7 @@ type typedClient struct { paramCodec runtime.ParameterCodec } -// Create implements client.Client +// Create implements client.Client. func (c *typedClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { o, err := c.cache.getObjMeta(obj) if err != nil { @@ -51,7 +51,7 @@ func (c *typedClient) Create(ctx context.Context, obj Object, opts ...CreateOpti Into(obj) } -// Update implements client.Client +// Update implements client.Client. func (c *typedClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { o, err := c.cache.getObjMeta(obj) if err != nil { @@ -70,7 +70,7 @@ func (c *typedClient) Update(ctx context.Context, obj Object, opts ...UpdateOpti Into(obj) } -// Delete implements client.Client +// Delete implements client.Client. func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { o, err := c.cache.getObjMeta(obj) if err != nil { @@ -89,7 +89,7 @@ func (c *typedClient) Delete(ctx context.Context, obj Object, opts ...DeleteOpti Error() } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (c *typedClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { o, err := c.cache.getObjMeta(obj) if err != nil { @@ -108,7 +108,7 @@ func (c *typedClient) DeleteAllOf(ctx context.Context, obj Object, opts ...Delet Error() } -// Patch implements client.Client +// Patch implements client.Client. func (c *typedClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { o, err := c.cache.getObjMeta(obj) if err != nil { @@ -131,7 +131,7 @@ func (c *typedClient) Patch(ctx context.Context, obj Object, patch Patch, opts . Into(obj) } -// Get implements client.Client +// Get implements client.Client. func (c *typedClient) Get(ctx context.Context, key ObjectKey, obj Object) error { r, err := c.cache.getResource(obj) if err != nil { @@ -143,7 +143,7 @@ func (c *typedClient) Get(ctx context.Context, key ObjectKey, obj Object) error Name(key.Name).Do(ctx).Into(obj) } -// List implements client.Client +// List implements client.Client. func (c *typedClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { r, err := c.cache.getResource(obj) if err != nil { diff --git a/pkg/client/unstructured_client.go b/pkg/client/unstructured_client.go index f8fb3ccec1..dcf15be275 100644 --- a/pkg/client/unstructured_client.go +++ b/pkg/client/unstructured_client.go @@ -36,7 +36,7 @@ type unstructuredClient struct { paramCodec runtime.ParameterCodec } -// Create implements client.Client +// Create implements client.Client. func (uc *unstructuredClient) Create(ctx context.Context, obj Object, opts ...CreateOption) error { u, ok := obj.(*unstructured.Unstructured) if !ok { @@ -64,7 +64,7 @@ func (uc *unstructuredClient) Create(ctx context.Context, obj Object, opts ...Cr return result } -// Update implements client.Client +// Update implements client.Client. func (uc *unstructuredClient) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { u, ok := obj.(*unstructured.Unstructured) if !ok { @@ -93,7 +93,7 @@ func (uc *unstructuredClient) Update(ctx context.Context, obj Object, opts ...Up return result } -// Delete implements client.Client +// Delete implements client.Client. func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { _, ok := obj.(*unstructured.Unstructured) if !ok { @@ -116,7 +116,7 @@ func (uc *unstructuredClient) Delete(ctx context.Context, obj Object, opts ...De Error() } -// DeleteAllOf implements client.Client +// DeleteAllOf implements client.Client. func (uc *unstructuredClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { _, ok := obj.(*unstructured.Unstructured) if !ok { @@ -139,7 +139,7 @@ func (uc *unstructuredClient) DeleteAllOf(ctx context.Context, obj Object, opts Error() } -// Patch implements client.Client +// Patch implements client.Client. func (uc *unstructuredClient) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { _, ok := obj.(*unstructured.Unstructured) if !ok { @@ -167,7 +167,7 @@ func (uc *unstructuredClient) Patch(ctx context.Context, obj Object, patch Patch Into(obj) } -// Get implements client.Client +// Get implements client.Client. func (uc *unstructuredClient) Get(ctx context.Context, key ObjectKey, obj Object) error { u, ok := obj.(*unstructured.Unstructured) if !ok { @@ -193,7 +193,7 @@ func (uc *unstructuredClient) Get(ctx context.Context, key ObjectKey, obj Object return result } -// List implements client.Client +// List implements client.Client. func (uc *unstructuredClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error { u, ok := obj.(*unstructured.UnstructuredList) if !ok { diff --git a/pkg/cluster/cluster.go b/pkg/cluster/cluster.go index 76fa72ad76..dfd0fa9dd8 100644 --- a/pkg/cluster/cluster.go +++ b/pkg/cluster/cluster.go @@ -139,10 +139,10 @@ type Options struct { newRecorderProvider func(config *rest.Config, scheme *runtime.Scheme, logger logr.Logger, makeBroadcaster intrec.EventBroadcasterProducer) (*intrec.Provider, error) } -// Option can be used to manipulate Options +// Option can be used to manipulate Options. type Option func(*Options) -// New constructs a brand new cluster +// New constructs a brand new cluster. func New(config *rest.Config, opts ...Option) (Cluster, error) { if config == nil { return nil, errors.New("must specify Config") @@ -204,7 +204,7 @@ func New(config *rest.Config, opts ...Option) (Cluster, error) { }, nil } -// setOptionsDefaults set default values for Options fields +// setOptionsDefaults set default values for Options fields. func setOptionsDefaults(options Options) Options { // Use the Kubernetes client-go scheme if none is specified if options.Scheme == nil { @@ -252,10 +252,10 @@ func setOptionsDefaults(options Options) Options { return options } -// NewClientFunc allows a user to define how to create a client +// NewClientFunc allows a user to define how to create a client. type NewClientFunc func(cache cache.Cache, config *rest.Config, options client.Options, uncachedObjects ...client.Object) (client.Client, error) -// DefaultNewClient creates the default caching client +// DefaultNewClient creates the default caching client. func DefaultNewClient(cache cache.Cache, config *rest.Config, options client.Options, uncachedObjects ...client.Object) (client.Client, error) { c, err := client.New(config, options) if err != nil { diff --git a/pkg/cluster/cluster_suite_test.go b/pkg/cluster/cluster_suite_test.go index fe8873473a..8e9b7ef2ac 100644 --- a/pkg/cluster/cluster_suite_test.go +++ b/pkg/cluster/cluster_suite_test.go @@ -40,7 +40,7 @@ var testenv *envtest.Environment var cfg *rest.Config var clientset *kubernetes.Clientset -// clientTransport is used to force-close keep-alives in tests that check for leaks +// clientTransport is used to force-close keep-alives in tests that check for leaks. var clientTransport *http.Transport var _ = BeforeSuite(func(done Done) { diff --git a/pkg/config/config.go b/pkg/config/config.go index fce75d7bfb..f23b02df00 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -28,7 +28,7 @@ import ( ) // ControllerManagerConfiguration defines the functions necessary to parse a config file -// and to configure the Options struct for the ctrl.Manager +// and to configure the Options struct for the ctrl.Manager. type ControllerManagerConfiguration interface { runtime.Object @@ -37,7 +37,7 @@ type ControllerManagerConfiguration interface { } // DeferredFileLoader is used to configure the decoder for loading controller -// runtime component config types +// runtime component config types. type DeferredFileLoader struct { ControllerManagerConfiguration path string @@ -62,7 +62,7 @@ func File() *DeferredFileLoader { } } -// Complete will use sync.Once to set the scheme +// Complete will use sync.Once to set the scheme. func (d *DeferredFileLoader) Complete() (v1alpha1.ControllerManagerConfigurationSpec, error) { d.once.Do(d.loadFile) if d.err != nil { @@ -71,25 +71,25 @@ func (d *DeferredFileLoader) Complete() (v1alpha1.ControllerManagerConfiguration return d.ControllerManagerConfiguration.Complete() } -// AtPath will set the path to load the file for the decoder +// AtPath will set the path to load the file for the decoder. func (d *DeferredFileLoader) AtPath(path string) *DeferredFileLoader { d.path = path return d } -// OfKind will set the type to be used for decoding the file into +// OfKind will set the type to be used for decoding the file into. func (d *DeferredFileLoader) OfKind(obj ControllerManagerConfiguration) *DeferredFileLoader { d.ControllerManagerConfiguration = obj return d } -// InjectScheme will configure the scheme to be used for decoding the file +// InjectScheme will configure the scheme to be used for decoding the file. func (d *DeferredFileLoader) InjectScheme(scheme *runtime.Scheme) error { d.scheme = scheme return nil } -// loadFile is used from the mutex.Once to load the file +// loadFile is used from the mutex.Once to load the file. func (d *DeferredFileLoader) loadFile() { if d.scheme == nil { d.err = fmt.Errorf("scheme not supplied to controller configuration loader") @@ -109,6 +109,4 @@ func (d *DeferredFileLoader) loadFile() { if err = runtime.DecodeInto(codecs.UniversalDecoder(), content, d.ControllerManagerConfiguration); err != nil { d.err = fmt.Errorf("could not decode file into runtime.Object") } - - return } diff --git a/pkg/config/example_test.go b/pkg/config/example_test.go index 4402f77ba6..fb1cd58b5f 100644 --- a/pkg/config/example_test.go +++ b/pkg/config/example_test.go @@ -37,24 +37,22 @@ func init() { func ExampleFile() { // This will load a config file from ./config.yaml loader := config.File() - _, err := loader.Complete() - if err != nil { + if _, err := loader.Complete(); err != nil { fmt.Println("failed to load config") os.Exit(1) } } -// This example will load the file from a custom path +// This example will load the file from a custom path. func ExampleDeferredFileLoader_atPath() { loader := config.File().AtPath("/var/run/controller-runtime/config.yaml") - _, err := loader.Complete() - if err != nil { + if _, err := loader.Complete(); err != nil { fmt.Println("failed to load config") os.Exit(1) } } -// This example sets up loader with a custom scheme +// This example sets up loader with a custom scheme. func ExampleDeferredFileLoader_injectScheme() { loader := config.File() err := loader.InjectScheme(scheme) @@ -70,7 +68,7 @@ func ExampleDeferredFileLoader_injectScheme() { } } -// This example sets up the loader with a custom scheme and custom type +// This example sets up the loader with a custom scheme and custom type. func ExampleDeferredFileLoader_ofKind() { loader := config.File().OfKind(&v1alpha1.CustomControllerManagerConfiguration{}) err := loader.InjectScheme(scheme) diff --git a/pkg/config/v1alpha1/register.go b/pkg/config/v1alpha1/register.go index 72baa27f19..9efdbc0668 100644 --- a/pkg/config/v1alpha1/register.go +++ b/pkg/config/v1alpha1/register.go @@ -22,10 +22,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "controller-runtime.sigs.k8s.io", Version: "v1alpha1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/pkg/config/v1alpha1/types.go b/pkg/config/v1alpha1/types.go index e13f1c0090..e67b62e514 100644 --- a/pkg/config/v1alpha1/types.go +++ b/pkg/config/v1alpha1/types.go @@ -24,7 +24,7 @@ import ( configv1alpha1 "k8s.io/component-base/config/v1alpha1" ) -// ControllerManagerConfigurationSpec defines the desired state of GenericControllerManagerConfiguration +// ControllerManagerConfigurationSpec defines the desired state of GenericControllerManagerConfiguration. type ControllerManagerConfigurationSpec struct { // SyncPeriod determines the minimum frequency at which watched resources are // reconciled. A lower period will correct entropy more quickly, but reduce @@ -96,7 +96,7 @@ type ControllerConfigurationSpec struct { CacheSyncTimeout *time.Duration `json:"cacheSyncTimeout,omitempty"` } -// ControllerMetrics defines the metrics configs +// ControllerMetrics defines the metrics configs. type ControllerMetrics struct { // BindAddress is the TCP address that the controller should bind to // for serving prometheus metrics. @@ -105,7 +105,7 @@ type ControllerMetrics struct { BindAddress string `json:"bindAddress,omitempty"` } -// ControllerHealth defines the health configs +// ControllerHealth defines the health configs. type ControllerHealth struct { // HealthProbeBindAddress is the TCP address that the controller should bind to // for serving health probes @@ -121,7 +121,7 @@ type ControllerHealth struct { LivenessEndpointName string `json:"livenessEndpointName,omitempty"` } -// ControllerWebhook defines the webhook server for the controller +// ControllerWebhook defines the webhook server for the controller. type ControllerWebhook struct { // Port is the port that the webhook server serves at. // It is used to set webhook.Server.Port. @@ -143,7 +143,7 @@ type ControllerWebhook struct { // +kubebuilder:object:root=true -// ControllerManagerConfiguration is the Schema for the GenericControllerManagerConfigurations API +// ControllerManagerConfiguration is the Schema for the GenericControllerManagerConfigurations API. type ControllerManagerConfiguration struct { metav1.TypeMeta `json:",inline"` @@ -151,7 +151,7 @@ type ControllerManagerConfiguration struct { ControllerManagerConfigurationSpec `json:",inline"` } -// Complete returns the configuration for controller-runtime +// Complete returns the configuration for controller-runtime. func (c *ControllerManagerConfigurationSpec) Complete() (ControllerManagerConfigurationSpec, error) { return *c, nil } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 85d8d6d54c..c9e07562a3 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -32,7 +32,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// Options are the arguments for creating a new Controller +// Options are the arguments for creating a new Controller. type Options struct { // MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1. MaxConcurrentReconciles int diff --git a/pkg/controller/controller_suite_test.go b/pkg/controller/controller_suite_test.go index b4d5111bb8..363c1076b6 100644 --- a/pkg/controller/controller_suite_test.go +++ b/pkg/controller/controller_suite_test.go @@ -46,7 +46,7 @@ var testenv *envtest.Environment var cfg *rest.Config var clientset *kubernetes.Clientset -// clientTransport is used to force-close keep-alives in tests that check for leaks +// clientTransport is used to force-close keep-alives in tests that check for leaks. var clientTransport *http.Transport var _ = BeforeSuite(func(done Done) { diff --git a/pkg/controller/controllertest/testing.go b/pkg/controller/controllertest/testing.go index 570a97e36d..b9f97d5289 100644 --- a/pkg/controller/controllertest/testing.go +++ b/pkg/controller/controllertest/testing.go @@ -29,10 +29,10 @@ var _ runtime.Object = &ErrorType{} // ErrorType implements runtime.Object but isn't registered in any scheme and should cause errors in tests as a result. type ErrorType struct{} -// GetObjectKind implements runtime.Object +// GetObjectKind implements runtime.Object. func (ErrorType) GetObjectKind() schema.ObjectKind { return nil } -// DeepCopyObject implements runtime.Object +// DeepCopyObject implements runtime.Object. func (ErrorType) DeepCopyObject() runtime.Object { return nil } var _ workqueue.RateLimitingInterface = Queue{} diff --git a/pkg/controller/controllertest/util.go b/pkg/controller/controllertest/util.go index 2ce0b4812e..df6ae9a223 100644 --- a/pkg/controller/controllertest/util.go +++ b/pkg/controller/controllertest/util.go @@ -25,7 +25,7 @@ import ( var _ cache.SharedIndexInformer = &FakeInformer{} -// FakeInformer provides fake Informer functionality for testing +// FakeInformer provides fake Informer functionality for testing. type FakeInformer struct { // Synced is returned by the HasSynced functions to implement the Informer interface Synced bool @@ -51,7 +51,7 @@ func (f *FakeInformer) Informer() cache.SharedIndexInformer { return f } -// HasSynced implements the Informer interface. Returns f.Synced +// HasSynced implements the Informer interface. Returns f.Synced. func (f *FakeInformer) HasSynced() bool { return f.Synced } @@ -61,26 +61,26 @@ func (f *FakeInformer) AddEventHandler(handler cache.ResourceEventHandler) { f.handlers = append(f.handlers, handler) } -// Run implements the Informer interface. Increments f.RunCount +// Run implements the Informer interface. Increments f.RunCount. func (f *FakeInformer) Run(<-chan struct{}) { f.RunCount++ } -// Add fakes an Add event for obj +// Add fakes an Add event for obj. func (f *FakeInformer) Add(obj metav1.Object) { for _, h := range f.handlers { h.OnAdd(obj) } } -// Update fakes an Update event for obj +// Update fakes an Update event for obj. func (f *FakeInformer) Update(oldObj, newObj metav1.Object) { for _, h := range f.handlers { h.OnUpdate(oldObj, newObj) } } -// Delete fakes an Delete event for obj +// Delete fakes an Delete event for obj. func (f *FakeInformer) Delete(obj metav1.Object) { for _, h := range f.handlers { h.OnDelete(obj) diff --git a/pkg/controller/controllerutil/controllerutil.go b/pkg/controller/controllerutil/controllerutil.go index f77d52052d..7863c3deec 100644 --- a/pkg/controller/controllerutil/controllerutil.go +++ b/pkg/controller/controllerutil/controllerutil.go @@ -22,7 +22,7 @@ import ( "reflect" "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" @@ -34,7 +34,7 @@ import ( // AlreadyOwnedError is an error returned if the object you are trying to assign // a controller reference is already owned by another controller Object is the -// subject and Owner is the reference for the current owner +// subject and Owner is the reference for the current owner. type AlreadyOwnedError struct { Object metav1.Object Owner metav1.OwnerReference @@ -44,10 +44,10 @@ func (e *AlreadyOwnedError) Error() string { return fmt.Sprintf("Object %s/%s is already owned by another %s controller %s", e.Object.GetNamespace(), e.Object.GetName(), e.Owner.Kind, e.Owner.Name) } -func newAlreadyOwnedError(Object metav1.Object, Owner metav1.OwnerReference) *AlreadyOwnedError { +func newAlreadyOwnedError(obj metav1.Object, owner metav1.OwnerReference) *AlreadyOwnedError { return &AlreadyOwnedError{ - Object: Object, - Owner: Owner, + Object: obj, + Owner: owner, } } @@ -118,13 +118,11 @@ func SetOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) erro // Update owner references and return. upsertOwnerRef(ref, object) return nil - } func upsertOwnerRef(ref metav1.OwnerReference, object metav1.Object) { owners := object.GetOwnerReferences() - idx := indexOwnerRef(owners, ref) - if idx == -1 { + if idx := indexOwnerRef(owners, ref); idx == -1 { owners = append(owners, ref) } else { owners[idx] = ref @@ -156,7 +154,7 @@ func validateOwner(owner, object metav1.Object) error { return nil } -// Returns true if a and b point to the same object +// Returns true if a and b point to the same object. func referSameObject(a, b metav1.OwnerReference) bool { aGV, err := schema.ParseGroupVersion(a.APIVersion) if err != nil { @@ -171,19 +169,19 @@ func referSameObject(a, b metav1.OwnerReference) bool { return aGV.Group == bGV.Group && a.Kind == b.Kind && a.Name == b.Name } -// OperationResult is the action result of a CreateOrUpdate call +// OperationResult is the action result of a CreateOrUpdate call. type OperationResult string const ( // They should complete the sentence "Deployment default/foo has been ..." - // OperationResultNone means that the resource has not been changed + // OperationResultNone means that the resource has not been changed. OperationResultNone OperationResult = "unchanged" - // OperationResultCreated means that a new resource is created + // OperationResultCreated means that a new resource is created. OperationResultCreated OperationResult = "created" - // OperationResultUpdated means that an existing resource is updated + // OperationResultUpdated means that an existing resource is updated. OperationResultUpdated OperationResult = "updated" - // OperationResultUpdatedStatus means that an existing resource and its status is updated + // OperationResultUpdatedStatus means that an existing resource and its status is updated. OperationResultUpdatedStatus OperationResult = "updatedStatus" - // OperationResultUpdatedStatusOnly means that only an existing status is updated + // OperationResultUpdatedStatusOnly means that only an existing status is updated. OperationResultUpdatedStatusOnly OperationResult = "updatedStatusOnly" ) @@ -197,7 +195,7 @@ const ( // They should complete the sentence "Deployment default/foo has been .. func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object, f MutateFn) (OperationResult, error) { key := client.ObjectKeyFromObject(obj) if err := c.Get(ctx, key, obj); err != nil { - if !errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return OperationResultNone, err } if err := mutate(f, key, obj); err != nil { @@ -209,7 +207,7 @@ func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object, f M return OperationResultCreated, nil } - existing := obj.DeepCopyObject() + existing := obj.DeepCopyObject() //nolint:ifshort if err := mutate(f, key, obj); err != nil { return OperationResultNone, err } @@ -234,7 +232,7 @@ func CreateOrUpdate(ctx context.Context, c client.Client, obj client.Object, f M func CreateOrPatch(ctx context.Context, c client.Client, obj client.Object, f MutateFn) (OperationResult, error) { key := client.ObjectKeyFromObject(obj) if err := c.Get(ctx, key, obj); err != nil { - if !errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return OperationResultNone, err } if f != nil { @@ -336,7 +334,7 @@ func CreateOrPatch(ctx context.Context, c client.Client, obj client.Object, f Mu return result, nil } -// mutate wraps a MutateFn and applies validation to its result +// mutate wraps a MutateFn and applies validation to its result. func mutate(f MutateFn, key client.ObjectKey, obj client.Object) error { if err := f(); err != nil { return err diff --git a/pkg/controller/controllerutil/controllerutil_test.go b/pkg/controller/controllerutil/controllerutil_test.go index 95228f9154..d47c691465 100644 --- a/pkg/controller/controllerutil/controllerutil_test.go +++ b/pkg/controller/controllerutil/controllerutil_test.go @@ -267,7 +267,7 @@ var _ = Describe("Controllerutil", func() { BeforeEach(func() { deploy = &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("deploy-%d", rand.Int31()), + Name: fmt.Sprintf("deploy-%d", rand.Int31()), //nolint:gosec Namespace: "default", }, } @@ -416,7 +416,7 @@ var _ = Describe("Controllerutil", func() { BeforeEach(func() { deploy = &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("deploy-%d", rand.Int31()), + Name: fmt.Sprintf("deploy-%d", rand.Int31()), //nolint:gosec Namespace: "default", }, } @@ -760,7 +760,6 @@ func deploymentNamespaceChanger(deploy *appsv1.Deployment) controllerutil.Mutate return func() error { deploy.Namespace = fmt.Sprintf("%s-1", deploy.Namespace) return nil - } } diff --git a/pkg/controller/controllerutil/example_test.go b/pkg/controller/controllerutil/example_test.go index 7670dd1852..b2d6f71a5c 100644 --- a/pkg/controller/controllerutil/example_test.go +++ b/pkg/controller/controllerutil/example_test.go @@ -31,7 +31,7 @@ var ( log = logf.Log.WithName("controllerutil-examples") ) -// This example creates or updates an existing deployment +// This example creates or updates an existing deployment. func ExampleCreateOrUpdate() { // c is client.Client @@ -39,7 +39,6 @@ func ExampleCreateOrUpdate() { deploy := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} op, err := controllerutil.CreateOrUpdate(context.TODO(), c, deploy, func() error { - // Deployment selector is immutable so we set this value only if // a new object is going to be created if deploy.ObjectMeta.CreationTimestamp.IsZero() { diff --git a/pkg/envtest/crd.go b/pkg/envtest/crd.go index e8eead0b67..2f2160d683 100644 --- a/pkg/envtest/crd.go +++ b/pkg/envtest/crd.go @@ -47,7 +47,7 @@ import ( "sigs.k8s.io/yaml" ) -// CRDInstallOptions are the options for installing CRDs +// CRDInstallOptions are the options for installing CRDs. type CRDInstallOptions struct { // Scheme is used to determine if conversion webhooks should be enabled // for a particular CRD / object. @@ -89,7 +89,7 @@ type CRDInstallOptions struct { const defaultPollInterval = 100 * time.Millisecond const defaultMaxWait = 10 * time.Second -// InstallCRDs installs a collection of CRDs into a cluster by reading the crd yaml files from a directory +// InstallCRDs installs a collection of CRDs into a cluster by reading the crd yaml files from a directory. func InstallCRDs(config *rest.Config, options CRDInstallOptions) ([]client.Object, error) { defaultCRDOptions(&options) @@ -115,7 +115,7 @@ func InstallCRDs(config *rest.Config, options CRDInstallOptions) ([]client.Objec return options.CRDs, nil } -// readCRDFiles reads the directories of CRDs in options.Paths and adds the CRD structs to options.CRDs +// readCRDFiles reads the directories of CRDs in options.Paths and adds the CRD structs to options.CRDs. func readCRDFiles(options *CRDInstallOptions) error { if len(options.Paths) > 0 { crdList, err := renderCRDs(options) @@ -128,7 +128,7 @@ func readCRDFiles(options *CRDInstallOptions) error { return nil } -// defaultCRDOptions sets the default values for CRDs +// defaultCRDOptions sets the default values for CRDs. func defaultCRDOptions(o *CRDInstallOptions) { if o.Scheme == nil { o.Scheme = scheme.Scheme @@ -141,7 +141,7 @@ func defaultCRDOptions(o *CRDInstallOptions) { } } -// WaitForCRDs waits for the CRDs to appear in discovery +// WaitForCRDs waits for the CRDs to appear in discovery. func WaitForCRDs(config *rest.Config, crds []client.Object, options CRDInstallOptions) error { // Add each CRD to a map of GroupVersion to Resource waitingFor := map[schema.GroupVersion]*sets.String{} @@ -204,7 +204,7 @@ func WaitForCRDs(config *rest.Config, crds []client.Object, options CRDInstallOp return wait.PollImmediate(options.PollInterval, options.MaxTime, p.poll) } -// poller checks if all the resources have been found in discovery, and returns false if not +// poller checks if all the resources have been found in discovery, and returns false if not. type poller struct { // config is used to get discovery config *rest.Config @@ -213,7 +213,7 @@ type poller struct { waitingFor map[schema.GroupVersion]*sets.String } -// poll checks if all the resources have been found in discovery, and returns false if not +// poll checks if all the resources have been found in discovery, and returns false if not. func (p *poller) poll() (done bool, err error) { // Create a new clientset to avoid any client caching of discovery cs, err := clientset.NewForConfig(p.config) @@ -233,7 +233,7 @@ func (p *poller) poll() (done bool, err error) { // TODO: Maybe the controller-runtime client should be able to do this... resourceList, err := cs.Discovery().ServerResourcesForGroupVersion(gv.Group + "/" + gv.Version) if err != nil { - return false, nil + return false, nil //nolint:nilerr } // Remove each found resource from the resources set that we are waiting for @@ -249,9 +249,8 @@ func (p *poller) poll() (done bool, err error) { return allFound, nil } -// UninstallCRDs uninstalls a collection of CRDs by reading the crd yaml files from a directory +// UninstallCRDs uninstalls a collection of CRDs by reading the crd yaml files from a directory. func UninstallCRDs(config *rest.Config, options CRDInstallOptions) error { - // Read the CRD yamls into options.CRDs if err := readCRDFiles(&options); err != nil { return err @@ -277,7 +276,7 @@ func UninstallCRDs(config *rest.Config, options CRDInstallOptions) error { return nil } -// CreateCRDs creates the CRDs +// CreateCRDs creates the CRDs. func CreateCRDs(config *rest.Config, crds []client.Object) error { cs, err := client.New(config, client.Options{}) if err != nil { @@ -340,10 +339,8 @@ func renderCRDs(options *CRDInstallOptions) ([]client.Object, error) { if !info.IsDir() { filePath, files = filepath.Dir(path), []os.FileInfo{info} - } else { - if files, err = ioutil.ReadDir(path); err != nil { - return nil, err - } + } else if files, err = ioutil.ReadDir(path); err != nil { + return nil, err } log.V(1).Info("reading CRDs from path", "path", path) @@ -364,7 +361,7 @@ func renderCRDs(options *CRDInstallOptions) ([]client.Object, error) { } // Converting map to a list to return - var res []client.Object + res := []client.Object{} for _, obj := range crds { res = append(res, obj) } @@ -557,7 +554,7 @@ func modifyConversionWebhooks(crds []client.Object, scheme *runtime.Scheme, webh return nil } -// readCRDs reads the CRDs from files and Unmarshals them into structs +// readCRDs reads the CRDs from files and Unmarshals them into structs. func readCRDs(basePath string, files []os.FileInfo) ([]*unstructured.Unstructured, error) { var crds []*unstructured.Unstructured @@ -603,9 +600,9 @@ func readCRDs(basePath string, files []os.FileInfo) ([]*unstructured.Unstructure return crds, nil } -// readDocuments reads documents from file +// readDocuments reads documents from file. func readDocuments(fp string) ([][]byte, error) { - b, err := ioutil.ReadFile(fp) + b, err := ioutil.ReadFile(fp) //nolint:gosec if err != nil { return nil, err } diff --git a/pkg/envtest/printer/ginkgo.go b/pkg/envtest/printer/ginkgo.go index 1435a1a435..d835dc7721 100644 --- a/pkg/envtest/printer/ginkgo.go +++ b/pkg/envtest/printer/ginkgo.go @@ -33,21 +33,21 @@ var _ ginkgo.Reporter = NewlineReporter{} // See issue https://github.com/jstemmer/go-junit-report/issues/31 type NewlineReporter struct{} -// SpecSuiteWillBegin implements ginkgo.Reporter +// SpecSuiteWillBegin implements ginkgo.Reporter. func (NewlineReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { } -// BeforeSuiteDidRun implements ginkgo.Reporter +// BeforeSuiteDidRun implements ginkgo.Reporter. func (NewlineReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {} -// AfterSuiteDidRun implements ginkgo.Reporter +// AfterSuiteDidRun implements ginkgo.Reporter. func (NewlineReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {} -// SpecWillRun implements ginkgo.Reporter +// SpecWillRun implements ginkgo.Reporter. func (NewlineReporter) SpecWillRun(specSummary *types.SpecSummary) {} -// SpecDidComplete implements ginkgo.Reporter +// SpecDidComplete implements ginkgo.Reporter. func (NewlineReporter) SpecDidComplete(specSummary *types.SpecSummary) {} -// SpecSuiteDidEnd Prints a newline between "35 Passed | 0 Failed | 0 Pending | 0 Skipped" and "--- PASS:" +// SpecSuiteDidEnd Prints a newline between "35 Passed | 0 Failed | 0 Pending | 0 Skipped" and "--- PASS:". func (NewlineReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { fmt.Printf("\n") } diff --git a/pkg/envtest/printer/prow.go b/pkg/envtest/printer/prow.go index 5a586b3250..2f4009aa03 100644 --- a/pkg/envtest/printer/prow.go +++ b/pkg/envtest/printer/prow.go @@ -73,35 +73,35 @@ func (pr *prowReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summa } } -// BeforeSuiteDidRun implements ginkgo.Reporter +// BeforeSuiteDidRun implements ginkgo.Reporter. func (pr *prowReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { if pr.junitReporter != nil { pr.junitReporter.BeforeSuiteDidRun(setupSummary) } } -// AfterSuiteDidRun implements ginkgo.Reporter +// AfterSuiteDidRun implements ginkgo.Reporter. func (pr *prowReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { if pr.junitReporter != nil { pr.junitReporter.AfterSuiteDidRun(setupSummary) } } -// SpecWillRun implements ginkgo.Reporter +// SpecWillRun implements ginkgo.Reporter. func (pr *prowReporter) SpecWillRun(specSummary *types.SpecSummary) { if pr.junitReporter != nil { pr.junitReporter.SpecWillRun(specSummary) } } -// SpecDidComplete implements ginkgo.Reporter +// SpecDidComplete implements ginkgo.Reporter. func (pr *prowReporter) SpecDidComplete(specSummary *types.SpecSummary) { if pr.junitReporter != nil { pr.junitReporter.SpecDidComplete(specSummary) } } -// SpecSuiteDidEnd Prints a newline between "35 Passed | 0 Failed | 0 Pending | 0 Skipped" and "--- PASS:" +// SpecSuiteDidEnd Prints a newline between "35 Passed | 0 Failed | 0 Pending | 0 Skipped" and "--- PASS:". func (pr *prowReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { if pr.junitReporter != nil { pr.junitReporter.SpecSuiteDidEnd(summary) diff --git a/pkg/envtest/server.go b/pkg/envtest/server.go index d53706f453..967e3060ed 100644 --- a/pkg/envtest/server.go +++ b/pkg/envtest/server.go @@ -59,15 +59,15 @@ const ( defaultKubebuilderControlPlaneStopTimeout = 20 * time.Second ) -// internal types we expose as part of our public API +// internal types we expose as part of our public API. type ( - // ControlPlane is the re-exported ControlPlane type from the internal testing package + // ControlPlane is the re-exported ControlPlane type from the internal testing package. ControlPlane = controlplane.ControlPlane - // APIServer is the re-exported APIServer from the internal testing package + // APIServer is the re-exported APIServer from the internal testing package. APIServer = controlplane.APIServer - // Etcd is the re-exported Etcd from the internal testing package + // Etcd is the re-exported Etcd from the internal testing package. Etcd = controlplane.Etcd // User represents a Kubernetes user to provision for auth purposes. @@ -103,7 +103,7 @@ var ( ) // Environment creates a Kubernetes test environment that will start / stop the Kubernetes control plane and -// install extension APIs +// install extension APIs. type Environment struct { // ControlPlane is the ControlPlane including the apiserver and etcd ControlPlane controlplane.ControlPlane @@ -194,7 +194,7 @@ func (te *Environment) Stop() error { return te.ControlPlane.Stop() } -// Start starts a local Kubernetes server and updates te.ApiserverPort with the port it is listening on +// Start starts a local Kubernetes server and updates te.ApiserverPort with the port it is listening on. func (te *Environment) Start() (*rest.Config, error) { if te.useExistingCluster() { log.V(1).Info("using existing cluster") @@ -211,7 +211,7 @@ func (te *Environment) Start() (*rest.Config, error) { } } else { apiServer := te.ControlPlane.GetAPIServer() - if len(apiServer.Args) == 0 { + if len(apiServer.Args) == 0 { //nolint:staticcheck // pass these through separately from above in case something like // AddUser defaults APIServer. // @@ -222,7 +222,7 @@ func (te *Environment) Start() (*rest.Config, error) { // NB(directxman12): we still pass these in so that things work if the // user manually specifies them, but in most cases we expect them to // be nil so that we use the new .Configure() logic. - apiServer.Args = te.KubeAPIServerFlags + apiServer.Args = te.KubeAPIServerFlags //nolint:staticcheck } if te.ControlPlane.Etcd == nil { te.ControlPlane.Etcd = &controlplane.Etcd{} @@ -256,7 +256,7 @@ func (te *Environment) Start() (*rest.Config, error) { apiServer.StartTimeout = te.ControlPlaneStartTimeout apiServer.StopTimeout = te.ControlPlaneStopTimeout - log.V(1).Info("starting control plane", "api server flags", apiServer.Args) + log.V(1).Info("starting control plane") if err := te.startControlPlane(); err != nil { return nil, fmt.Errorf("unable to start control plane itself: %w", err) } @@ -372,4 +372,4 @@ func (te *Environment) useExistingCluster() bool { // you can use those to append your own additional arguments. // // Deprecated: use APIServer.Configure() instead. -var DefaultKubeAPIServerFlags = controlplane.APIServerDefaultArgs +var DefaultKubeAPIServerFlags = controlplane.APIServerDefaultArgs //nolint:staticcheck diff --git a/pkg/envtest/webhook.go b/pkg/envtest/webhook.go index ad9fe0dbc2..567f732e41 100644 --- a/pkg/envtest/webhook.go +++ b/pkg/envtest/webhook.go @@ -23,7 +23,6 @@ import ( "path/filepath" "time" - "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -38,7 +37,7 @@ import ( "sigs.k8s.io/yaml" ) -// WebhookInstallOptions are the options for installing mutating or validating webhooks +// WebhookInstallOptions are the options for installing mutating or validating webhooks. type WebhookInstallOptions struct { // Paths is a list of paths to the directories or files containing the mutating or validating webhooks yaml or json configs. Paths []string @@ -79,7 +78,7 @@ type WebhookInstallOptions struct { // ModifyWebhookDefinitions modifies webhook definitions by: // - applying CABundle based on the provided tinyca -// - if webhook client config uses service spec, it's removed and replaced with direct url +// - if webhook client config uses service spec, it's removed and replaced with direct url. func (o *WebhookInstallOptions) ModifyWebhookDefinitions() error { caData := o.LocalServingCAData @@ -172,14 +171,10 @@ func (o *WebhookInstallOptions) PrepWithoutInstalling() error { return err } - if err := o.ModifyWebhookDefinitions(); err != nil { - return err - } - - return nil + return o.ModifyWebhookDefinitions() } -// Install installs specified webhooks to the API server +// Install installs specified webhooks to the API server. func (o *WebhookInstallOptions) Install(config *rest.Config) error { if len(o.LocalServingCAData) == 0 { if err := o.PrepWithoutInstalling(); err != nil { @@ -191,14 +186,10 @@ func (o *WebhookInstallOptions) Install(config *rest.Config) error { return err } - if err := WaitForWebhooks(config, o.MutatingWebhooks, o.ValidatingWebhooks, *o); err != nil { - return err - } - - return nil + return WaitForWebhooks(config, o.MutatingWebhooks, o.ValidatingWebhooks, *o) } -// Cleanup cleans up cert directories +// Cleanup cleans up cert directories. func (o *WebhookInstallOptions) Cleanup() error { if o.LocalServingCertDir != "" { return os.RemoveAll(o.LocalServingCertDir) @@ -206,12 +197,11 @@ func (o *WebhookInstallOptions) Cleanup() error { return nil } -// WaitForWebhooks waits for the Webhooks to be available through API server +// WaitForWebhooks waits for the Webhooks to be available through API server. func WaitForWebhooks(config *rest.Config, mutatingWebhooks []client.Object, validatingWebhooks []client.Object, options WebhookInstallOptions) error { - waitingFor := map[schema.GroupVersionKind]*sets.String{} for _, hook := range runtimeListToUnstructured(append(validatingWebhooks, mutatingWebhooks...)) { @@ -226,7 +216,7 @@ func WaitForWebhooks(config *rest.Config, return wait.PollImmediate(options.PollInterval, options.MaxTime, p.poll) } -// poller checks if all the resources have been found in discovery, and returns false if not +// poller checks if all the resources have been found in discovery, and returns false if not. type webhookPoller struct { // config is used to get discovery config *rest.Config @@ -235,7 +225,7 @@ type webhookPoller struct { waitingFor map[schema.GroupVersionKind]*sets.String } -// poll checks if all the resources have been found in discovery, and returns false if not +// poll checks if all the resources have been found in discovery, and returns false if not. func (p *webhookPoller) poll() (done bool, err error) { // Create a new clientset to avoid any client caching of discovery c, err := client.New(p.config, client.Options{}) @@ -261,7 +251,7 @@ func (p *webhookPoller) poll() (done bool, err error) { names.Delete(name) } - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { allFound = false } if err != nil { @@ -272,7 +262,7 @@ func (p *webhookPoller) poll() (done bool, err error) { return allFound, nil } -// setupCA creates CA for testing and writes them to disk +// setupCA creates CA for testing and writes them to disk. func (o *WebhookInstallOptions) setupCA() error { hookCA, err := certs.NewTinyCA() if err != nil { @@ -296,10 +286,10 @@ func (o *WebhookInstallOptions) setupCA() error { return fmt.Errorf("unable to marshal webhook serving certs: %v", err) } - if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.crt"), certData, 0640); err != nil { + if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.crt"), certData, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to write webhook serving cert to disk: %v", err) } - if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.key"), keyData, 0640); err != nil { + if err := ioutil.WriteFile(filepath.Join(localServingCertsDir, "tls.key"), keyData, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to write webhook serving key to disk: %v", err) } @@ -329,7 +319,7 @@ func createWebhooks(config *rest.Config, mutHooks []client.Object, valHooks []cl return nil } -// ensureCreated creates or update object if already exists in the cluster +// ensureCreated creates or update object if already exists in the cluster. func ensureCreated(cs client.Client, obj *unstructured.Unstructured) error { existing := obj.DeepCopy() err := cs.Get(context.Background(), client.ObjectKey{Name: obj.GetName()}, existing) @@ -350,7 +340,7 @@ func ensureCreated(cs client.Client, obj *unstructured.Unstructured) error { return nil } -// parseWebhook reads the directories or files of Webhooks in options.Paths and adds the Webhook structs to options +// parseWebhook reads the directories or files of Webhooks in options.Paths and adds the Webhook structs to options. func parseWebhook(options *WebhookInstallOptions) error { if len(options.Paths) > 0 { for _, path := range options.Paths { @@ -373,7 +363,7 @@ func parseWebhook(options *WebhookInstallOptions) error { } // readWebhooks reads the Webhooks from files and Unmarshals them into structs -// returns slice of mutating and validating webhook configurations +// returns slice of mutating and validating webhook configurations. func readWebhooks(path string) ([]client.Object, []client.Object, error) { // Get the webhook files var files []os.FileInfo @@ -385,10 +375,8 @@ func readWebhooks(path string) ([]client.Object, []client.Object, error) { } if !info.IsDir() { path, files = filepath.Dir(path), []os.FileInfo{info} - } else { - if files, err = ioutil.ReadDir(path); err != nil { - return nil, nil, err - } + } else if files, err = ioutil.ReadDir(path); err != nil { + return nil, nil, err } // file extensions that may contain Webhooks diff --git a/pkg/envtest/webhook_test.go b/pkg/envtest/webhook_test.go index d6c9ab0f14..97080f288c 100644 --- a/pkg/envtest/webhook_test.go +++ b/pkg/envtest/webhook_test.go @@ -18,7 +18,6 @@ package envtest import ( "context" - "fmt" "path/filepath" "time" @@ -26,7 +25,7 @@ import ( . "github.com/onsi/gomega" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" @@ -84,7 +83,7 @@ var _ = Describe("Test", func() { Eventually(func() bool { err = c.Create(context.TODO(), obj) - return errors.ReasonForError(err) == metav1.StatusReason("Always denied") + return apierrors.ReasonForError(err) == metav1.StatusReason("Always denied") }, 1*time.Second).Should(BeTrue()) cancel() @@ -117,5 +116,5 @@ type rejectingValidator struct { } func (v *rejectingValidator) Handle(_ context.Context, _ admission.Request) admission.Response { - return admission.Denied(fmt.Sprint("Always denied")) + return admission.Denied("Always denied") } diff --git a/pkg/finalizer/finalizer.go b/pkg/finalizer/finalizer.go index 1261b73994..1f627f8c49 100644 --- a/pkg/finalizer/finalizer.go +++ b/pkg/finalizer/finalizer.go @@ -17,7 +17,7 @@ import ( "context" "fmt" - utilerrors "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) @@ -34,7 +34,7 @@ type Result struct { StatusUpdated bool } -// NewFinalizers returns the Finalizers interface +// NewFinalizers returns the Finalizers interface. func NewFinalizers() Finalizers { return finalizers{} } @@ -75,5 +75,5 @@ func (f finalizers) Finalize(ctx context.Context, obj client.Object) (Result, er } } } - return res, utilerrors.NewAggregate(errList) + return res, kerrors.NewAggregate(errList) } diff --git a/pkg/finalizer/types.go b/pkg/finalizer/types.go index 29d3d1dcc9..e3a002a935 100644 --- a/pkg/finalizer/types.go +++ b/pkg/finalizer/types.go @@ -21,21 +21,21 @@ import ( // Registerer holds Register that will check if a key is already registered // and error out and it does; and if not registered, it will add the finalizer -// to the finalizers map as the value for the provided key +// to the finalizers map as the value for the provided key. type Registerer interface { Register(key string, f Finalizer) error } // Finalizer holds Finalize that will add/remove a finalizer based on the // deletion timestamp being set and return an indication of whether the -// obj needs an update or not +// obj needs an update or not. type Finalizer interface { Finalize(context.Context, client.Object) (Result, error) } // Finalizers implements Registerer and Finalizer to finalize all registered // finalizers if the provided object has a deletion timestamp or set all -// registered finalizers if it does not +// registered finalizers if it does not. type Finalizers interface { Registerer Finalizer diff --git a/pkg/handler/enqueue.go b/pkg/handler/enqueue.go index fb8987cfe9..e6d3a4eaab 100644 --- a/pkg/handler/enqueue.go +++ b/pkg/handler/enqueue.go @@ -35,7 +35,7 @@ var _ EventHandler = &EnqueueRequestForObject{} // Controllers that have associated Resources (e.g. CRDs) to reconcile the associated Resource. type EnqueueRequestForObject struct{} -// Create implements EventHandler +// Create implements EventHandler. func (e *EnqueueRequestForObject) Create(evt event.CreateEvent, q workqueue.RateLimitingInterface) { if evt.Object == nil { enqueueLog.Error(nil, "CreateEvent received with no metadata", "event", evt) @@ -47,24 +47,25 @@ func (e *EnqueueRequestForObject) Create(evt event.CreateEvent, q workqueue.Rate }}) } -// Update implements EventHandler +// Update implements EventHandler. func (e *EnqueueRequestForObject) Update(evt event.UpdateEvent, q workqueue.RateLimitingInterface) { - if evt.ObjectNew != nil { + switch { + case evt.ObjectNew != nil: q.Add(reconcile.Request{NamespacedName: types.NamespacedName{ Name: evt.ObjectNew.GetName(), Namespace: evt.ObjectNew.GetNamespace(), }}) - } else if evt.ObjectOld != nil { + case evt.ObjectOld != nil: q.Add(reconcile.Request{NamespacedName: types.NamespacedName{ Name: evt.ObjectOld.GetName(), Namespace: evt.ObjectOld.GetNamespace(), }}) - } else { + default: enqueueLog.Error(nil, "UpdateEvent received with no metadata", "event", evt) } } -// Delete implements EventHandler +// Delete implements EventHandler. func (e *EnqueueRequestForObject) Delete(evt event.DeleteEvent, q workqueue.RateLimitingInterface) { if evt.Object == nil { enqueueLog.Error(nil, "DeleteEvent received with no metadata", "event", evt) @@ -76,7 +77,7 @@ func (e *EnqueueRequestForObject) Delete(evt event.DeleteEvent, q workqueue.Rate }}) } -// Generic implements EventHandler +// Generic implements EventHandler. func (e *EnqueueRequestForObject) Generic(evt event.GenericEvent, q workqueue.RateLimitingInterface) { if evt.Object == nil { enqueueLog.Error(nil, "GenericEvent received with no metadata", "event", evt) diff --git a/pkg/handler/enqueue_mapped.go b/pkg/handler/enqueue_mapped.go index 585c21e718..17401b1fdb 100644 --- a/pkg/handler/enqueue_mapped.go +++ b/pkg/handler/enqueue_mapped.go @@ -51,26 +51,26 @@ type enqueueRequestsFromMapFunc struct { toRequests MapFunc } -// Create implements EventHandler +// Create implements EventHandler. func (e *enqueueRequestsFromMapFunc) Create(evt event.CreateEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.mapAndEnqueue(q, evt.Object, reqs) } -// Update implements EventHandler +// Update implements EventHandler. func (e *enqueueRequestsFromMapFunc) Update(evt event.UpdateEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.mapAndEnqueue(q, evt.ObjectOld, reqs) e.mapAndEnqueue(q, evt.ObjectNew, reqs) } -// Delete implements EventHandler +// Delete implements EventHandler. func (e *enqueueRequestsFromMapFunc) Delete(evt event.DeleteEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.mapAndEnqueue(q, evt.Object, reqs) } -// Generic implements EventHandler +// Generic implements EventHandler. func (e *enqueueRequestsFromMapFunc) Generic(evt event.GenericEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.mapAndEnqueue(q, evt.Object, reqs) diff --git a/pkg/handler/enqueue_owner.go b/pkg/handler/enqueue_owner.go index 8aa4ec52b2..63699893fc 100644 --- a/pkg/handler/enqueue_owner.go +++ b/pkg/handler/enqueue_owner.go @@ -57,7 +57,7 @@ type EnqueueRequestForOwner struct { mapper meta.RESTMapper } -// Create implements EventHandler +// Create implements EventHandler. func (e *EnqueueRequestForOwner) Create(evt event.CreateEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.getOwnerReconcileRequest(evt.Object, reqs) @@ -66,7 +66,7 @@ func (e *EnqueueRequestForOwner) Create(evt event.CreateEvent, q workqueue.RateL } } -// Update implements EventHandler +// Update implements EventHandler. func (e *EnqueueRequestForOwner) Update(evt event.UpdateEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.getOwnerReconcileRequest(evt.ObjectOld, reqs) @@ -76,7 +76,7 @@ func (e *EnqueueRequestForOwner) Update(evt event.UpdateEvent, q workqueue.RateL } } -// Delete implements EventHandler +// Delete implements EventHandler. func (e *EnqueueRequestForOwner) Delete(evt event.DeleteEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.getOwnerReconcileRequest(evt.Object, reqs) @@ -85,7 +85,7 @@ func (e *EnqueueRequestForOwner) Delete(evt event.DeleteEvent, q workqueue.RateL } } -// Generic implements EventHandler +// Generic implements EventHandler. func (e *EnqueueRequestForOwner) Generic(evt event.GenericEvent, q workqueue.RateLimitingInterface) { reqs := map[reconcile.Request]empty{} e.getOwnerReconcileRequest(evt.Object, reqs) @@ -105,10 +105,9 @@ func (e *EnqueueRequestForOwner) parseOwnerTypeGroupKind(scheme *runtime.Scheme) } // Expect only 1 kind. If there is more than one kind this is probably an edge case such as ListOptions. if len(kinds) != 1 { - err := fmt.Errorf("Expected exactly 1 kind for OwnerType %T, but found %s kinds", e.OwnerType, kinds) - log.Error(nil, "Expected exactly 1 kind for OwnerType", "owner type", fmt.Sprintf("%T", e.OwnerType), "kinds", kinds) + err := fmt.Errorf("expected exactly 1 kind for OwnerType %T, but found %s kinds", e.OwnerType, kinds) + log.Error(nil, "expected exactly 1 kind for OwnerType", "owner type", fmt.Sprintf("%T", e.OwnerType), "kinds", kinds) return err - } // Cache the Group and Kind for the OwnerType e.groupKind = schema.GroupKind{Group: kinds[0].Group, Kind: kinds[0].Kind} @@ -156,7 +155,7 @@ func (e *EnqueueRequestForOwner) getOwnerReconcileRequest(object metav1.Object, // getOwnersReferences returns the OwnerReferences for an object as specified by the EnqueueRequestForOwner // - if IsController is true: only take the Controller OwnerReference (if found) -// - if IsController is false: take all OwnerReferences +// - if IsController is false: take all OwnerReferences. func (e *EnqueueRequestForOwner) getOwnersReferences(object metav1.Object) []metav1.OwnerReference { if object == nil { return nil diff --git a/pkg/handler/eventhandler.go b/pkg/handler/eventhandler.go index c9b93f8b97..8652d22d72 100644 --- a/pkg/handler/eventhandler.go +++ b/pkg/handler/eventhandler.go @@ -75,28 +75,28 @@ type Funcs struct { GenericFunc func(event.GenericEvent, workqueue.RateLimitingInterface) } -// Create implements EventHandler +// Create implements EventHandler. func (h Funcs) Create(e event.CreateEvent, q workqueue.RateLimitingInterface) { if h.CreateFunc != nil { h.CreateFunc(e, q) } } -// Delete implements EventHandler +// Delete implements EventHandler. func (h Funcs) Delete(e event.DeleteEvent, q workqueue.RateLimitingInterface) { if h.DeleteFunc != nil { h.DeleteFunc(e, q) } } -// Update implements EventHandler +// Update implements EventHandler. func (h Funcs) Update(e event.UpdateEvent, q workqueue.RateLimitingInterface) { if h.UpdateFunc != nil { h.UpdateFunc(e, q) } } -// Generic implements EventHandler +// Generic implements EventHandler. func (h Funcs) Generic(e event.GenericEvent, q workqueue.RateLimitingInterface) { if h.GenericFunc != nil { h.GenericFunc(e, q) diff --git a/pkg/healthz/healthz.go b/pkg/healthz/healthz.go index e7f4b1c279..bd1cc151af 100644 --- a/pkg/healthz/healthz.go +++ b/pkg/healthz/healthz.go @@ -35,7 +35,7 @@ type Handler struct { Checks map[string]Checker } -// checkStatus holds the output of a particular check +// checkStatus holds the output of a particular check. type checkStatus struct { name string healthy bool @@ -173,8 +173,7 @@ type CheckHandler struct { } func (h CheckHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { - err := h.Checker(req) - if err != nil { + if err := h.Checker(req); err != nil { http.Error(resp, fmt.Sprintf("internal server error: %v", err), http.StatusInternalServerError) } else { fmt.Fprint(resp, "ok") @@ -184,10 +183,10 @@ func (h CheckHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { // Checker knows how to perform a health check. type Checker func(req *http.Request) error -// Ping returns true automatically when checked +// Ping returns true automatically when checked. var Ping Checker = func(_ *http.Request) error { return nil } -// getExcludedChecks extracts the health check names to be excluded from the query param +// getExcludedChecks extracts the health check names to be excluded from the query param. func getExcludedChecks(r *http.Request) sets.String { checks, found := r.URL.Query()["exclude"] if found { diff --git a/pkg/internal/controller/controller.go b/pkg/internal/controller/controller.go index f5024502d9..224d300b89 100644 --- a/pkg/internal/controller/controller.go +++ b/pkg/internal/controller/controller.go @@ -37,7 +37,7 @@ import ( var _ inject.Injector = &Controller{} -// Controller implements controller.Controller +// Controller implements controller.Controller. type Controller struct { // Name is used to uniquely identify a Controller in tracing, logging and monitoring. Name is required. Name string @@ -94,14 +94,14 @@ type watchDescription struct { predicates []predicate.Predicate } -// Reconcile implements reconcile.Reconciler +// Reconcile implements reconcile.Reconciler. func (c *Controller) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { log := c.Log.WithValues("name", req.Name, "namespace", req.Namespace) ctx = logf.IntoContext(ctx, log) return c.Do.Reconcile(ctx, req) } -// Watch implements controller.Controller +// Watch implements controller.Controller. func (c *Controller) Watch(src source.Source, evthdler handler.EventHandler, prct ...predicate.Predicate) error { c.mu.Lock() defer c.mu.Unlock() @@ -131,7 +131,7 @@ func (c *Controller) Watch(src source.Source, evthdler handler.EventHandler, prc return src.Start(c.ctx, evthdler, c.Queue, prct...) } -// Start implements controller.Controller +// Start implements controller.Controller. func (c *Controller) Start(ctx context.Context) error { // use an IIFE to get proper lock handling // but lock outside to get proper handling of the queue shutdown @@ -295,13 +295,14 @@ func (c *Controller) reconcileHandler(ctx context.Context, obj interface{}) { // RunInformersAndControllers the syncHandler, passing it the Namespace/Name string of the // resource to be synced. - if result, err := c.Do.Reconcile(ctx, req); err != nil { + result, err := c.Do.Reconcile(ctx, req) + switch { + case err != nil: c.Queue.AddRateLimited(req) ctrlmetrics.ReconcileErrors.WithLabelValues(c.Name).Inc() ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelError).Inc() log.Error(err, "Reconciler error") - return - } else if result.RequeueAfter > 0 { + case result.RequeueAfter > 0: // The result.RequeueAfter request will be lost, if it is returned // along with a non-nil error. But this is intended as // We need to drive to stable reconcile loops before queuing due @@ -309,18 +310,15 @@ func (c *Controller) reconcileHandler(ctx context.Context, obj interface{}) { c.Queue.Forget(obj) c.Queue.AddAfter(req, result.RequeueAfter) ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelRequeueAfter).Inc() - return - } else if result.Requeue { + case result.Requeue: c.Queue.AddRateLimited(req) ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelRequeue).Inc() - return + default: + // Finally, if no error occurs we Forget this item so it does not + // get queued again until another change happens. + c.Queue.Forget(obj) + ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelSuccess).Inc() } - - // Finally, if no error occurs we Forget this item so it does not - // get queued again until another change happens. - c.Queue.Forget(obj) - - ctrlmetrics.ReconcileTotal.WithLabelValues(c.Name, labelSuccess).Inc() } // GetLogger returns this controller's logger. @@ -328,13 +326,13 @@ func (c *Controller) GetLogger() logr.Logger { return c.Log } -// InjectFunc implement SetFields.Injector +// InjectFunc implement SetFields.Injector. func (c *Controller) InjectFunc(f inject.Func) error { c.SetFields = f return nil } -// updateMetrics updates prometheus metrics within the controller +// updateMetrics updates prometheus metrics within the controller. func (c *Controller) updateMetrics(reconcileTime time.Duration) { ctrlmetrics.ReconcileTime.WithLabelValues(c.Name).Observe(reconcileTime.Seconds()) } diff --git a/pkg/internal/controller/metrics/metrics.go b/pkg/internal/controller/metrics/metrics.go index 126ded6609..baec669277 100644 --- a/pkg/internal/controller/metrics/metrics.go +++ b/pkg/internal/controller/metrics/metrics.go @@ -18,6 +18,7 @@ package metrics import ( "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" "sigs.k8s.io/controller-runtime/pkg/metrics" ) @@ -25,21 +26,21 @@ var ( // ReconcileTotal is a prometheus counter metrics which holds the total // number of reconciliations per controller. It has two labels. controller label refers // to the controller name and result label refers to the reconcile result i.e - // success, error, requeue, requeue_after + // success, error, requeue, requeue_after. ReconcileTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "controller_runtime_reconcile_total", Help: "Total number of reconciliations per controller", }, []string{"controller", "result"}) // ReconcileErrors is a prometheus counter metrics which holds the total - // number of errors from the Reconciler + // number of errors from the Reconciler. ReconcileErrors = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "controller_runtime_reconcile_errors_total", Help: "Total number of reconciliation errors per controller", }, []string{"controller"}) // ReconcileTime is a prometheus metric which keeps track of the duration - // of reconciliations + // of reconciliations. ReconcileTime = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "controller_runtime_reconcile_time_seconds", Help: "Length of time per reconciliation per controller", @@ -48,14 +49,14 @@ var ( }, []string{"controller"}) // WorkerCount is a prometheus metric which holds the number of - // concurrent reconciles per controller + // concurrent reconciles per controller. WorkerCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "controller_runtime_max_concurrent_reconciles", Help: "Maximum number of concurrent reconciles per controller", }, []string{"controller"}) // ActiveWorkers is a prometheus metric which holds the number - // of active workers per controller + // of active workers per controller. ActiveWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "controller_runtime_active_workers", Help: "Number of currently used workers per controller", @@ -70,8 +71,8 @@ func init() { WorkerCount, ActiveWorkers, // expose process metrics like CPU, Memory, file descriptor usage etc. - prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}), + collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), // expose Go runtime metrics like GC stats, memory stats etc. - prometheus.NewGoCollector(), + collectors.NewGoCollector(), ) } diff --git a/pkg/internal/objectutil/objectutil.go b/pkg/internal/objectutil/objectutil.go index 5264da3cc1..7057f3dbe4 100644 --- a/pkg/internal/objectutil/objectutil.go +++ b/pkg/internal/objectutil/objectutil.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" - "k8s.io/apimachinery/pkg/api/meta" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -28,7 +27,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) -// FilterWithLabels returns a copy of the items in objs matching labelSel +// FilterWithLabels returns a copy of the items in objs matching labelSel. func FilterWithLabels(objs []runtime.Object, labelSel labels.Selector) ([]runtime.Object, error) { outItems := make([]runtime.Object, 0, len(objs)) for _, obj := range objs { @@ -69,10 +68,10 @@ func IsAPINamespacedWithGVK(gk schema.GroupVersionKind, scheme *runtime.Scheme, scope := restmapping.Scope.Name() if scope == "" { - return false, errors.New("Scope cannot be identified. Empty scope returned") + return false, errors.New("scope cannot be identified, empty scope returned") } - if scope != meta.RESTScopeNameRoot { + if scope != apimeta.RESTScopeNameRoot { return true, nil } return false, nil diff --git a/pkg/internal/recorder/recorder_test.go b/pkg/internal/recorder/recorder_test.go index 5da3f0ce04..ea7aaf8d43 100644 --- a/pkg/internal/recorder/recorder_test.go +++ b/pkg/internal/recorder/recorder_test.go @@ -17,7 +17,7 @@ limitations under the License. package recorder_test import ( - tlog "github.com/go-logr/logr/testing" + "github.com/go-logr/logr" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "k8s.io/client-go/kubernetes/scheme" @@ -29,7 +29,7 @@ var _ = Describe("recorder.Provider", func() { makeBroadcaster := func() (record.EventBroadcaster, bool) { return record.NewBroadcaster(), true } Describe("NewProvider", func() { It("should return a provider instance and a nil error.", func() { - provider, err := recorder.NewProvider(cfg, scheme.Scheme, tlog.NullLogger{}, makeBroadcaster) + provider, err := recorder.NewProvider(cfg, scheme.Scheme, logr.DiscardLogger{}, makeBroadcaster) Expect(provider).NotTo(BeNil()) Expect(err).NotTo(HaveOccurred()) }) @@ -38,14 +38,14 @@ var _ = Describe("recorder.Provider", func() { // Invalid the config cfg1 := *cfg cfg1.Host = "invalid host" - _, err := recorder.NewProvider(&cfg1, scheme.Scheme, tlog.NullLogger{}, makeBroadcaster) + _, err := recorder.NewProvider(&cfg1, scheme.Scheme, logr.DiscardLogger{}, makeBroadcaster) Expect(err).NotTo(BeNil()) Expect(err.Error()).To(ContainSubstring("failed to init clientSet")) }) }) Describe("GetEventRecorder", func() { It("should return a recorder instance.", func() { - provider, err := recorder.NewProvider(cfg, scheme.Scheme, tlog.NullLogger{}, makeBroadcaster) + provider, err := recorder.NewProvider(cfg, scheme.Scheme, logr.DiscardLogger{}, makeBroadcaster) Expect(err).NotTo(HaveOccurred()) recorder := provider.GetEventRecorderFor("test") diff --git a/pkg/internal/testing/certs/tinyca_test.go b/pkg/internal/testing/certs/tinyca_test.go index 3d77cd3eb6..e3f2513210 100644 --- a/pkg/internal/testing/certs/tinyca_test.go +++ b/pkg/internal/testing/certs/tinyca_test.go @@ -80,7 +80,7 @@ var _ = Describe("TinyCA", func() { cert, err := ca.NewServingCert() Expect(err).NotTo(HaveOccurred(), "should be able to generate the serving certs") - duration := cert.Cert.NotAfter.Sub(time.Now()) + duration := time.Until(cert.Cert.NotAfter) Expect(duration).To(BeNumerically("<=", 168*time.Hour), "not-after should be short-ish (<= 1 week)") Expect(duration).To(BeNumerically(">=", 2*time.Hour), "not-after should be enough for long tests (couple of hours)") }) @@ -166,7 +166,7 @@ var _ = Describe("TinyCA", func() { }) It("should be valid for short enough to avoid production usage, but long enough for long-running tests", func() { - duration := cert.Cert.NotAfter.Sub(time.Now()) + duration := time.Until(cert.Cert.NotAfter) Expect(duration).To(BeNumerically("<=", 168*time.Hour), "not-after should be short-ish (<= 1 week)") Expect(duration).To(BeNumerically(">=", 2*time.Hour), "not-after should be enough for long tests (couple of hours)") }) diff --git a/pkg/internal/testing/controlplane/apiserver.go b/pkg/internal/testing/controlplane/apiserver.go index 478bd997ff..ece5efd651 100644 --- a/pkg/internal/testing/controlplane/apiserver.go +++ b/pkg/internal/testing/controlplane/apiserver.go @@ -32,9 +32,9 @@ import ( ) const ( - // saKeyFile is the name of the service account signing private key file + // saKeyFile is the name of the service account signing private key file. saKeyFile = "sa-signer.key" - // saKeyFile is the name of the service account signing public key (cert) file + // saKeyFile is the name of the service account signing public key (cert) file. saCertFile = "sa-signer.crt" ) @@ -170,10 +170,7 @@ func (s *APIServer) prepare() error { if err := s.setProcessState(); err != nil { return err } - if err := s.Authn.Start(); err != nil { - return err - } - return nil + return s.Authn.Start() } // configurePorts configures the serving ports for this API server. @@ -292,7 +289,7 @@ func (s *APIServer) setProcessState() error { return err } - s.processState.Args, s.Args, err = process.TemplateAndArguments(s.Args, s.Configure(), process.TemplateDefaults{ + s.processState.Args, s.Args, err = process.TemplateAndArguments(s.Args, s.Configure(), process.TemplateDefaults{ //nolint:staticcheck Data: s, Defaults: s.defaultArgs(), MinimalDefaults: map[string][]string{ @@ -388,10 +385,10 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.crt"), certData, 0640); err != nil { + if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.crt"), certData, 0640); err != nil { //nolint:gosec return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.key"), keyData, 0640); err != nil { + if err := ioutil.WriteFile(filepath.Join(s.CertDir, "apiserver.key"), keyData, 0640); err != nil { //nolint:gosec return err } @@ -408,14 +405,10 @@ func (s *APIServer) populateAPIServerCerts() error { return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, saCertFile), saCert, 0640); err != nil { + if err := ioutil.WriteFile(filepath.Join(s.CertDir, saCertFile), saCert, 0640); err != nil { //nolint:gosec return err } - if err := ioutil.WriteFile(filepath.Join(s.CertDir, saKeyFile), saKey, 0640); err != nil { - return err - } - - return nil + return ioutil.WriteFile(filepath.Join(s.CertDir, saKeyFile), saKey, 0640) //nolint:gosec } // Stop stops this process gracefully, waits for its termination, and cleans up @@ -439,7 +432,7 @@ func (s *APIServer) Stop() error { // complex feature detection neeeded. It's recommended that you switch to .Configure // as you upgrade API server versions. // -// Deprecated: use APIServer.Configure() +// Deprecated: use APIServer.Configure(). var APIServerDefaultArgs = []string{ "--advertise-address=127.0.0.1", "--etcd-servers={{ if .EtcdURL }}{{ .EtcdURL.String }}{{ end }}", @@ -470,7 +463,7 @@ func PrepareAPIServer(s *APIServer) error { // function that sets up the API server just before starting it, // without actually starting it. It's public to make testing easier. // -// NB(directxman12): do not expose this outside of internal +// NB(directxman12): do not expose this outside of internal. func APIServerArguments(s *APIServer) []string { return s.processState.Args } diff --git a/pkg/internal/testing/controlplane/auth.go b/pkg/internal/testing/controlplane/auth.go index 7971118fe8..b2cd4e5e04 100644 --- a/pkg/internal/testing/controlplane/auth.go +++ b/pkg/internal/testing/controlplane/auth.go @@ -43,7 +43,7 @@ type User struct { // 1. Configure // 2. Start // 3. AddUsers (0+ calls) -// 4. Stop +// 4. Stop. type Authn interface { // Configure provides the working directory to this authenticator, // and configures the given API server arguments to make use of this authenticator. @@ -128,7 +128,7 @@ func (c *CertAuthn) Start() error { return fmt.Errorf("start called before configure") } caCrt := c.ca.CA.CertBytes() - if err := ioutil.WriteFile(c.caCrtPath(), caCrt, 0640); err != nil { + if err := ioutil.WriteFile(c.caCrtPath(), caCrt, 0640); err != nil { //nolint:gosec return fmt.Errorf("unable to save the client certificate CA to %s: %w", c.caCrtPath(), err) } diff --git a/pkg/internal/testing/controlplane/etcd.go b/pkg/internal/testing/controlplane/etcd.go index 4f6da04bf1..00d8254777 100644 --- a/pkg/internal/testing/controlplane/etcd.go +++ b/pkg/internal/testing/controlplane/etcd.go @@ -132,7 +132,7 @@ func (e *Etcd) setProcessState() error { e.StopTimeout = e.processState.StopTimeout var err error - e.processState.Args, e.Args, err = process.TemplateAndArguments(e.Args, e.Configure(), process.TemplateDefaults{ + e.processState.Args, e.Args, err = process.TemplateAndArguments(e.Args, e.Configure(), process.TemplateDefaults{ //nolint:staticcheck Data: e, Defaults: e.defaultArgs(), }) @@ -150,8 +150,8 @@ func (e *Etcd) Stop() error { func (e *Etcd) defaultArgs() map[string][]string { args := map[string][]string{ - "listen-peer-urls": []string{"http://localhost:0"}, - "data-dir": []string{e.DataDir}, + "listen-peer-urls": {"http://localhost:0"}, + "data-dir": {e.DataDir}, } if e.URL != nil { args["advertise-client-urls"] = []string{e.URL.String()} diff --git a/pkg/internal/testing/controlplane/kubectl.go b/pkg/internal/testing/controlplane/kubectl.go index fff8869b08..a27b7a0ff8 100644 --- a/pkg/internal/testing/controlplane/kubectl.go +++ b/pkg/internal/testing/controlplane/kubectl.go @@ -30,6 +30,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/internal/testing/process" ) +const ( + envtestName = "envtest" +) + // KubeConfigFromREST reverse-engineers a kubeconfig file from a rest.Config. // The options are tailored towards the rest.Configs we generate, so they're // not broadly applicable. @@ -48,14 +52,14 @@ func KubeConfigFromREST(cfg *rest.Config) ([]byte, error) { return nil, fmt.Errorf("unable to interpret config's host value as a URL: %w", err) } - kubeConfig.Clusters["envtest"] = &kcapi.Cluster{ + kubeConfig.Clusters[envtestName] = &kcapi.Cluster{ // TODO(directxman12): if client-go ever decides to expose defaultServerUrlFor(config), // we can just use that. Note that this is not the same as the public DefaultServerURL, // which requires us to pass a bunch of stuff in manually. Server: (&url.URL{Scheme: protocol, Host: baseURL.Host, Path: cfg.APIPath}).String(), CertificateAuthorityData: cfg.CAData, } - kubeConfig.AuthInfos["envtest"] = &kcapi.AuthInfo{ + kubeConfig.AuthInfos[envtestName] = &kcapi.AuthInfo{ // try to cover all auth strategies that aren't plugins ClientCertificateData: cfg.CertData, ClientKeyData: cfg.KeyData, @@ -64,10 +68,10 @@ func KubeConfigFromREST(cfg *rest.Config) ([]byte, error) { Password: cfg.Password, } kcCtx := kcapi.NewContext() - kcCtx.Cluster = "envtest" - kcCtx.AuthInfo = "envtest" - kubeConfig.Contexts["envtest"] = kcCtx - kubeConfig.CurrentContext = "envtest" + kcCtx.Cluster = envtestName + kcCtx.AuthInfo = envtestName + kubeConfig.Contexts[envtestName] = kcCtx + kubeConfig.CurrentContext = envtestName contents, err := clientcmd.Write(*kubeConfig) if err != nil { diff --git a/pkg/internal/testing/controlplane/plane.go b/pkg/internal/testing/controlplane/plane.go index e07396a041..36fd3c6306 100644 --- a/pkg/internal/testing/controlplane/plane.go +++ b/pkg/internal/testing/controlplane/plane.go @@ -21,9 +21,8 @@ import ( "net/url" "os" - utilerrors "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/internal/testing/certs" ) @@ -95,7 +94,7 @@ func (f *ControlPlane) Stop() error { } } - return utilerrors.NewAggregate(errList) + return kerrors.NewAggregate(errList) } // APIURL returns the URL you should connect to to talk to your API server. diff --git a/pkg/internal/testing/process/arguments.go b/pkg/internal/testing/process/arguments.go index 63b61417b3..6c2c91e144 100644 --- a/pkg/internal/testing/process/arguments.go +++ b/pkg/internal/testing/process/arguments.go @@ -25,7 +25,7 @@ import ( // RenderTemplates returns an []string to render the templates // -// Deprecated: will be removed in favor of Arguments +// Deprecated: will be removed in favor of Arguments. func RenderTemplates(argTemplates []string, data interface{}) (args []string, err error) { var t *template.Template @@ -52,7 +52,7 @@ func RenderTemplates(argTemplates []string, data interface{}) (args []string, er // appending each argument that starts with `--` and contains an `=` to the // argument set (ignoring defaults), returning the rest. // -// Deprecated: will be removed when RenderTemplates is removed +// Deprecated: will be removed when RenderTemplates is removed. func SliceToArguments(sliceArgs []string, args *Arguments) []string { var rest []string for i, arg := range sliceArgs { @@ -79,7 +79,7 @@ func SliceToArguments(sliceArgs []string, args *Arguments) []string { // TemplateDefaults specifies defaults to be used for joining structured arguments with templates. // -// Deprecated: will be removed when RenderTemplates is removed +// Deprecated: will be removed when RenderTemplates is removed. type TemplateDefaults struct { // Data will be used to render the template. Data interface{} @@ -103,7 +103,7 @@ type TemplateDefaults struct { // It returns the resulting rendered arguments, plus the arguments that were // not transferred to `args` during rendering. // -// Deprecated: will be removed when RenderTemplates is removed +// Deprecated: will be removed when RenderTemplates is removed. func TemplateAndArguments(templ []string, args *Arguments, data TemplateDefaults) (allArgs []string, nonFlagishArgs []string, err error) { if len(templ) == 0 { // 3 & 4 (no template case) return args.AsStrings(data.Defaults), nil, nil @@ -168,7 +168,7 @@ type Arg interface { type userArg []string func (a userArg) Append(vals ...string) Arg { - return userArg(append(a, vals...)) + return userArg(append(a, vals...)) //nolint:unconvert } func (a userArg) Get(_ []string) []string { return []string(a) @@ -177,7 +177,7 @@ func (a userArg) Get(_ []string) []string { type defaultedArg []string func (a defaultedArg) Append(vals ...string) Arg { - return defaultedArg(append(a, vals...)) + return defaultedArg(append(a, vals...)) //nolint:unconvert } func (a defaultedArg) Get(defaults []string) []string { res := append([]string(nil), defaults...) @@ -253,7 +253,7 @@ func (a *Arguments) AsStrings(defaults map[string][]string) []string { // Get returns the value of the given flag. If nil, // it will not be passed in AsString, otherwise: // -// len == 0 --> `--key`, len > 0 --> `--key=val1 --key=val2 ...` +// len == 0 --> `--key`, len > 0 --> `--key=val1 --key=val2 ...`. func (a *Arguments) Get(key string) Arg { if vals, ok := a.values[key]; ok { return vals diff --git a/pkg/internal/testing/process/arguments_test.go b/pkg/internal/testing/process/arguments_test.go index ca168fefab..2534eb8446 100644 --- a/pkg/internal/testing/process/arguments_test.go +++ b/pkg/internal/testing/process/arguments_test.go @@ -110,11 +110,11 @@ var _ = Describe("Arguments Templates", func() { data = TemplateDefaults{ Data: map[string]string{"sharpness": "extra"}, Defaults: map[string][]string{ - "cracker": []string{"ritz"}, - "pickle": []string{"kosher-dill"}, + "cracker": {"ritz"}, + "pickle": {"kosher-dill"}, }, MinimalDefaults: map[string][]string{ - "pickle": []string{"kosher-dill"}, + "pickle": {"kosher-dill"}, }, } ) @@ -300,8 +300,8 @@ var _ = Describe("Arguments", func() { Context("when rendering flags", func() { It("should not render defaults for disabled flags", func() { defs := map[string][]string{ - "some-key": []string{"val1", "val2"}, - "other-key": []string{"val"}, + "some-key": {"val1", "val2"}, + "other-key": {"val"}, } args := EmptyArguments(). Disable("some-key") @@ -323,7 +323,7 @@ var _ = Describe("Arguments", func() { It("should read from defaults if the user hasn't set a value for a flag", func() { defs := map[string][]string{ - "some-key": []string{"val1", "val2"}, + "some-key": {"val1", "val2"}, } args := EmptyArguments(). Append("other-key", "vala", "valb") @@ -332,7 +332,7 @@ var _ = Describe("Arguments", func() { It("should not render defaults if the user has set a value for a flag", func() { defs := map[string][]string{ - "some-key": []string{"val1", "val2"}, + "some-key": {"val1", "val2"}, } args := EmptyArguments(). Set("some-key", "vala") @@ -348,5 +348,5 @@ func (a commaArg) Get(defs []string) []string { return []string{strings.Join(defs, ",") + "," + strings.Join(a, ",")} } func (a commaArg) Append(vals ...string) Arg { - return commaArg(append(a, vals...)) + return commaArg(append(a, vals...)) //nolint:unconvert } diff --git a/pkg/internal/testing/process/bin_path_finder.go b/pkg/internal/testing/process/bin_path_finder.go index a496f08416..e1428aa6e5 100644 --- a/pkg/internal/testing/process/bin_path_finder.go +++ b/pkg/internal/testing/process/bin_path_finder.go @@ -42,7 +42,7 @@ const ( // 1. TEST_ASSET_{tr/a-z-/A-Z_/} (if set; asset overrides -- EnvAssetOverridePrefix) // 1. KUBEBUILDER_ASSETS (if set; global asset path -- EnvAssetsPath) // 3. assetDirectory (if set; per-config asset directory) -// 4. /usr/local/kubebuilder/bin (AssetsDefaultPath) +// 4. /usr/local/kubebuilder/bin (AssetsDefaultPath). func BinPathFinder(symbolicName, assetDirectory string) (binPath string) { punctuationPattern := regexp.MustCompile("[^A-Z0-9]+") sanitizedName := punctuationPattern.ReplaceAllString(strings.ToUpper(symbolicName), "_") diff --git a/pkg/internal/testing/process/process.go b/pkg/internal/testing/process/process.go index 3434090ceb..5a0f7b8565 100644 --- a/pkg/internal/testing/process/process.go +++ b/pkg/internal/testing/process/process.go @@ -33,13 +33,13 @@ import ( "time" ) -// ListenAddr represents some listening address and port +// ListenAddr represents some listening address and port. type ListenAddr struct { Address string Port string } -// URL returns a URL for this address with the given scheme and subpath +// URL returns a URL for this address with the given scheme and subpath. func (l *ListenAddr) URL(scheme string, path string) *url.URL { return &url.URL{ Scheme: scheme, @@ -48,7 +48,7 @@ func (l *ListenAddr) URL(scheme string, path string) *url.URL { } } -// HostPort returns the joined host-port pair for this address +// HostPort returns the joined host-port pair for this address. func (l *ListenAddr) HostPort() string { return net.JoinHostPort(l.Address, l.Port) } @@ -159,8 +159,7 @@ func (ps *State) Start(stdout, stderr io.Writer) (err error) { ready := make(chan bool) timedOut := time.After(ps.StartTimeout) - var pollerStopCh stopChannel - pollerStopCh = make(stopChannel) + pollerStopCh := make(stopChannel) go pollURLUntilOK(ps.HealthCheck.URL, ps.HealthCheck.PollInterval, ready, pollerStopCh) ps.waitDone = make(chan struct{}) @@ -198,7 +197,7 @@ func (ps *State) Start(stdout, stderr io.Writer) (err error) { } if ps.Cmd != nil { // intentionally ignore this -- we might've crashed, failed to start, etc - ps.Cmd.Process.Signal(syscall.SIGTERM) //nolint errcheck + ps.Cmd.Process.Signal(syscall.SIGTERM) //nolint:errcheck } return fmt.Errorf("timeout waiting for process %s to start", path.Base(ps.Path)) } @@ -220,7 +219,7 @@ func pollURLUntilOK(url url.URL, interval time.Duration, ready chan bool, stopCh // there's probably certs *somewhere*, // but it's fine to just skip validating // them for health checks during testing - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec }, }, } diff --git a/pkg/leaderelection/leader_election.go b/pkg/leaderelection/leader_election.go index 0173f6e2f4..55fd228690 100644 --- a/pkg/leaderelection/leader_election.go +++ b/pkg/leaderelection/leader_election.go @@ -31,7 +31,7 @@ import ( const inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" -// Options provides the required configuration to create a new resource lock +// Options provides the required configuration to create a new resource lock. type Options struct { // LeaderElection determines whether or not to use leader election when // starting the manager. @@ -104,8 +104,7 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op func getInClusterNamespace() (string, error) { // Check whether the namespace file exists. // If not, we are not running in cluster so can't guess the namespace. - _, err := os.Stat(inClusterNamespacePath) - if os.IsNotExist(err) { + if _, err := os.Stat(inClusterNamespacePath); os.IsNotExist(err) { return "", fmt.Errorf("not running in-cluster, please specify LeaderElectionNamespace") } else if err != nil { return "", fmt.Errorf("error checking namespace file: %w", err) diff --git a/pkg/log/deleg.go b/pkg/log/deleg.go index ed18ae6d11..bbd9c9c756 100644 --- a/pkg/log/deleg.go +++ b/pkg/log/deleg.go @@ -47,7 +47,7 @@ func (p *loggerPromise) WithName(l *DelegatingLogger, name string) *loggerPromis return res } -// WithValues provides a new Logger with the tags appended +// WithValues provides a new Logger with the tags appended. func (p *loggerPromise) WithValues(l *DelegatingLogger, tags ...interface{}) *loggerPromise { res := &loggerPromise{ logger: l, @@ -74,7 +74,7 @@ func (p *loggerPromise) V(l *DelegatingLogger, level int) *loggerPromise { return res } -// Fulfill instantiates the Logger with the provided logger +// Fulfill instantiates the Logger with the provided logger. func (p *loggerPromise) Fulfill(parentLogger logr.Logger) { var logger = parentLogger if p.name != nil { @@ -163,7 +163,7 @@ func (l *DelegatingLogger) V(level int) logr.Logger { return res } -// WithName provides a new Logger with the name appended +// WithName provides a new Logger with the name appended. func (l *DelegatingLogger) WithName(name string) logr.Logger { l.lock.RLock() defer l.lock.RUnlock() @@ -179,7 +179,7 @@ func (l *DelegatingLogger) WithName(name string) logr.Logger { return res } -// WithValues provides a new Logger with the tags appended +// WithValues provides a new Logger with the tags appended. func (l *DelegatingLogger) WithValues(tags ...interface{}) logr.Logger { l.lock.RLock() defer l.lock.RUnlock() diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 56e61277c2..be3ad87997 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -27,7 +27,7 @@ import ( var _ logr.Logger = &DelegatingLogger{} -// logInfo is the information for a particular fakeLogger message +// logInfo is the information for a particular fakeLogger message. type logInfo struct { name []string tags []interface{} @@ -90,8 +90,8 @@ func (f *fakeLogger) Info(msg string, vals ...interface{}) { }) } -func (f *fakeLogger) Enabled() bool { return true } -func (f *fakeLogger) V(lvl int) logr.InfoLogger { return f } +func (f *fakeLogger) Enabled() bool { return true } +func (f *fakeLogger) V(lvl int) logr.Logger { return f } var _ = Describe("logging", func() { diff --git a/pkg/log/null.go b/pkg/log/null.go index 4c56f3427b..09a5a02eb6 100644 --- a/pkg/log/null.go +++ b/pkg/log/null.go @@ -29,32 +29,32 @@ type NullLogger struct{} var _ logr.Logger = NullLogger{} -// Info implements logr.InfoLogger +// Info implements logr.InfoLogger. func (NullLogger) Info(_ string, _ ...interface{}) { // Do nothing. } -// Enabled implements logr.InfoLogger +// Enabled implements logr.InfoLogger. func (NullLogger) Enabled() bool { return false } -// Error implements logr.Logger +// Error implements logr.Logger. func (NullLogger) Error(_ error, _ string, _ ...interface{}) { // Do nothing. } -// V implements logr.Logger -func (log NullLogger) V(_ int) logr.InfoLogger { +// V implements logr.Logger. +func (log NullLogger) V(_ int) logr.Logger { return log } -// WithName implements logr.Logger +// WithName implements logr.Logger. func (log NullLogger) WithName(_ string) logr.Logger { return log } -// WithValues implements logr.Logger +// WithValues implements logr.Logger. func (log NullLogger) WithValues(_ ...interface{}) logr.Logger { return log } diff --git a/pkg/log/warning_handler.go b/pkg/log/warning_handler.go index d4ea12cebf..3012fdd411 100644 --- a/pkg/log/warning_handler.go +++ b/pkg/log/warning_handler.go @@ -23,7 +23,7 @@ import ( ) // KubeAPIWarningLoggerOptions controls the behavior -// of a rest.WarningHandler constructed using NewKubeAPIWarningLogger() +// of a rest.WarningHandler constructed using NewKubeAPIWarningLogger(). type KubeAPIWarningLoggerOptions struct { // Deduplicate indicates a given warning message should only be written once. // Setting this to true in a long-running process handling many warnings can diff --git a/pkg/log/zap/kube_helpers.go b/pkg/log/zap/kube_helpers.go index e37df1aed0..765327d623 100644 --- a/pkg/log/zap/kube_helpers.go +++ b/pkg/log/zap/kube_helpers.go @@ -40,7 +40,7 @@ type KubeAwareEncoder struct { Verbose bool } -// namespacedNameWrapper is a zapcore.ObjectMarshaler for Kubernetes NamespacedName +// namespacedNameWrapper is a zapcore.ObjectMarshaler for Kubernetes NamespacedName. type namespacedNameWrapper struct { types.NamespacedName } @@ -60,12 +60,11 @@ type kubeObjectWrapper struct { obj runtime.Object } -// MarshalLogObject implements zapcore.ObjectMarshaler +// MarshalLogObject implements zapcore.ObjectMarshaler. func (w kubeObjectWrapper) MarshalLogObject(enc zapcore.ObjectEncoder) error { // TODO(directxman12): log kind and apiversion if not set explicitly (common case) // -- needs an a scheme to convert to the GVK. - gvk := w.obj.GetObjectKind().GroupVersionKind() - if gvk.Version != "" { + if gvk := w.obj.GetObjectKind().GroupVersionKind(); gvk.Version != "" { enc.AddString("apiVersion", gvk.GroupVersion().String()) enc.AddString("kind", gvk.Kind) } @@ -75,8 +74,7 @@ func (w kubeObjectWrapper) MarshalLogObject(enc zapcore.ObjectEncoder) error { return fmt.Errorf("got runtime.Object without object metadata: %v", w.obj) } - ns := objMeta.GetNamespace() - if ns != "" { + if ns := objMeta.GetNamespace(); ns != "" { enc.AddString("namespace", ns) } enc.AddString("name", objMeta.GetName()) @@ -86,14 +84,14 @@ func (w kubeObjectWrapper) MarshalLogObject(enc zapcore.ObjectEncoder) error { // NB(directxman12): can't just override AddReflected, since the encoder calls AddReflected on itself directly -// Clone implements zapcore.Encoder +// Clone implements zapcore.Encoder. func (k *KubeAwareEncoder) Clone() zapcore.Encoder { return &KubeAwareEncoder{ Encoder: k.Encoder.Clone(), } } -// EncodeEntry implements zapcore.Encoder +// EncodeEntry implements zapcore.Encoder. func (k *KubeAwareEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { if k.Verbose { // Kubernetes objects implement fmt.Stringer, so if we diff --git a/pkg/log/zap/zap.go b/pkg/log/zap/zap.go index 68dba3c656..22eb5d771a 100644 --- a/pkg/log/zap/zap.go +++ b/pkg/log/zap/zap.go @@ -43,12 +43,12 @@ func New(opts ...Opts) logr.Logger { return zapr.NewLogger(NewRaw(opts...)) } -// Opts allows to manipulate Options +// Opts allows to manipulate Options. type Opts func(*Options) // UseDevMode sets the logger to use (or not use) development mode (more // human-readable output, extra stack traces and logging information, etc). -// See Options.Development +// See Options.Development. func UseDevMode(enabled bool) Opts { return func(o *Options) { o.Development = enabled @@ -56,7 +56,7 @@ func UseDevMode(enabled bool) Opts { } // WriteTo configures the logger to write to the given io.Writer, instead of standard error. -// See Options.DestWriter +// See Options.DestWriter. func WriteTo(out io.Writer) Opts { return func(o *Options) { o.DestWriter = out @@ -64,14 +64,14 @@ func WriteTo(out io.Writer) Opts { } // Encoder configures how the logger will encode the output e.g JSON or console. -// See Options.Encoder +// See Options.Encoder. func Encoder(encoder zapcore.Encoder) func(o *Options) { return func(o *Options) { o.Encoder = encoder } } -// JSONEncoder configures the logger to use a JSON Encoder +// JSONEncoder configures the logger to use a JSON Encoder. func JSONEncoder(opts ...EncoderConfigOption) func(o *Options) { return func(o *Options) { o.Encoder = newJSONEncoder(opts...) @@ -86,7 +86,7 @@ func newJSONEncoder(opts ...EncoderConfigOption) zapcore.Encoder { return zapcore.NewJSONEncoder(encoderConfig) } -// ConsoleEncoder configures the logger to use a Console encoder +// ConsoleEncoder configures the logger to use a Console encoder. func ConsoleEncoder(opts ...EncoderConfigOption) func(o *Options) { return func(o *Options) { o.Encoder = newConsoleEncoder(opts...) @@ -121,14 +121,14 @@ func StacktraceLevel(stacktraceLevel zapcore.LevelEnabler) func(o *Options) { } // RawZapOpts allows appending arbitrary zap.Options to configure the underlying zap logger. -// See Options.ZapOpts +// See Options.ZapOpts. func RawZapOpts(zapOpts ...zap.Option) func(o *Options) { return func(o *Options) { o.ZapOpts = append(o.ZapOpts, zapOpts...) } } -// Options contains all possible settings +// Options contains all possible settings. type Options struct { // Development configures the logger to use a Zap development config // (stacktraces on warnings, no sampling), otherwise a Zap production @@ -169,7 +169,7 @@ type Options struct { ZapOpts []zap.Option } -// addDefaults adds defaults to the Options +// addDefaults adds defaults to the Options. func (o *Options) addDefaults() { if o.DestWriter == nil && o.DestWritter == nil { o.DestWriter = os.Stderr @@ -191,7 +191,6 @@ func (o *Options) addDefaults() { o.StacktraceLevel = &lvl } o.ZapOpts = append(o.ZapOpts, zap.Development()) - } else { if o.NewEncoder == nil { o.NewEncoder = newJSONEncoder @@ -209,7 +208,7 @@ func (o *Options) addDefaults() { if !o.Level.Enabled(zapcore.Level(-2)) { o.ZapOpts = append(o.ZapOpts, zap.WrapCore(func(core zapcore.Core) zapcore.Core { - return zapcore.NewSampler(core, time.Second, 100, 100) + return zapcore.NewSamplerWithOptions(core, time.Second, 100, 100) })) } } @@ -246,7 +245,6 @@ func NewRaw(opts ...Opts) *zap.Logger { // or any integer value > 0 which corresponds to custom debug levels of increasing verbosity") // zap-stacktrace-level: Zap Level at and above which stacktraces are captured (one of 'info', 'error' or 'panic') func (o *Options) BindFlags(fs *flag.FlagSet) { - // Set Development mode value fs.BoolVar(&o.Development, "zap-devel", o.Development, "Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn). "+ diff --git a/pkg/log/zap/zap_test.go b/pkg/log/zap/zap_test.go index 870b7b61f8..095fc54598 100644 --- a/pkg/log/zap/zap_test.go +++ b/pkg/log/zap/zap_test.go @@ -26,19 +26,19 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "go.uber.org/zap/zapcore" - kapi "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" ) -// testStringer is a fmt.Stringer +// testStringer is a fmt.Stringer. type testStringer struct{} func (testStringer) String() string { return "value" } -// fakeSyncWriter is a fake zap.SyncerWriter that lets us test if sync was called +// fakeSyncWriter is a fake zap.SyncerWriter that lets us test if sync was called. type fakeSyncWriter bool func (w *fakeSyncWriter) Write(p []byte) (int, error) { @@ -49,7 +49,7 @@ func (w *fakeSyncWriter) Sync() error { return nil } -// logInfo is the information for a particular fakeLogger message +// logInfo is the information for a particular fakeLogger message. type logInfo struct { name []string tags []interface{} @@ -114,8 +114,8 @@ func (f *fakeLogger) Info(msg string, vals ...interface{}) { }) } -func (f *fakeLogger) Enabled() bool { return true } -func (f *fakeLogger) V(lvl int) logr.InfoLogger { return f } +func (f *fakeLogger) Enabled() bool { return true } +func (f *fakeLogger) V(lvl int) logr.Logger { return f } var _ = Describe("Zap options setup", func() { var opts *Options @@ -148,7 +148,7 @@ var _ = Describe("Zap logger setup", func() { defineTests := func() { It("should log a standard namespaced Kubernetes object name and namespace", func() { - pod := &kapi.Pod{} + pod := &corev1.Pod{} pod.Name = "some-pod" pod.Namespace = "some-ns" logger.Info("here's a kubernetes object", "thing", pod) @@ -173,7 +173,7 @@ var _ = Describe("Zap logger setup", func() { }) It("should log a standard non-namespaced Kubernetes object name", func() { - node := &kapi.Node{} + node := &corev1.Node{} node.Name = "some-node" logger.Info("here's a kubernetes object", "thing", node) @@ -187,7 +187,7 @@ var _ = Describe("Zap logger setup", func() { }) It("should log a standard Kubernetes object's kind, if set", func() { - node := &kapi.Node{} + node := &corev1.Node{} node.Name = "some-node" node.APIVersion = "v1" node.Kind = "Node" @@ -528,23 +528,23 @@ var _ = Describe("Zap log level flag options setup", func() { By("setting up the logger") logger := New(WriteTo(logOut), Level(zapcore.Level(-3))) logger.V(3).Info("test 3") // Should be logged - Expect(string(logOut.Bytes())).To(ContainSubstring(`"msg":"test 3"`)) + Expect(logOut.String()).To(ContainSubstring(`"msg":"test 3"`)) logOut.Truncate(0) logger.V(1).Info("test 1") // Should be logged - Expect(string(logOut.Bytes())).To(ContainSubstring(`"msg":"test 1"`)) + Expect(logOut.String()).To(ContainSubstring(`"msg":"test 1"`)) logOut.Truncate(0) logger.V(4).Info("test 4") // Should not be logged - Expect(string(logOut.Bytes())).To(BeEmpty()) + Expect(logOut.String()).To(BeEmpty()) logger.V(-3).Info("test -3") // Log a panic, since V(-1*N) for all N > 0 is not permitted. - Expect(string(logOut.Bytes())).To(ContainSubstring(`"level":"dpanic"`)) + Expect(logOut.String()).To(ContainSubstring(`"level":"dpanic"`)) }) It("does not log with positive logr level", func() { By("setting up the logger") logger := New(WriteTo(logOut), Level(zapcore.Level(1))) logger.V(1).Info("test 1") - Expect(string(logOut.Bytes())).To(BeEmpty()) + Expect(logOut.String()).To(BeEmpty()) logger.V(3).Info("test 3") - Expect(string(logOut.Bytes())).To(BeEmpty()) + Expect(logOut.String()).To(BeEmpty()) }) }) }) diff --git a/pkg/manager/example_test.go b/pkg/manager/example_test.go index dddfe22be8..17557d1817 100644 --- a/pkg/manager/example_test.go +++ b/pkg/manager/example_test.go @@ -89,11 +89,10 @@ func ExampleManager_start() { } // This example will populate Options from a custom config file -// using defaults +// using defaults. func ExampleOptions_andFrom() { opts := manager.Options{} - _, err := opts.AndFrom(conf.File()) - if err != nil { + if _, err := opts.AndFrom(conf.File()); err != nil { log.Error(err, "unable to load config") os.Exit(1) } @@ -113,7 +112,7 @@ func ExampleOptions_andFrom() { } // This example will populate Options from a custom config file -// using defaults and will panic if there are errors +// using defaults and will panic if there are errors. func ExampleOptions_andFromOrDie() { cfg, err := config.GetConfig() if err != nil { diff --git a/pkg/manager/internal.go b/pkg/manager/internal.go index c16a5bb5f3..5f85e10c90 100644 --- a/pkg/manager/internal.go +++ b/pkg/manager/internal.go @@ -29,7 +29,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" - utilerrors "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/client-go/rest" "k8s.io/client-go/tools/leaderelection" "k8s.io/client-go/tools/leaderelection/resourcelock" @@ -251,8 +251,7 @@ func (cm *controllerManager) AddMetricsExtraHandler(path string, handler http.Ha cm.mu.Lock() defer cm.mu.Unlock() - _, found := cm.metricsExtraHandlers[path] - if found { + if _, found := cm.metricsExtraHandlers[path]; found { return fmt.Errorf("can't register extra handler by duplicate path %q on metrics http server", path) } @@ -261,7 +260,7 @@ func (cm *controllerManager) AddMetricsExtraHandler(path string, handler http.Ha return nil } -// AddHealthzCheck allows you to add Healthz checker +// AddHealthzCheck allows you to add Healthz checker. func (cm *controllerManager) AddHealthzCheck(name string, check healthz.Checker) error { cm.mu.Lock() defer cm.mu.Unlock() @@ -282,7 +281,7 @@ func (cm *controllerManager) AddHealthzCheck(name string, check healthz.Checker) return nil } -// AddReadyzCheck allows you to add Readyz checker +// AddReadyzCheck allows you to add Readyz checker. func (cm *controllerManager) AddReadyzCheck(name string, check healthz.Checker) error { cm.mu.Lock() defer cm.mu.Unlock() @@ -451,7 +450,7 @@ func (cm *controllerManager) Start(ctx context.Context) (err error) { // Utilerrors.Aggregate allows to use errors.Is for all contained errors // whereas fmt.Errorf allows wrapping at most one error which means the // other one can not be found anymore. - err = utilerrors.NewAggregate([]error{err, stopErr}) + err = kerrors.NewAggregate([]error{err, stopErr}) } else { err = stopErr } diff --git a/pkg/manager/manager.go b/pkg/manager/manager.go index 843919427d..903e3e47f9 100644 --- a/pkg/manager/manager.go +++ b/pkg/manager/manager.go @@ -95,7 +95,7 @@ type Manager interface { GetControllerOptions() v1alpha1.ControllerConfigurationSpec } -// Options are the arguments for creating a new Manager +// Options are the arguments for creating a new Manager. type Options struct { // Scheme is the scheme used to resolve runtime.Objects to GroupVersionKinds / Resources // Defaults to the kubernetes/client-go scheme.Scheme, but it's almost always better @@ -292,7 +292,7 @@ type Runnable interface { // until it's done running. type RunnableFunc func(context.Context) error -// Start implements Runnable +// Start implements Runnable. func (r RunnableFunc) Start(ctx context.Context) error { return r(ctx) } @@ -319,7 +319,7 @@ func New(config *rest.Config, options Options) (Manager, error) { clusterOptions.NewClient = options.NewClient clusterOptions.ClientDisableCacheFor = options.ClientDisableCacheFor clusterOptions.DryRunClient = options.DryRunClient - clusterOptions.EventBroadcaster = options.EventBroadcaster + clusterOptions.EventBroadcaster = options.EventBroadcaster //nolint:staticcheck }) if err != nil { return nil, err @@ -393,7 +393,7 @@ func New(config *rest.Config, options Options) (Manager, error) { // AndFrom will use a supplied type and convert to Options // any options already set on Options will be ignored, this is used to allow -// cli flags to override anything specified in the config file +// cli flags to override anything specified in the config file. func (o Options) AndFrom(loader config.ControllerManagerConfiguration) (Options, error) { if inj, wantsScheme := loader.(inject.Scheme); wantsScheme { err := inj.InjectScheme(o.Scheme) @@ -458,7 +458,7 @@ func (o Options) AndFrom(loader config.ControllerManagerConfiguration) (Options, return o, nil } -// AndFromOrDie will use options.AndFrom() and will panic if there are errors +// AndFromOrDie will use options.AndFrom() and will panic if there are errors. func (o Options) AndFromOrDie(loader config.ControllerManagerConfiguration) Options { o, err := o.AndFrom(loader) if err != nil { @@ -468,7 +468,7 @@ func (o Options) AndFromOrDie(loader config.ControllerManagerConfiguration) Opti } func (o Options) setLeaderElectionConfig(obj v1alpha1.ControllerManagerConfigurationSpec) Options { - if o.LeaderElection == false && obj.LeaderElection.LeaderElect != nil { + if !o.LeaderElection && obj.LeaderElection.LeaderElect != nil { o.LeaderElection = *obj.LeaderElection.LeaderElect } @@ -499,7 +499,7 @@ func (o Options) setLeaderElectionConfig(obj v1alpha1.ControllerManagerConfigura return o } -// defaultHealthProbeListener creates the default health probes listener bound to the given address +// defaultHealthProbeListener creates the default health probes listener bound to the given address. func defaultHealthProbeListener(addr string) (net.Listener, error) { if addr == "" || addr == "0" { return nil, nil @@ -512,9 +512,8 @@ func defaultHealthProbeListener(addr string) (net.Listener, error) { return ln, nil } -// setOptionsDefaults set default values for Options fields +// setOptionsDefaults set default values for Options fields. func setOptionsDefaults(options Options) Options { - // Allow newResourceLock to be mocked if options.newResourceLock == nil { options.newResourceLock = leaderelection.NewResourceLock diff --git a/pkg/manager/manager_suite_test.go b/pkg/manager/manager_suite_test.go index 27341129c8..6723d85149 100644 --- a/pkg/manager/manager_suite_test.go +++ b/pkg/manager/manager_suite_test.go @@ -42,7 +42,7 @@ var testenv *envtest.Environment var cfg *rest.Config var clientset *kubernetes.Clientset -// clientTransport is used to force-close keep-alives in tests that check for leaks +// clientTransport is used to force-close keep-alives in tests that check for leaks. var clientTransport *http.Transport var _ = BeforeSuite(func(done Done) { diff --git a/pkg/manager/manager_test.go b/pkg/manager/manager_test.go index 50b99efa94..e930f26f92 100644 --- a/pkg/manager/manager_test.go +++ b/pkg/manager/manager_test.go @@ -819,7 +819,7 @@ var _ = Describe("manger.Manager", func() { defer GinkgoRecover() defer runnableDoneFunc() <-ctx.Done() - time.Sleep(300 * time.Millisecond) //slow closure simulation + time.Sleep(300 * time.Millisecond) // slow closure simulation return nil }))).To(Succeed()) diff --git a/pkg/metrics/client_go_adapter.go b/pkg/metrics/client_go_adapter.go index 3df9b0b0b0..90754269dd 100644 --- a/pkg/metrics/client_go_adapter.go +++ b/pkg/metrics/client_go_adapter.go @@ -51,7 +51,7 @@ const ( ) var ( - // client metrics + // client metrics. requestLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Subsystem: RestClientSubsystem, Name: LatencyKey, @@ -65,7 +65,7 @@ var ( Help: "Number of HTTP requests, partitioned by status code, method, and host.", }, []string{"code", "method", "host"}) - // reflector metrics + // reflector metrics. // TODO(directxman12): update these to be histograms once the metrics overhaul KEP // PRs start landing. @@ -124,7 +124,7 @@ func init() { registerReflectorMetrics() } -// registerClientMetrics sets up the client latency metrics from client-go +// registerClientMetrics sets up the client latency metrics from client-go. func registerClientMetrics() { // register the metrics with our registry Registry.MustRegister(requestLatency) @@ -137,7 +137,7 @@ func registerClientMetrics() { }) } -// registerReflectorMetrics sets up reflector (reconcile) loop metrics +// registerReflectorMetrics sets up reflector (reconcile) loop metrics. func registerReflectorMetrics() { Registry.MustRegister(listsTotal) Registry.MustRegister(listsDuration) diff --git a/pkg/metrics/registry.go b/pkg/metrics/registry.go index 9ba3d600ea..ce17124d53 100644 --- a/pkg/metrics/registry.go +++ b/pkg/metrics/registry.go @@ -26,5 +26,5 @@ type RegistererGatherer interface { } // Registry is a prometheus registry for storing metrics within the -// controller-runtime +// controller-runtime. var Registry RegistererGatherer = prometheus.NewRegistry() diff --git a/pkg/predicate/predicate.go b/pkg/predicate/predicate.go index bab2ce346e..fc59d89ba3 100644 --- a/pkg/predicate/predicate.go +++ b/pkg/predicate/predicate.go @@ -65,7 +65,7 @@ type Funcs struct { GenericFunc func(event.GenericEvent) bool } -// Create implements Predicate +// Create implements Predicate. func (p Funcs) Create(e event.CreateEvent) bool { if p.CreateFunc != nil { return p.CreateFunc(e) @@ -73,7 +73,7 @@ func (p Funcs) Create(e event.CreateEvent) bool { return true } -// Delete implements Predicate +// Delete implements Predicate. func (p Funcs) Delete(e event.DeleteEvent) bool { if p.DeleteFunc != nil { return p.DeleteFunc(e) @@ -81,7 +81,7 @@ func (p Funcs) Delete(e event.DeleteEvent) bool { return true } -// Update implements Predicate +// Update implements Predicate. func (p Funcs) Update(e event.UpdateEvent) bool { if p.UpdateFunc != nil { return p.UpdateFunc(e) @@ -89,7 +89,7 @@ func (p Funcs) Update(e event.UpdateEvent) bool { return true } -// Generic implements Predicate +// Generic implements Predicate. func (p Funcs) Generic(e event.GenericEvent) bool { if p.GenericFunc != nil { return p.GenericFunc(e) @@ -117,12 +117,12 @@ func NewPredicateFuncs(filter func(object client.Object) bool) Funcs { } } -// ResourceVersionChangedPredicate implements a default update predicate function on resource version change +// ResourceVersionChangedPredicate implements a default update predicate function on resource version change. type ResourceVersionChangedPredicate struct { Funcs } -// Update implements default UpdateEvent filter for validating resource version change +// Update implements default UpdateEvent filter for validating resource version change. func (ResourceVersionChangedPredicate) Update(e event.UpdateEvent) bool { if e.ObjectOld == nil { log.Error(nil, "Update event has no old object to update", "event", e) @@ -156,7 +156,7 @@ type GenerationChangedPredicate struct { Funcs } -// Update implements default UpdateEvent filter for validating generation change +// Update implements default UpdateEvent filter for validating generation change. func (GenerationChangedPredicate) Update(e event.UpdateEvent) bool { if e.ObjectOld == nil { log.Error(nil, "Update event has no old object to update", "event", e) @@ -186,7 +186,7 @@ type AnnotationChangedPredicate struct { Funcs } -// Update implements default UpdateEvent filter for validating annotation change +// Update implements default UpdateEvent filter for validating annotation change. func (AnnotationChangedPredicate) Update(e event.UpdateEvent) bool { if e.ObjectOld == nil { log.Error(nil, "Update event has no old object to update", "event", e) @@ -216,7 +216,7 @@ type LabelChangedPredicate struct { Funcs } -// Update implements default UpdateEvent filter for checking label change +// Update implements default UpdateEvent filter for checking label change. func (LabelChangedPredicate) Update(e event.UpdateEvent) bool { if e.ObjectOld == nil { log.Error(nil, "Update event has no old object to update", "event", e) diff --git a/pkg/reconcile/example_test.go b/pkg/reconcile/example_test.go index 1d380112c9..2b799df90d 100644 --- a/pkg/reconcile/example_test.go +++ b/pkg/reconcile/example_test.go @@ -27,7 +27,6 @@ import ( // This example implements a simple no-op reconcile function that prints the object to be Reconciled. func ExampleFunc() { - r := reconcile.Func(func(_ context.Context, o reconcile.Request) (reconcile.Result, error) { // Create your business logic to create, update, delete objects here. fmt.Printf("Name: %s, Namespace: %s", o.Name, o.Namespace) diff --git a/pkg/runtime/inject/inject.go b/pkg/runtime/inject/inject.go index 8874c75727..c8c56ba817 100644 --- a/pkg/runtime/inject/inject.go +++ b/pkg/runtime/inject/inject.go @@ -29,7 +29,7 @@ import ( ) // Cache is used by the ControllerManager to inject Cache into Sources, EventHandlers, Predicates, and -// Reconciles +// Reconciles. type Cache interface { InjectCache(cache cache.Cache) error } @@ -49,7 +49,7 @@ type APIReader interface { } // APIReaderInto will set APIReader on i and return the result if it implements APIReaderInto. -// Returns false if i does not implement APIReader +// Returns false if i does not implement APIReader. func APIReaderInto(reader client.Reader, i interface{}) (bool, error) { if s, ok := i.(APIReader); ok { return true, s.InjectAPIReader(reader) @@ -58,7 +58,7 @@ func APIReaderInto(reader client.Reader, i interface{}) (bool, error) { } // Config is used by the ControllerManager to inject Config into Sources, EventHandlers, Predicates, and -// Reconciles +// Reconciles. type Config interface { InjectConfig(*rest.Config) error } @@ -73,7 +73,7 @@ func ConfigInto(config *rest.Config, i interface{}) (bool, error) { } // Client is used by the ControllerManager to inject client into Sources, EventHandlers, Predicates, and -// Reconciles +// Reconciles. type Client interface { InjectClient(client.Client) error } @@ -88,7 +88,7 @@ func ClientInto(client client.Client, i interface{}) (bool, error) { } // Scheme is used by the ControllerManager to inject Scheme into Sources, EventHandlers, Predicates, and -// Reconciles +// Reconciles. type Scheme interface { InjectScheme(scheme *runtime.Scheme) error } @@ -117,7 +117,7 @@ func StopChannelInto(stop <-chan struct{}, i interface{}) (bool, error) { return false, nil } -// Mapper is used to inject the rest mapper to components that may need it +// Mapper is used to inject the rest mapper to components that may need it. type Mapper interface { InjectMapper(meta.RESTMapper) error } @@ -134,7 +134,7 @@ func MapperInto(mapper meta.RESTMapper, i interface{}) (bool, error) { // Func injects dependencies into i. type Func func(i interface{}) error -// Injector is used by the ControllerManager to inject Func into Controllers +// Injector is used by the ControllerManager to inject Func into Controllers. type Injector interface { InjectFunc(f Func) error } diff --git a/pkg/source/internal/eventsource.go b/pkg/source/internal/eventsource.go index 33c4c41348..f0cfe212ed 100644 --- a/pkg/source/internal/eventsource.go +++ b/pkg/source/internal/eventsource.go @@ -33,14 +33,14 @@ var log = logf.RuntimeLog.WithName("source").WithName("EventHandler") var _ cache.ResourceEventHandler = EventHandler{} -// EventHandler adapts a handler.EventHandler interface to a cache.ResourceEventHandler interface +// EventHandler adapts a handler.EventHandler interface to a cache.ResourceEventHandler interface. type EventHandler struct { EventHandler handler.EventHandler Queue workqueue.RateLimitingInterface Predicates []predicate.Predicate } -// OnAdd creates CreateEvent and calls Create on EventHandler +// OnAdd creates CreateEvent and calls Create on EventHandler. func (e EventHandler) OnAdd(obj interface{}) { c := event.CreateEvent{} @@ -63,7 +63,7 @@ func (e EventHandler) OnAdd(obj interface{}) { e.EventHandler.Create(c, e.Queue) } -// OnUpdate creates UpdateEvent and calls Update on EventHandler +// OnUpdate creates UpdateEvent and calls Update on EventHandler. func (e EventHandler) OnUpdate(oldObj, newObj interface{}) { u := event.UpdateEvent{} @@ -94,7 +94,7 @@ func (e EventHandler) OnUpdate(oldObj, newObj interface{}) { e.EventHandler.Update(u, e.Queue) } -// OnDelete creates DeleteEvent and calls Delete on EventHandler +// OnDelete creates DeleteEvent and calls Delete on EventHandler. func (e EventHandler) OnDelete(obj interface{}) { d := event.DeleteEvent{} diff --git a/pkg/source/source.go b/pkg/source/source.go index adabbaf917..a63b37c443 100644 --- a/pkg/source/source.go +++ b/pkg/source/source.go @@ -66,7 +66,7 @@ type SyncingSource interface { // NewKindWithCache creates a Source without InjectCache, so that it is assured that the given cache is used // and not overwritten. It can be used to watch objects in a different cluster by passing the cache -// from that other cluster +// from that other cluster. func NewKindWithCache(object client.Object, cache cache.Cache) SyncingSource { return &kindWithCache{kind: Kind{Type: object, cache: cache}} } @@ -84,7 +84,7 @@ func (ks *kindWithCache) WaitForSync(ctx context.Context) error { return ks.kind.WaitForSync(ctx) } -// Kind is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create) +// Kind is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create). type Kind struct { // Type is the type of object to watch. e.g. &v1.Pod{} Type client.Object @@ -104,7 +104,6 @@ var _ SyncingSource = &Kind{} // to enqueue reconcile.Requests. func (ks *Kind) Start(ctx context.Context, handler handler.EventHandler, queue workqueue.RateLimitingInterface, prct ...predicate.Predicate) error { - // Type should have been specified by the user. if ks.Type == nil { return fmt.Errorf("must specify Kind.Type") @@ -146,7 +145,7 @@ func (ks *Kind) String() string { if ks.Type != nil && ks.Type.GetObjectKind() != nil { return fmt.Sprintf("kind source: %v", ks.Type.GetObjectKind().GroupVersionKind().String()) } - return fmt.Sprintf("kind source: unknown GVK") + return "kind source: unknown GVK" } // WaitForSync implements SyncingSource to allow controllers to wait with starting @@ -307,7 +306,7 @@ func (cs *Channel) syncLoop(ctx context.Context) { } } -// Informer is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create) +// Informer is used to provide a source of events originating inside the cluster from Watches (e.g. Pod Create). type Informer struct { // Informer is the controller-runtime Informer Informer cache.Informer @@ -319,7 +318,6 @@ var _ Source = &Informer{} // to enqueue reconcile.Requests. func (is *Informer) Start(ctx context.Context, handler handler.EventHandler, queue workqueue.RateLimitingInterface, prct ...predicate.Predicate) error { - // Informer should have been specified by the user. if is.Informer == nil { return fmt.Errorf("must specify Informer.Informer") @@ -335,10 +333,10 @@ func (is *Informer) String() string { var _ Source = Func(nil) -// Func is a function that implements Source +// Func is a function that implements Source. type Func func(context.Context, handler.EventHandler, workqueue.RateLimitingInterface, ...predicate.Predicate) error -// Start implements Source +// Start implements Source. func (f Func) Start(ctx context.Context, evt handler.EventHandler, queue workqueue.RateLimitingInterface, pr ...predicate.Predicate) error { return f(ctx, evt, queue, pr...) diff --git a/pkg/webhook/admission/admissiontest/util.go b/pkg/webhook/admission/admissiontest/util.go index dc6e4ccb63..685e8274d8 100644 --- a/pkg/webhook/admission/admissiontest/util.go +++ b/pkg/webhook/admission/admissiontest/util.go @@ -32,35 +32,35 @@ type FakeValidator struct { GVKToReturn schema.GroupVersionKind } -// ValidateCreate implements admission.Validator +// ValidateCreate implements admission.Validator. func (v *FakeValidator) ValidateCreate() error { return v.ErrorToReturn } -// ValidateUpdate implements admission.Validator +// ValidateUpdate implements admission.Validator. func (v *FakeValidator) ValidateUpdate(old runtime.Object) error { return v.ErrorToReturn } -// ValidateDelete implements admission.Validator +// ValidateDelete implements admission.Validator. func (v *FakeValidator) ValidateDelete() error { return v.ErrorToReturn } -// GetObjectKind implements admission.Validator +// GetObjectKind implements admission.Validator. func (v *FakeValidator) GetObjectKind() schema.ObjectKind { return v } -// DeepCopyObject implements admission.Validator +// DeepCopyObject implements admission.Validator. func (v *FakeValidator) DeepCopyObject() runtime.Object { return &FakeValidator{ErrorToReturn: v.ErrorToReturn, GVKToReturn: v.GVKToReturn} } -// GroupVersionKind implements admission.Validator +// GroupVersionKind implements admission.Validator. func (v *FakeValidator) GroupVersionKind() schema.GroupVersionKind { return v.GVKToReturn } -// SetGroupVersionKind implements admission.Validator +// SetGroupVersionKind implements admission.Validator. func (v *FakeValidator) SetGroupVersionKind(gvk schema.GroupVersionKind) { v.GVKToReturn = gvk } diff --git a/pkg/webhook/admission/decode.go b/pkg/webhook/admission/decode.go index 9583b5e9ac..c7cb71b755 100644 --- a/pkg/webhook/admission/decode.go +++ b/pkg/webhook/admission/decode.go @@ -31,7 +31,7 @@ type Decoder struct { codecs serializer.CodecFactory } -// NewDecoder creates a Decoder given the runtime.Scheme +// NewDecoder creates a Decoder given the runtime.Scheme. func NewDecoder(scheme *runtime.Scheme) (*Decoder, error) { return &Decoder{codecs: serializer.NewCodecFactory(scheme)}, nil } @@ -64,11 +64,7 @@ func (d *Decoder) DecodeRaw(rawObj runtime.RawExtension, into runtime.Object) er } if unstructuredInto, isUnstructured := into.(*unstructured.Unstructured); isUnstructured { // unmarshal into unstructured's underlying object to avoid calling the decoder - if err := json.Unmarshal(rawObj.Raw, &unstructuredInto.Object); err != nil { - return err - } - - return nil + return json.Unmarshal(rawObj.Raw, &unstructuredInto.Object) } deserializer := d.codecs.UniversalDeserializer() diff --git a/pkg/webhook/admission/defaulter.go b/pkg/webhook/admission/defaulter.go index 8b255894ba..0d9aa7a838 100644 --- a/pkg/webhook/admission/defaulter.go +++ b/pkg/webhook/admission/defaulter.go @@ -24,7 +24,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" ) -// Defaulter defines functions for setting defaults on resources +// Defaulter defines functions for setting defaults on resources. type Defaulter interface { runtime.Object Default() @@ -58,8 +58,7 @@ func (h *mutatingHandler) Handle(ctx context.Context, req Request) Response { // Get the object in the request obj := h.defaulter.DeepCopyObject().(Defaulter) - err := h.decoder.Decode(req, obj) - if err != nil { + if err := h.decoder.Decode(req, obj); err != nil { return Errored(http.StatusBadRequest, err) } diff --git a/pkg/webhook/admission/http.go b/pkg/webhook/admission/http.go index 052f803161..3fa8872ff2 100644 --- a/pkg/webhook/admission/http.go +++ b/pkg/webhook/admission/http.go @@ -68,8 +68,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // verify the content type is accurate - contentType := r.Header.Get("Content-Type") - if contentType != "application/json" { + if contentType := r.Header.Get("Content-Type"); contentType != "application/json" { err = fmt.Errorf("contentType=%s, expected application/json", contentType) wh.log.Error(err, "unable to process a request with an unknown content type", "content type", contentType) reviewResponse = Errored(http.StatusBadRequest, err) @@ -125,8 +124,7 @@ func (wh *Webhook) writeResponseTyped(w io.Writer, response Response, admRevGVK // writeAdmissionResponse writes ar to w. func (wh *Webhook) writeAdmissionResponse(w io.Writer, ar v1.AdmissionReview) { - err := json.NewEncoder(w).Encode(ar) - if err != nil { + if err := json.NewEncoder(w).Encode(ar); err != nil { wh.log.Error(err, "unable to encode the response") wh.writeResponse(w, Errored(http.StatusInternalServerError, err)) } else { diff --git a/pkg/webhook/admission/validator.go b/pkg/webhook/admission/validator.go index 926d4a5bd1..4b27e75ede 100644 --- a/pkg/webhook/admission/validator.go +++ b/pkg/webhook/admission/validator.go @@ -22,11 +22,11 @@ import ( "net/http" v1 "k8s.io/api/admission/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" ) -// Validator defines functions for validating an operation +// Validator defines functions for validating an operation. type Validator interface { runtime.Object ValidateCreate() error @@ -70,7 +70,7 @@ func (h *validatingHandler) Handle(ctx context.Context, req Request) Response { err = obj.ValidateCreate() if err != nil { - var apiStatus errors.APIStatus + var apiStatus apierrors.APIStatus if goerrors.As(err, &apiStatus) { return validationResponseFromStatus(false, apiStatus.Status()) } @@ -92,7 +92,7 @@ func (h *validatingHandler) Handle(ctx context.Context, req Request) Response { err = obj.ValidateUpdate(oldObj) if err != nil { - var apiStatus errors.APIStatus + var apiStatus apierrors.APIStatus if goerrors.As(err, &apiStatus) { return validationResponseFromStatus(false, apiStatus.Status()) } @@ -110,7 +110,7 @@ func (h *validatingHandler) Handle(ctx context.Context, req Request) Response { err = obj.ValidateDelete() if err != nil { - var apiStatus errors.APIStatus + var apiStatus apierrors.APIStatus if goerrors.As(err, &apiStatus) { return validationResponseFromStatus(false, apiStatus.Status()) } diff --git a/pkg/webhook/admission/validator_test.go b/pkg/webhook/admission/validator_test.go index d34d3a3380..7fe19268d9 100644 --- a/pkg/webhook/admission/validator_test.go +++ b/pkg/webhook/admission/validator_test.go @@ -26,7 +26,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission/admissiontest" admissionv1 "k8s.io/api/admission/v1" - apierrs "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -98,7 +98,7 @@ var _ = Describe("validatingHandler", func() { Context("when dealing with Status errors", func() { - expectedError := &apierrs.StatusError{ + expectedError := &apierrors.StatusError{ ErrStatus: metav1.Status{ Message: "some message", Code: http.StatusUnprocessableEntity, diff --git a/pkg/webhook/admission/webhook.go b/pkg/webhook/admission/webhook.go index d8c7721501..cf7dbcf68d 100644 --- a/pkg/webhook/admission/webhook.go +++ b/pkg/webhook/admission/webhook.go @@ -133,8 +133,8 @@ type Webhook struct { } // InjectLogger gets a handle to a logging instance, hopefully with more info about this particular webhook. -func (w *Webhook) InjectLogger(l logr.Logger) error { - w.log = l +func (wh *Webhook) InjectLogger(l logr.Logger) error { + wh.log = l return nil } @@ -142,10 +142,10 @@ func (w *Webhook) InjectLogger(l logr.Logger) error { // If the webhook is mutating type, it delegates the AdmissionRequest to each handler and merge the patches. // If the webhook is validating type, it delegates the AdmissionRequest to each handler and // deny the request if anyone denies. -func (w *Webhook) Handle(ctx context.Context, req Request) Response { - resp := w.Handler.Handle(ctx, req) +func (wh *Webhook) Handle(ctx context.Context, req Request) Response { + resp := wh.Handler.Handle(ctx, req) if err := resp.Complete(req); err != nil { - w.log.Error(err, "unable to encode response") + wh.log.Error(err, "unable to encode response") return Errored(http.StatusInternalServerError, errUnableToEncodeResponse) } @@ -153,19 +153,19 @@ func (w *Webhook) Handle(ctx context.Context, req Request) Response { } // InjectScheme injects a scheme into the webhook, in order to construct a Decoder. -func (w *Webhook) InjectScheme(s *runtime.Scheme) error { +func (wh *Webhook) InjectScheme(s *runtime.Scheme) error { // TODO(directxman12): we should have a better way to pass this down var err error - w.decoder, err = NewDecoder(s) + wh.decoder, err = NewDecoder(s) if err != nil { return err } // inject the decoder here too, just in case the order of calling this is not // scheme first, then inject func - if w.Handler != nil { - if _, err := InjectDecoderInto(w.GetDecoder(), w.Handler); err != nil { + if wh.Handler != nil { + if _, err := InjectDecoderInto(wh.GetDecoder(), wh.Handler); err != nil { return err } } @@ -175,12 +175,12 @@ func (w *Webhook) InjectScheme(s *runtime.Scheme) error { // GetDecoder returns a decoder to decode the objects embedded in admission requests. // It may be nil if we haven't received a scheme to use to determine object types yet. -func (w *Webhook) GetDecoder() *Decoder { - return w.decoder +func (wh *Webhook) GetDecoder() *Decoder { + return wh.decoder } // InjectFunc injects the field setter into the webhook. -func (w *Webhook) InjectFunc(f inject.Func) error { +func (wh *Webhook) InjectFunc(f inject.Func) error { // inject directly into the handlers. It would be more correct // to do this in a sync.Once in Handle (since we don't have some // other start/finalize-type method), but it's more efficient to @@ -200,14 +200,14 @@ func (w *Webhook) InjectFunc(f inject.Func) error { return err } - if _, err := InjectDecoderInto(w.GetDecoder(), target); err != nil { + if _, err := InjectDecoderInto(wh.GetDecoder(), target); err != nil { return err } return nil } - return setFields(w.Handler) + return setFields(wh.Handler) } // StandaloneOptions let you configure a StandaloneWebhook. diff --git a/pkg/webhook/alias.go b/pkg/webhook/alias.go index 276784efb2..1a831016af 100644 --- a/pkg/webhook/alias.go +++ b/pkg/webhook/alias.go @@ -23,10 +23,10 @@ import ( // define some aliases for common bits of the webhook functionality -// Defaulter defines functions for setting defaults on resources +// Defaulter defines functions for setting defaults on resources. type Defaulter = admission.Defaulter -// Validator defines functions for validating an operation +// Validator defines functions for validating an operation. type Validator = admission.Validator // AdmissionRequest defines the input for an admission handler. diff --git a/pkg/webhook/authentication/http.go b/pkg/webhook/authentication/http.go index 5c3472dfb6..19f2f9e51c 100644 --- a/pkg/webhook/authentication/http.go +++ b/pkg/webhook/authentication/http.go @@ -68,8 +68,7 @@ func (wh *Webhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // verify the content type is accurate - contentType := r.Header.Get("Content-Type") - if contentType != "application/json" { + if contentType := r.Header.Get("Content-Type"); contentType != "application/json" { err = fmt.Errorf("contentType=%s, expected application/json", contentType) wh.log.Error(err, "unable to process a request with an unknown content type", "content type", contentType) reviewResponse = Errored(err) @@ -140,7 +139,6 @@ func (wh *Webhook) writeTokenResponse(w io.Writer, ar authenticationv1.TokenRevi if log := wh.log; log.V(1).Enabled() { log.V(1).Info("wrote response", "UID", res.UID, "authenticated", res.Status.Authenticated) } - return } // unversionedTokenReview is used to decode both v1 and v1beta1 TokenReview types. diff --git a/pkg/webhook/authentication/webhook.go b/pkg/webhook/authentication/webhook.go index 5ebf0b7286..b1229e422e 100644 --- a/pkg/webhook/authentication/webhook.go +++ b/pkg/webhook/authentication/webhook.go @@ -42,7 +42,7 @@ type Request struct { // Response is the output of an authentication handler. // It contains a response indicating if a given -// operation is allowed +// operation is allowed. type Response struct { authenticationv1.TokenReview } @@ -89,16 +89,16 @@ type Webhook struct { } // InjectLogger gets a handle to a logging instance, hopefully with more info about this particular webhook. -func (w *Webhook) InjectLogger(l logr.Logger) error { - w.log = l +func (wh *Webhook) InjectLogger(l logr.Logger) error { + wh.log = l return nil } // Handle processes TokenReview. -func (w *Webhook) Handle(ctx context.Context, req Request) Response { - resp := w.Handler.Handle(ctx, req) +func (wh *Webhook) Handle(ctx context.Context, req Request) Response { + resp := wh.Handler.Handle(ctx, req) if err := resp.Complete(req); err != nil { - w.log.Error(err, "unable to encode response") + wh.log.Error(err, "unable to encode response") return Errored(errUnableToEncodeResponse) } @@ -106,7 +106,7 @@ func (w *Webhook) Handle(ctx context.Context, req Request) Response { } // InjectFunc injects the field setter into the webhook. -func (w *Webhook) InjectFunc(f inject.Func) error { +func (wh *Webhook) InjectFunc(f inject.Func) error { // inject directly into the handlers. It would be more correct // to do this in a sync.Once in Handle (since we don't have some // other start/finalize-type method), but it's more efficient to @@ -125,5 +125,5 @@ func (w *Webhook) InjectFunc(f inject.Func) error { return nil } - return setFields(w.Handler) + return setFields(wh.Handler) } diff --git a/pkg/webhook/example_test.go b/pkg/webhook/example_test.go index 9dad697e94..e1f2bbee6c 100644 --- a/pkg/webhook/example_test.go +++ b/pkg/webhook/example_test.go @@ -86,7 +86,7 @@ func Example() { // // Note that this assumes and requires a valid TLS // cert and key at the default locations -// tls.crt and tls.key +// tls.crt and tls.key. func ExampleServer_StartStandalone() { // Create a webhook server hookServer := &Server{ @@ -151,5 +151,4 @@ func ExampleStandaloneWebhook() { if err := http.ListenAndServe(port, mux); err != nil { panic(err) } - } diff --git a/pkg/webhook/server.go b/pkg/webhook/server.go index dfca94e99a..99b6ae9eb4 100644 --- a/pkg/webhook/server.go +++ b/pkg/webhook/server.go @@ -128,8 +128,7 @@ func (s *Server) Register(path string, hook http.Handler) { defer s.mu.Unlock() s.defaultingOnce.Do(s.setDefaults) - _, found := s.webhooks[path] - if found { + if _, found := s.webhooks[path]; found { panic(fmt.Errorf("can't register duplicate path: %v", path)) } // TODO(directxman12): call setfields if we've already started the server @@ -180,7 +179,7 @@ func (s *Server) StartStandalone(ctx context.Context, scheme *runtime.Scheme) er } // tlsVersion converts from human-readable TLS version (for example "1.1") -// to the values accepted by tls.Config (for example 0x301) +// to the values accepted by tls.Config (for example 0x301). func tlsVersion(version string) (uint16, error) { switch version { // default is previous behaviour @@ -195,7 +194,7 @@ func tlsVersion(version string) (uint16, error) { case "1.3": return tls.VersionTLS13, nil default: - return 0, fmt.Errorf("Invalid TLSMinVersion %v: expects 1.0, 1.1, 1.2, 1.3 or empty", version) + return 0, fmt.Errorf("invalid TLSMinVersion %v: expects 1.0, 1.1, 1.2, 1.3 or empty", version) } } @@ -226,7 +225,7 @@ func (s *Server) Start(ctx context.Context) error { return err } - cfg := &tls.Config{ + cfg := &tls.Config{ //nolint:gosec NextProtos: []string{"h2"}, GetCertificate: certWatcher.GetCertificate, MinVersion: tlsMinVersion, @@ -249,7 +248,7 @@ func (s *Server) Start(ctx context.Context) error { cfg.ClientAuth = tls.RequireAndVerifyClientCert } - listener, err := tls.Listen("tcp", net.JoinHostPort(s.Host, strconv.Itoa(int(s.Port))), cfg) + listener, err := tls.Listen("tcp", net.JoinHostPort(s.Host, strconv.Itoa(s.Port)), cfg) if err != nil { return err } diff --git a/pkg/webhook/webhook_integration_test.go b/pkg/webhook/webhook_integration_test.go index 9cf8c7e0a3..3ed9713157 100644 --- a/pkg/webhook/webhook_integration_test.go +++ b/pkg/webhook/webhook_integration_test.go @@ -19,8 +19,7 @@ package webhook_test import ( "context" "crypto/tls" - goerrors "errors" - "fmt" + "errors" "net" "net/http" "path/filepath" @@ -31,7 +30,7 @@ import ( . "github.com/onsi/gomega" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/kubernetes/scheme" @@ -98,7 +97,7 @@ var _ = Describe("Webhook", func() { Eventually(func() bool { err = c.Create(context.TODO(), obj) - return errors.ReasonForError(err) == metav1.StatusReason("Always denied") + return apierrors.ReasonForError(err) == metav1.StatusReason("Always denied") }, 1*time.Second).Should(BeTrue()) cancel() @@ -122,7 +121,7 @@ var _ = Describe("Webhook", func() { Eventually(func() bool { err = c.Create(context.TODO(), obj) - return errors.ReasonForError(err) == metav1.StatusReason("Always denied") + return apierrors.ReasonForError(err) == metav1.StatusReason("Always denied") }, 1*time.Second).Should(BeTrue()) cancel() @@ -146,7 +145,7 @@ var _ = Describe("Webhook", func() { Eventually(func() bool { err := c.Create(context.TODO(), obj) - return errors.ReasonForError(err) == metav1.StatusReason("Always denied") + return apierrors.ReasonForError(err) == metav1.StatusReason("Always denied") }, 1*time.Second).Should(BeTrue()) cancel() @@ -170,18 +169,19 @@ var _ = Describe("Webhook", func() { cfg := &tls.Config{ NextProtos: []string{"h2"}, GetCertificate: certWatcher.GetCertificate, + MinVersion: tls.VersionTLS12, } By("generating the listener") listener, err := tls.Listen("tcp", net.JoinHostPort(testenv.WebhookInstallOptions.LocalServingHost, - strconv.Itoa(int(testenv.WebhookInstallOptions.LocalServingPort))), cfg) + strconv.Itoa(testenv.WebhookInstallOptions.LocalServingPort)), cfg) Expect(err).NotTo(HaveOccurred()) By("creating and registering the standalone webhook") hook, err := admission.StandaloneWebhook(admission.ValidatingWebhookFor( &admissiontest.FakeValidator{ - ErrorToReturn: goerrors.New("Always denied"), + ErrorToReturn: errors.New("Always denied"), GVKToReturn: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, }), admission.StandaloneOptions{}) Expect(err).NotTo(HaveOccurred()) @@ -202,7 +202,7 @@ var _ = Describe("Webhook", func() { Eventually(func() bool { err = c.Create(context.TODO(), obj) - return errors.ReasonForError(err) == metav1.StatusReason("Always denied") + return apierrors.ReasonForError(err) == metav1.StatusReason("Always denied") }, 1*time.Second).Should(BeTrue()) cancel() @@ -225,5 +225,5 @@ func (v *rejectingValidator) Handle(ctx context.Context, req admission.Request) if err := v.d.Decode(req, &obj); err != nil { return admission.Denied(err.Error()) } - return admission.Denied(fmt.Sprint("Always denied")) + return admission.Denied("Always denied") } diff --git a/tools/setup-envtest/env/env.go b/tools/setup-envtest/env/env.go index 8ed7a682a3..e12a107352 100644 --- a/tools/setup-envtest/env/env.go +++ b/tools/setup-envtest/env/env.go @@ -95,7 +95,7 @@ func (e *Env) item() store.Item { // ListVersions prints out all available versions matching this Env's // platform & version selector (respecting NoDownload to figure -// out whether or not to match remote versions) +// out whether or not to match remote versions). func (e *Env) ListVersions(ctx context.Context) { out := tabwriter.NewWriter(e.Out, 4, 4, 2, ' ', 0) defer out.Flush() @@ -130,7 +130,6 @@ func (e *Env) ListVersions(ctx context.Context) { } } } - } // LatestVersion returns the latest version matching our version selector and diff --git a/tools/setup-envtest/env/exit.go b/tools/setup-envtest/env/exit.go index 44da97dff1..ae393b593b 100644 --- a/tools/setup-envtest/env/exit.go +++ b/tools/setup-envtest/env/exit.go @@ -68,8 +68,7 @@ func asExit(val interface{}, exit **exitCode) bool { // // This should be the first defer in your main function. func HandleExitWithCode() { - cause := recover() - if CheckRecover(cause, func(code int, err error) { + if cause := recover(); CheckRecover(cause, func(code int, err error) { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(code) }) { @@ -81,7 +80,7 @@ func HandleExitWithCode() { // if it's an exitCode error. It returns true if we should re-panic // the cause. // -// It's mainly useful for testing, normally you'd use HandleExitWithCode +// It's mainly useful for testing, normally you'd use HandleExitWithCode. func CheckRecover(cause interface{}, cb func(int, error)) bool { if cause == nil { return false diff --git a/tools/setup-envtest/env/helpers.go b/tools/setup-envtest/env/helpers.go index 439293ffb0..2c98c88d95 100644 --- a/tools/setup-envtest/env/helpers.go +++ b/tools/setup-envtest/env/helpers.go @@ -30,7 +30,7 @@ const ( PrintPath // PrintEnv prints the path with the corresponding env variable, so that // you can source the output like - // `source $(fetch-envtest switch -p env 1.20.x)` + // `source $(fetch-envtest switch -p env 1.20.x)`. PrintEnv ) diff --git a/tools/setup-envtest/main.go b/tools/setup-envtest/main.go index b4030cb6d6..9c0ab78057 100644 --- a/tools/setup-envtest/main.go +++ b/tools/setup-envtest/main.go @@ -42,9 +42,9 @@ var ( targetOS = flag.String("os", runtime.GOOS, "os to download for (e.g. linux, darwin, for listing operations, use '*' to list all platforms)") targetArch = flag.String("arch", runtime.GOARCH, "architecture to download for (e.g. amd64, for listing operations, use '*' to list all platforms)") - // printFormat is the flag value for -p, --print + // printFormat is the flag value for -p, --print. printFormat = envp.PrintOverview - // zapLvl is the flag value for logging verbosity + // zapLvl is the flag value for logging verbosity. zapLvl = zap.WarnLevel binDir = flag.String("bin-dir", "", @@ -57,7 +57,7 @@ var ( // TODO(directxman12): handle interrupts? -// setupLogging configures a Zap logger +// setupLogging configures a Zap logger. func setupLogging() logr.Logger { logCfg := zap.NewDevelopmentConfig() logCfg.Level = zap.NewAtomicLevelAt(zapLvl) diff --git a/tools/setup-envtest/remote/client.go b/tools/setup-envtest/remote/client.go index f910a2f153..00e4840813 100644 --- a/tools/setup-envtest/remote/client.go +++ b/tools/setup-envtest/remote/client.go @@ -5,7 +5,7 @@ package remote import ( "context" - "crypto/md5" + "crypto/md5" //nolint:gosec "encoding/base64" "encoding/json" "fmt" @@ -116,7 +116,7 @@ func (c *Client) ListVersions(ctx context.Context) ([]versions.Set, error) { } } - var res []versions.Set + res := make([]versions.Set, 0, len(knownVersions)) for ver, details := range knownVersions { res = append(res, versions.Set{Version: ver, Platforms: details}) } @@ -157,7 +157,7 @@ func (c *Client) GetVersion(ctx context.Context, version versions.Concrete, plat // stream in chunks to do the checksum, don't load the whole thing into // memory to avoid causing issues with big files. buf := make([]byte, 32*1024) // 32KiB, same as io.Copy - checksum := md5.New() + checksum := md5.New() //nolint:gosec for cont := true; cont; { amt, err := resp.Body.Read(buf) if err != nil && err != io.EOF { @@ -165,7 +165,7 @@ func (c *Client) GetVersion(ctx context.Context, version versions.Concrete, plat } if amt > 0 { // checksum never returns errors according to docs - checksum.Write(buf[:amt]) //nolint errcheck + checksum.Write(buf[:amt]) if _, err := out.Write(buf[:amt]); err != nil { return fmt.Errorf("unable write next chunk of %s: %w", itemName, err) } @@ -178,10 +178,8 @@ func (c *Client) GetVersion(ctx context.Context, version versions.Concrete, plat if sum != platform.MD5 { return fmt.Errorf("checksum mismatch for %s: %s (computed) != %s (reported from GCS)", itemName, sum, platform.MD5) } - } else { - if _, err := io.Copy(out, resp.Body); err != nil { - return fmt.Errorf("unable to download %s: %w", itemName, err) - } + } else if _, err := io.Copy(out, resp.Body); err != nil { + return fmt.Errorf("unable to download %s: %w", itemName, err) } return nil } diff --git a/tools/setup-envtest/store/store.go b/tools/setup-envtest/store/store.go index 6220dea70c..e3c9ca018f 100644 --- a/tools/setup-envtest/store/store.go +++ b/tools/setup-envtest/store/store.go @@ -165,7 +165,7 @@ func (s *Store) Add(ctx context.Context, item Item, contents io.Reader) (resErr } if err := func() error { // IIFE to get the defer properly in a loop defer binOut.Close() - if _, err := io.Copy(binOut, tarReader); err != nil { + if _, err := io.Copy(binOut, tarReader); err != nil { //nolint:gosec return fmt.Errorf("unable to write file %s from archive to disk for version-platform pair %s", targetPath, itemName) } return nil @@ -235,7 +235,7 @@ func (s *Store) unpackedPath(name string) afero.Fs { } // eachItem iterates through the on-disk versions that match our version & platform selector, -// calling the callback for each +// calling the callback for each. func (s *Store) eachItem(ctx context.Context, filter Filter, cb func(name string, item Item)) error { log := logr.FromContext(ctx) entries, err := afero.ReadDir(s.unpackedBase(), "") diff --git a/tools/setup-envtest/store/store_test.go b/tools/setup-envtest/store/store_test.go index b1cb16ef89..862996abfa 100644 --- a/tools/setup-envtest/store/store_test.go +++ b/tools/setup-envtest/store/store_test.go @@ -172,7 +172,7 @@ var _ = Describe("Store", func() { }) var ( - // keep this sorted + // keep this sorted. localVersions = []store.Item{ {Version: ver(1, 17, 9), Platform: versions.Platform{OS: "linux", Arch: "amd64"}}, {Version: ver(1, 16, 2), Platform: versions.Platform{OS: "linux", Arch: "yourimagination"}}, @@ -191,7 +191,7 @@ var ( newName = "kubebuilder-tools-1.16.3-linux-amd64.tar.gz" ) -func ver(major, minor, patch int) versions.Concrete { //nolint unparam +func ver(major, minor, patch int) versions.Concrete { return versions.Concrete{ Major: major, Minor: minor, @@ -211,10 +211,10 @@ func makeFakeArchive(magic string) io.Reader { for _, fileName := range []string{"some-file", "other-file"} { // create fake file contents: magic+fileName+randomBytes() var chunk [1024 * 48]byte // 1.5 times our chunk read size in GetVersion - copy(chunk[:], []byte(magic)) + copy(chunk[:], magic) copy(chunk[len(magic):], fileName) start := len(magic) + len(fileName) - if _, err := rand.Read(chunk[start:]); err != nil { + if _, err := rand.Read(chunk[start:]); err != nil { //nolint:gosec panic(err) } diff --git a/tools/setup-envtest/versions/parse.go b/tools/setup-envtest/versions/parse.go index 897fd9b024..4b3c5bb5ba 100644 --- a/tools/setup-envtest/versions/parse.go +++ b/tools/setup-envtest/versions/parse.go @@ -12,12 +12,12 @@ import ( var ( // baseVersionRE is a semver-ish version -- either X.Y.Z, X.Y, or X.Y.{*|x}. baseVersionRE = `(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)(?:\.(?P0|[1-9]\d*|x|\*))?` - // versionExprRe matches valid version input for FromExpr + // versionExprRe matches valid version input for FromExpr. versionExprRE = regexp.MustCompile(`^(?P<|~|<=)?` + baseVersionRE + `(?P!)?$`) // ConcreteVersionRE matches a concrete version anywhere in the string. ConcreteVersionRE = regexp.MustCompile(`(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)`) - // OnlyConcreteVersionRE matches a string that's just a concrete version + // OnlyConcreteVersionRE matches a string that's just a concrete version. OnlyConcreteVersionRE = regexp.MustCompile(`^` + ConcreteVersionRE.String() + `$`) ) @@ -35,7 +35,7 @@ var ( // - an '!' at the end means force checking API server for the latest versions // instead of settling for local matches. // -// ^[^~]?SEMVER(!)??$ +// ^[^~]?SEMVER(!)??$ . func FromExpr(expr string) (Spec, error) { match := versionExprRE.FindStringSubmatch(expr) if match == nil { diff --git a/tools/setup-envtest/versions/parse_test.go b/tools/setup-envtest/versions/parse_test.go index 477ab0904c..81b8276b90 100644 --- a/tools/setup-envtest/versions/parse_test.go +++ b/tools/setup-envtest/versions/parse_test.go @@ -24,15 +24,15 @@ import ( . "sigs.k8s.io/controller-runtime/tools/setup-envtest/versions" ) -func patchSel(x, y int, z PointVersion) PatchSelector { //nolint unparam +func patchSel(x, y int, z PointVersion) PatchSelector { return PatchSelector{Major: x, Minor: y, Patch: z} } -func patchSpec(x, y int, z PointVersion) Spec { //nolint unparam +func patchSpec(x, y int, z PointVersion) Spec { return Spec{Selector: patchSel(x, y, z)} } -func tildeSel(x, y, z int) TildeSelector { //nolint unparam +func tildeSel(x, y, z int) TildeSelector { return TildeSelector{ Concrete: Concrete{ Major: x, Minor: y, Patch: z, @@ -40,16 +40,16 @@ func tildeSel(x, y, z int) TildeSelector { //nolint unparam } } -func tildeSpec(x, y, z int) Spec { //nolint unparam +func tildeSpec(x, y, z int) Spec { return Spec{Selector: tildeSel(x, y, z)} } -func ltSpec(x, y int, z PointVersion) Spec { //nolint unparam +func ltSpec(x, y int, z PointVersion) Spec { // this just keeps the table a bit shorter return Spec{Selector: LessThanSelector{ PatchSelector: patchSel(x, y, z), }} } -func lteSpec(x, y int, z PointVersion) Spec { //nolint unparam +func lteSpec(x, y int, z PointVersion) Spec { // this just keeps the table a bit shorter return Spec{Selector: LessThanSelector{ PatchSelector: patchSel(x, y, z), diff --git a/tools/setup-envtest/versions/version.go b/tools/setup-envtest/versions/version.go index b94fdd621f..582ed7794e 100644 --- a/tools/setup-envtest/versions/version.go +++ b/tools/setup-envtest/versions/version.go @@ -191,7 +191,7 @@ func (s Spec) String() string { } // PointVersion represents a wildcard (patch) version -// or concrete numbre +// or concrete number. type PointVersion int const ( @@ -223,12 +223,12 @@ func (p PointVersion) String() string { var ( // LatestVersion matches the most recent version on the remote server. - LatestVersion Spec = Spec{ + LatestVersion = Spec{ Selector: AnySelector{}, CheckLatest: true, } // AnyVersion matches any local or remote version. - AnyVersion Spec = Spec{ + AnyVersion = Spec{ Selector: AnySelector{}, } ) diff --git a/tools/setup-envtest/workflows/workflows_test.go b/tools/setup-envtest/workflows/workflows_test.go index bd7b97f514..0968a69c99 100644 --- a/tools/setup-envtest/workflows/workflows_test.go +++ b/tools/setup-envtest/workflows/workflows_test.go @@ -32,8 +32,7 @@ func ver(major, minor, patch int) versions.Concrete { func shouldHaveError() { var err error var code int - cause := recover() - if envp.CheckRecover(cause, func(caughtCode int, caughtErr error) { + if cause := recover(); envp.CheckRecover(cause, func(caughtCode int, caughtErr error) { err = caughtErr code = caughtCode }) { diff --git a/tools/setup-envtest/workflows/workflows_testutils_test.go b/tools/setup-envtest/workflows/workflows_testutils_test.go index 05b13773f9..a20cf1a2ac 100644 --- a/tools/setup-envtest/workflows/workflows_testutils_test.go +++ b/tools/setup-envtest/workflows/workflows_testutils_test.go @@ -7,7 +7,7 @@ import ( "archive/tar" "bytes" "compress/gzip" - "crypto/md5" + "crypto/md5" //nolint:gosec "encoding/base64" "math/rand" "net/http" @@ -62,7 +62,7 @@ var ( remoteVersions = makeContents(remoteNames) - // keep this sorted + // keep this sorted. localVersions = []versions.Set{ {Version: ver(1, 17, 9), Platforms: []versions.PlatformItem{ {Platform: versions.Platform{OS: "linux", Arch: "amd64"}}, @@ -113,8 +113,8 @@ func makeContents(names []string) []item { res := make([]item, len(names)) for i, name := range names { var chunk [1024 * 48]byte // 1.5 times our chunk read size in GetVersion - copy(chunk[:], []byte(name)) - if _, err := rand.Read(chunk[len(name):]); err != nil { + copy(chunk[:], name) + if _, err := rand.Read(chunk[len(name):]); err != nil { //nolint:gosec panic(err) } res[i] = verWith(name, chunk[:]) @@ -144,7 +144,7 @@ func verWith(name string, contents []byte) item { meta: bucketObject{Name: name}, contents: out.Bytes(), } - hash := md5.Sum(res.contents) + hash := md5.Sum(res.contents) //nolint:gosec res.meta.Hash = base64.StdEncoding.EncodeToString(hash[:]) return res }