From c79a6947adf2b50919066665fa321db3cd683f04 Mon Sep 17 00:00:00 2001 From: Donnie Adams Date: Tue, 6 Feb 2024 13:31:44 -0500 Subject: [PATCH] chore: add revive lint and fix related issues Signed-off-by: Donnie Adams --- .golangci.yml | 1 + Makefile | 2 +- integration/client/apps/apps_test.go | 1 + .../client/credentials/credentials_test.go | 40 ++++++------ .../client/imagerules/imageallowrules_test.go | 6 +- .../imageroleauthorizations_test.go | 8 +-- .../client/imagerules/signature_test.go | 4 +- integration/client/images/images_test.go | 12 ++-- integration/helper/assertions.go | 2 +- integration/helper/config.go | 4 +- integration/helper/wait.go | 1 + integration/run/run_test.go | 8 +-- pkg/apis/admin.acorn.io/group.go | 2 +- pkg/apis/api.acorn.io/group.go | 2 +- pkg/apis/api.acorn.io/v1/conversion.go | 18 +++--- pkg/apis/api.acorn.io/v1/scheme.go | 10 +-- pkg/apis/api.acorn.io/v1/types.go | 10 +-- .../api.acorn.io/v1/zz_generated.deepcopy.go | 4 +- pkg/apis/internal.acorn.io/group.go | 2 +- pkg/apis/internal.acorn.io/v1/appspec.go | 8 +-- pkg/apis/internal.acorn.io/v1/event.go | 4 +- .../internal.acorn.io/v1/imageinstance.go | 8 +-- pkg/apis/internal.acorn.io/v1/map.go | 8 +-- pkg/apis/internal.acorn.io/v1/ports.go | 29 ++++----- pkg/apis/internal.acorn.io/v1/unmarshal.go | 4 +- .../v1/zz_generated.deepcopy.go | 4 +- pkg/apis/internal.admin.acorn.io/group.go | 2 +- pkg/apis/internal.admin.acorn.io/v1/scheme.go | 4 +- pkg/appdefinition/lookup.go | 3 +- pkg/autoupgrade/daemon.go | 12 ++-- pkg/build/assemble.go | 3 +- pkg/build/authprovider/provider.go | 8 +-- pkg/build/build.go | 2 +- pkg/build/remotekeychain.go | 1 + pkg/buildclient/client.go | 8 +-- pkg/buildclient/filesync.go | 2 +- pkg/cli/acorn.go | 10 +-- pkg/cli/all.go | 2 +- pkg/cli/apiserver.go | 4 +- pkg/cli/auth.go | 6 +- pkg/cli/build.go | 2 +- pkg/cli/builder/table/funcs.go | 2 +- pkg/cli/buildserver.go | 2 +- pkg/cli/check.go | 2 +- pkg/cli/copy.go | 4 +- pkg/cli/images.go | 12 ++-- pkg/cli/images_detail.go | 2 +- pkg/cli/images_sign.go | 2 +- pkg/cli/images_verify.go | 2 +- pkg/cli/install.go | 4 +- pkg/cli/kube.go | 2 +- pkg/cli/local.go | 14 ++--- pkg/cli/local_logs.go | 4 +- pkg/cli/local_rm.go | 4 +- pkg/cli/local_server.go | 4 +- pkg/cli/local_start.go | 4 +- pkg/cli/local_stop.go | 4 +- pkg/cli/project_create.go | 3 +- pkg/cli/project_update.go | 4 +- pkg/cli/pull.go | 2 +- pkg/cli/push.go | 2 +- pkg/cli/rm_helper.go | 28 ++++----- pkg/cli/run.go | 9 ++- pkg/cli/testdata/MockClient.go | 2 +- pkg/cli/uninstall.go | 2 +- pkg/cli/version.go | 2 +- pkg/client/app.go | 7 +-- pkg/client/client.go | 12 ++-- pkg/client/deferred.go | 4 +- pkg/client/image.go | 2 +- pkg/client/multi.go | 4 +- pkg/computeclasses/computeclasses.go | 20 +++--- pkg/config/config.go | 12 ++-- pkg/config/config_test.go | 2 +- .../acornimagebuildinstance/buildinstance.go | 2 +- pkg/controller/appdefinition/acorn.go | 2 +- pkg/controller/appdefinition/deploy.go | 42 +++++++------ pkg/controller/appdefinition/error.go | 2 +- pkg/controller/appdefinition/generation.go | 2 +- pkg/controller/appdefinition/namespace.go | 2 +- pkg/controller/appdefinition/pullappimage.go | 63 +++++++++---------- pkg/controller/appdefinition/volume.go | 16 ++--- pkg/controller/appdefinition/volume_bind.go | 2 +- pkg/controller/appstatus/containers.go | 9 +-- pkg/controller/appstatus/functions.go | 10 ++- pkg/controller/appstatus/jobs.go | 37 ++++++----- pkg/controller/appstatus/replicas.go | 4 +- pkg/controller/builder/builder.go | 4 +- pkg/controller/config/devconfig.go | 4 +- pkg/controller/config/dns.go | 11 ++-- pkg/controller/config/dns_test.go | 10 +-- pkg/controller/controller.go | 9 ++- pkg/controller/devsession/devsession.go | 4 +- pkg/controller/gc/gc.go | 2 +- pkg/controller/images/images.go | 2 +- pkg/controller/jobs/finalize.go | 10 +-- pkg/controller/jobs/output.go | 4 +- pkg/controller/local/pods.go | 2 +- pkg/controller/local/storage.go | 4 +- .../permissions/consumerpermissions.go | 2 +- pkg/controller/pvc/markandsave.go | 2 +- pkg/controller/quota/quota.go | 2 +- .../resolvedofferings/computeclass.go | 4 +- pkg/controller/routes.go | 29 +++++---- pkg/controller/scheduling/scheduling.go | 4 +- pkg/controller/tls/certs.go | 2 +- pkg/controller/tls/letsencrypt.go | 29 ++++----- pkg/controller/tls/provider.go | 4 +- pkg/cosign/find.go | 12 ++-- pkg/credentials/store.go | 2 +- pkg/dev/dev.go | 2 +- pkg/dev/ports.go | 2 +- pkg/encryption/nacl/decrypt.go | 5 +- pkg/encryption/nacl/keys.go | 35 ++++++----- pkg/imagedetails/imagedetails.go | 17 ++--- pkg/imagepattern/pattern.go | 20 +++--- pkg/imagerules/imageroleauthorizations.go | 6 +- pkg/imagerules/util/helpers.go | 2 +- pkg/imageselector/signatures/signatures.go | 12 ++-- pkg/imagesource/helper.go | 2 +- pkg/imagesystem/buildertemplate.go | 6 +- pkg/imagesystem/registry.go | 30 ++++----- pkg/imagesystem/registrytemplate.go | 2 +- pkg/install/install.go | 2 +- pkg/jobs/jobs.go | 4 +- pkg/local/docker.go | 16 ++--- pkg/local/server_generic.go | 3 +- pkg/local/server_linux.go | 22 +++---- pkg/log/default_log.go | 2 +- pkg/log/log.go | 6 +- pkg/manager/manager.go | 9 ++- pkg/mocks/mock_client.go | 8 +-- pkg/namespace/namespace.go | 2 +- pkg/profiles/default.go | 6 +- pkg/project/client.go | 4 +- pkg/project/operations.go | 2 +- pkg/proxy/proxy.go | 4 +- pkg/publicname/strategy.go | 4 +- pkg/publish/ingress.go | 6 +- pkg/publish/ingress_test.go | 2 +- pkg/ref/expr.go | 4 +- pkg/secrets/secret.go | 2 +- .../registry/apigroups/acorn/apps/icon.go | 2 +- .../registry/apigroups/acorn/apps/logs.go | 2 +- .../registry/apigroups/acorn/apps/pull.go | 4 +- .../apigroups/acorn/apps/validator.go | 4 +- .../registry/apigroups/acorn/builders/port.go | 2 +- .../apigroups/acorn/containers/exec.go | 2 +- .../acorn/containers/port_forward.go | 2 +- .../apigroups/acorn/containers/translator.go | 4 +- .../apigroups/acorn/credentials/strategy.go | 6 +- .../apigroups/acorn/credentials/translator.go | 6 +- .../acorn/imageallowrules/validator.go | 8 +-- .../registry/apigroups/acorn/images/pull.go | 2 +- .../registry/apigroups/acorn/images/push.go | 2 +- .../registry/apigroups/acorn/info/strategy.go | 2 +- .../apigroups/acorn/secrets/translator.go | 4 +- .../apigroups/acorn/secrets/validator.go | 4 +- .../apigroups/acorn/volumes/translator.go | 4 +- .../apigroups/admin/computeclass/strategy.go | 2 +- .../apigroups/admin/computeclass/validator.go | 2 +- .../imageroleauthorizations/validator.go | 8 +-- pkg/tables/converter.go | 2 +- 163 files changed, 551 insertions(+), 579 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 66bb432ed..6328f000c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,5 +21,6 @@ linters: - unused - goimports - whitespace + - revive fast: false max-same-issues: 50 diff --git a/Makefile b/Makefile index 003b96a00..301896c69 100644 --- a/Makefile +++ b/Makefile @@ -25,7 +25,7 @@ setup-ci-image: docker build -t acorn:v-ci . docker save acorn:v-ci | docker exec -i $$(docker ps | grep k3s | awk '{print $$1}') ctr --address /run/k3s/containerd/containerd.sock images import - -GOLANGCI_LINT_VERSION ?= v1.54.2 +GOLANGCI_LINT_VERSION ?= v1.55.2 setup-env: if ! command -v golangci-lint &> /dev/null; then \ echo "Could not find golangci-lint, installing version $(GOLANGCI_LINT_VERSION)."; \ diff --git a/integration/client/apps/apps_test.go b/integration/client/apps/apps_test.go index f82a71688..71ebc97ba 100644 --- a/integration/client/apps/apps_test.go +++ b/integration/client/apps/apps_test.go @@ -411,6 +411,7 @@ func TestAppLog(t *testing.T) { assert.NotEqual(t, "", msg1.Line) go func() { + //nolint:revive for range msgs { } }() diff --git a/integration/client/credentials/credentials_test.go b/integration/client/credentials/credentials_test.go index ac3a4a78d..c9780ac27 100644 --- a/integration/client/credentials/credentials_test.go +++ b/integration/client/credentials/credentials_test.go @@ -14,10 +14,10 @@ func TestCredentialCreate(t *testing.T) { helper.StartController(t) restConfig := helper.StartAPI(t) - reg, close := helper.StartRegistry(t) - reg1, close1 := helper.StartRegistry(t) - defer close() - defer close1() + reg, cancel := helper.StartRegistry(t) + reg1, cancel1 := helper.StartRegistry(t) + defer cancel() + defer cancel1() ctx := helper.GetCTX(t) kclient := helper.MustReturn(kclient.Default) @@ -60,10 +60,10 @@ func TestCredentialList(t *testing.T) { helper.StartController(t) restConfig := helper.StartAPI(t) - reg, close := helper.StartRegistry(t) - reg1, close1 := helper.StartRegistry(t) - defer close() - defer close1() + reg, cancel := helper.StartRegistry(t) + reg1, cancel1 := helper.StartRegistry(t) + defer cancel() + defer cancel1() ctx := helper.GetCTX(t) kclient := helper.MustReturn(kclient.Default) @@ -110,10 +110,10 @@ func TestCredentialGet(t *testing.T) { helper.StartController(t) restConfig := helper.StartAPI(t) - reg, close := helper.StartRegistry(t) - reg1, close1 := helper.StartRegistry(t) - defer close() - defer close1() + reg, cancel := helper.StartRegistry(t) + reg1, cancel1 := helper.StartRegistry(t) + defer cancel() + defer cancel1() ctx := helper.GetCTX(t) kclient := helper.MustReturn(kclient.Default) @@ -146,10 +146,10 @@ func TestCredentialUpdate(t *testing.T) { helper.StartController(t) restConfig := helper.StartAPI(t) - reg, close := helper.StartRegistry(t) - reg1, close1 := helper.StartRegistry(t) - defer close() - defer close1() + reg, cancel := helper.StartRegistry(t) + reg1, cancel1 := helper.StartRegistry(t) + defer cancel() + defer cancel1() ctx := helper.GetCTX(t) kclient := helper.MustReturn(kclient.Default) @@ -189,10 +189,10 @@ func TestCredentialDelete(t *testing.T) { helper.StartController(t) restConfig := helper.StartAPI(t) - reg, close := helper.StartRegistry(t) - reg1, close1 := helper.StartRegistry(t) - defer close() - defer close1() + reg, cancel := helper.StartRegistry(t) + reg1, cancel1 := helper.StartRegistry(t) + defer cancel() + defer cancel1() ctx := helper.GetCTX(t) kclient := helper.MustReturn(kclient.Default) diff --git a/integration/client/imagerules/imageallowrules_test.go b/integration/client/imagerules/imageallowrules_test.go index 95c810313..c69d0205c 100644 --- a/integration/client/imagerules/imageallowrules_test.go +++ b/integration/client/imagerules/imageallowrules_test.go @@ -18,15 +18,15 @@ import ( func TestImageAllowRules(t *testing.T) { // TODO(@iwilltry42): Add test for auto-upgrade pattern helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() ctx := helper.GetCTX(t) c, project := helper.ClientAndProject(t) kclient := helper.MustReturn(kclient.Default) // enable image allow rules in acorn config - helper.EnableFeatureWithRestore(t, ctx, kclient, profiles.FeatureImageAllowRules) + helper.EnableFeatureWithRestore(ctx, t, kclient, profiles.FeatureImageAllowRules) // Delete any existing IARs from this project namespace err := kclient.DeleteAllOf(ctx, &internalv1.ImageAllowRuleInstance{}, cclient.InNamespace(c.GetNamespace())) diff --git a/integration/client/imagerules/imageroleauthorizations_test.go b/integration/client/imagerules/imageroleauthorizations_test.go index 4f0f2e8f5..aa739c963 100644 --- a/integration/client/imagerules/imageroleauthorizations_test.go +++ b/integration/client/imagerules/imageroleauthorizations_test.go @@ -30,15 +30,15 @@ var parentAcornfile []byte func TestImageRoleAuthorizations(t *testing.T) { helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() ctx := helper.GetCTX(t) c, _ := helper.ClientAndProject(t) kclient := helper.MustReturn(kclient.Default) // enable image role authorizations in acorn config - helper.EnableFeatureWithRestore(t, ctx, kclient, profiles.FeatureImageRoleAuthorizations) + helper.EnableFeatureWithRestore(ctx, t, kclient, profiles.FeatureImageRoleAuthorizations) // Delete any existing rules from this project namespace err := kclient.DeleteAllOf(ctx, &internaladminv1.ImageRoleAuthorizationInstance{}, cclient.InNamespace(c.GetNamespace())) @@ -397,7 +397,7 @@ func TestImageRoleAuthorizationConsumerPerms(t *testing.T) { kclient := helper.MustReturn(kclient.Default) // enable image role authorizations in acorn config - helper.EnableFeatureWithRestore(t, ctx, kclient, profiles.FeatureImageRoleAuthorizations) + helper.EnableFeatureWithRestore(ctx, t, kclient, profiles.FeatureImageRoleAuthorizations) // Delete any existing rules from this project namespace err := kclient.DeleteAllOf(ctx, &internaladminv1.ImageRoleAuthorizationInstance{}, cclient.InNamespace(c.GetNamespace())) diff --git a/integration/client/imagerules/signature_test.go b/integration/client/imagerules/signature_test.go index 3b6b07175..91615317e 100644 --- a/integration/client/imagerules/signature_test.go +++ b/integration/client/imagerules/signature_test.go @@ -16,8 +16,8 @@ import ( func TestImageSignVerify(t *testing.T) { helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() ctx := helper.GetCTX(t) c, project := helper.ClientAndProject(t) diff --git a/integration/client/images/images_test.go b/integration/client/images/images_test.go index 02589f109..b3812ce60 100644 --- a/integration/client/images/images_test.go +++ b/integration/client/images/images_test.go @@ -150,8 +150,8 @@ func TestImageTag(t *testing.T) { func TestImagePush(t *testing.T) { helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() restConfig := helper.StartAPI(t) ctx := helper.GetCTX(t) @@ -193,8 +193,8 @@ func TestImagePush(t *testing.T) { func TestImagePull(t *testing.T) { helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() restConfig := helper.StartAPI(t) ctx := helper.GetCTX(t) @@ -268,8 +268,8 @@ func TestImagePull(t *testing.T) { func TestImageDetails(t *testing.T) { helper.StartController(t) - registry, close := helper.StartRegistry(t) - defer close() + registry, cancel := helper.StartRegistry(t) + defer cancel() restConfig := helper.StartAPI(t) ctx := helper.GetCTX(t) diff --git a/integration/helper/assertions.go b/integration/helper/assertions.go index e0b654c6d..139aeb674 100644 --- a/integration/helper/assertions.go +++ b/integration/helper/assertions.go @@ -13,7 +13,7 @@ func Subset[V, W any, Z comparable](t *testing.T, first []V, second []W, firstLo set := make(map[Z]int) for _, value := range second { - set[secondLookup(value)] += 1 + set[secondLookup(value)]++ } for _, value := range first { diff --git a/integration/helper/config.go b/integration/helper/config.go index 46f1398a3..04a747087 100644 --- a/integration/helper/config.go +++ b/integration/helper/config.go @@ -9,7 +9,7 @@ import ( kclient "sigs.k8s.io/controller-runtime/pkg/client" ) -func EnableFeatureWithRestore(t *testing.T, ctx context.Context, kclient kclient.WithWatch, feature string) { +func EnableFeatureWithRestore(ctx context.Context, t *testing.T, kclient kclient.WithWatch, feature string) { t.Helper() // enable feature in acorn config @@ -43,7 +43,7 @@ func EnableFeatureWithRestore(t *testing.T, ctx context.Context, kclient kclient } } -func SetIgnoreResourceRequirementsWithRestore(t *testing.T, ctx context.Context, kclient kclient.WithWatch) { +func SetIgnoreResourceRequirementsWithRestore(ctx context.Context, t *testing.T, kclient kclient.WithWatch) { t.Helper() cfg, err := config.Get(ctx, kclient) diff --git a/integration/helper/wait.go b/integration/helper/wait.go index a1bfa55fe..db2827823 100644 --- a/integration/helper/wait.go +++ b/integration/helper/wait.go @@ -40,6 +40,7 @@ func doWatch[T client.Object](t *testing.T, watchFunc watchFunc, cb func(obj T) } defer func() { result.Stop() + //nolint:revive for range result.ResultChan() { } }() diff --git a/integration/run/run_test.go b/integration/run/run_test.go index ac95d749a..c47ea4508 100644 --- a/integration/run/run_test.go +++ b/integration/run/run_test.go @@ -1425,8 +1425,8 @@ func TestCrossProjectNetworkConnection(t *testing.T) { }) // determine pod IPs so we can test network connections - fooIP := getPodIPFromAppName(t, ctx, &kc, fooApp.Name, fooApp.Status.Namespace) - barIP := getPodIPFromAppName(t, ctx, &kc, barApp.Name, barApp.Status.Namespace) + fooIP := getPodIPFromAppName(ctx, t, &kc, fooApp.Name, fooApp.Status.Namespace) + barIP := getPodIPFromAppName(ctx, t, &kc, barApp.Name, barApp.Status.Namespace) // build an Acorn that just runs a job with the official curl container curlImage1, err := proj1Client.AcornImageBuild(ctx, "testdata/networkpolicy/curl.Acornfile", nil) @@ -1500,7 +1500,7 @@ func TestCrossProjectNetworkConnection(t *testing.T) { } } -func getPodIPFromAppName(t *testing.T, ctx context.Context, kc *crClient.WithWatch, appName, namespace string) string { +func getPodIPFromAppName(ctx context.Context, t *testing.T, kc *crClient.WithWatch, appName, namespace string) string { t.Helper() selector, err := k8slabels.Parse(fmt.Sprintf("%s=%s", labels.AcornAppName, appName)) if err != nil { @@ -1800,7 +1800,7 @@ func TestIgnoreResourceRequirements(t *testing.T) { kc := helper.MustReturn(kclient.Default) project := helper.TempProject(t, kc) - helper.SetIgnoreResourceRequirementsWithRestore(t, ctx, kc) + helper.SetIgnoreResourceRequirementsWithRestore(ctx, t, kc) c, err := client.New(restConfig, project.Name, project.Name) if err != nil { diff --git a/pkg/apis/admin.acorn.io/group.go b/pkg/apis/admin.acorn.io/group.go index aea185d54..d7ea8abdf 100644 --- a/pkg/apis/admin.acorn.io/group.go +++ b/pkg/apis/admin.acorn.io/group.go @@ -1,3 +1,3 @@ -package admin_acorn_io +package adminacornio var Group = "admin.acorn.io" diff --git a/pkg/apis/api.acorn.io/group.go b/pkg/apis/api.acorn.io/group.go index eb8e47b37..f2917a76f 100644 --- a/pkg/apis/api.acorn.io/group.go +++ b/pkg/apis/api.acorn.io/group.go @@ -1,3 +1,3 @@ -package api_acorn_io +package apiacornio var Group = "api.acorn.io" diff --git a/pkg/apis/api.acorn.io/v1/conversion.go b/pkg/apis/api.acorn.io/v1/conversion.go index 80f032422..ed0554c7b 100644 --- a/pkg/apis/api.acorn.io/v1/conversion.go +++ b/pkg/apis/api.acorn.io/v1/conversion.go @@ -8,7 +8,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" ) -func convert_url_Values_To__ContainerReplicaExecOptions(in *url.Values, out *ContainerReplicaExecOptions, s conversion.Scope) error { +func convertURLlValuesToContainerReplicaExecOptions(in *url.Values, out *ContainerReplicaExecOptions, s conversion.Scope) error { if values, ok := map[string][]string(*in)["command"]; ok && len(values) > 0 { out.Command = *(*[]string)(unsafe.Pointer(&values)) } else { @@ -31,11 +31,11 @@ func convert_url_Values_To__ContainerReplicaExecOptions(in *url.Values, out *Con return nil } -func Convert_url_Values_To__ContainerReplicaExecOptions(in, out interface{}, s conversion.Scope) error { - return convert_url_Values_To__ContainerReplicaExecOptions(in.(*url.Values), out.(*ContainerReplicaExecOptions), s) +func ConvertURLValuesToContainerReplicaExecOptions(in, out interface{}, s conversion.Scope) error { + return convertURLlValuesToContainerReplicaExecOptions(in.(*url.Values), out.(*ContainerReplicaExecOptions), s) } -func convert_url_Values_To__LogOptions(in *url.Values, out *LogOptions, s conversion.Scope) error { +func convertURLValuesToLogOptions(in *url.Values, out *LogOptions, s conversion.Scope) error { if values, ok := map[string][]string(*in)["tailLines"]; ok && len(values) > 0 { out.Tail = new(int64) if err := runtime.Convert_Slice_string_To_int64(&values, out.Tail, s); err != nil { @@ -60,11 +60,11 @@ func convert_url_Values_To__LogOptions(in *url.Values, out *LogOptions, s conver return nil } -func Convert_url_Values_To__LogOptions(in, out interface{}, s conversion.Scope) error { - return convert_url_Values_To__LogOptions(in.(*url.Values), out.(*LogOptions), s) +func ConvertURLValuesToLogOptions(in, out interface{}, s conversion.Scope) error { + return convertURLValuesToLogOptions(in.(*url.Values), out.(*LogOptions), s) } -func convert_url_Values_To__ContainerReplicaPortForwardOptions(in *url.Values, out *ContainerReplicaPortForwardOptions, s conversion.Scope) error { +func convertURLValuesToContainerReplicaPortForwardOptions(in *url.Values, out *ContainerReplicaPortForwardOptions, s conversion.Scope) error { if values, ok := map[string][]string(*in)["port"]; ok && len(values) > 0 { if err := runtime.Convert_Slice_string_To_int(&values, &out.Port, s); err != nil { return err @@ -75,6 +75,6 @@ func convert_url_Values_To__ContainerReplicaPortForwardOptions(in *url.Values, o return nil } -func Convert_url_Values_To__ContainerReplicaPortForwardOptions(in, out interface{}, s conversion.Scope) error { - return convert_url_Values_To__ContainerReplicaPortForwardOptions(in.(*url.Values), out.(*ContainerReplicaPortForwardOptions), s) +func ConvertURLValuesToContainerReplicaPortForwardOptions(in, out interface{}, s conversion.Scope) error { + return convertURLValuesToContainerReplicaPortForwardOptions(in.(*url.Values), out.(*ContainerReplicaPortForwardOptions), s) } diff --git a/pkg/apis/api.acorn.io/v1/scheme.go b/pkg/apis/api.acorn.io/v1/scheme.go index 490582b88..25e145c90 100644 --- a/pkg/apis/api.acorn.io/v1/scheme.go +++ b/pkg/apis/api.acorn.io/v1/scheme.go @@ -4,7 +4,7 @@ import ( "fmt" "net/url" - api_acorn_io "github.com/acorn-io/runtime/pkg/apis/api.acorn.io" + apiacornio "github.com/acorn-io/runtime/pkg/apis/api.acorn.io" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -13,7 +13,7 @@ import ( const Version = "v1" var SchemeGroupVersion = schema.GroupVersion{ - Group: api_acorn_io.Group, + Group: apiacornio.Group, Version: Version, } @@ -83,13 +83,13 @@ func AddToSchemeWithGV(scheme *runtime.Scheme, schemeGroupVersion schema.GroupVe // Add the watch version that applies metav1.AddToGroupVersion(scheme, schemeGroupVersion) - if err := scheme.AddConversionFunc((*url.Values)(nil), (*ContainerReplicaPortForwardOptions)(nil), Convert_url_Values_To__ContainerReplicaPortForwardOptions); err != nil { + if err := scheme.AddConversionFunc((*url.Values)(nil), (*ContainerReplicaPortForwardOptions)(nil), ConvertURLValuesToContainerReplicaPortForwardOptions); err != nil { return err } - if err := scheme.AddConversionFunc((*url.Values)(nil), (*ContainerReplicaExecOptions)(nil), Convert_url_Values_To__ContainerReplicaExecOptions); err != nil { + if err := scheme.AddConversionFunc((*url.Values)(nil), (*ContainerReplicaExecOptions)(nil), ConvertURLValuesToContainerReplicaExecOptions); err != nil { return err } - if err := scheme.AddConversionFunc((*url.Values)(nil), (*LogOptions)(nil), Convert_url_Values_To__LogOptions); err != nil { + if err := scheme.AddConversionFunc((*url.Values)(nil), (*LogOptions)(nil), ConvertURLValuesToLogOptions); err != nil { return err } diff --git a/pkg/apis/api.acorn.io/v1/types.go b/pkg/apis/api.acorn.io/v1/types.go index 0ad85c96b..758284976 100644 --- a/pkg/apis/api.acorn.io/v1/types.go +++ b/pkg/apis/api.acorn.io/v1/types.go @@ -129,10 +129,10 @@ type Image struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` - ZZ_Remote bool `json:"remote,omitempty"` - Repo string `json:"repo,omitempty"` - Digest string `json:"digest,omitempty"` - Tags []string `json:"tags,omitempty"` + ZZRemote bool `json:"remote,omitempty"` + Repo string `json:"repo,omitempty"` + Digest string `json:"digest,omitempty"` + Tags []string `json:"tags,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -497,7 +497,7 @@ type Config struct { LetsEncryptTOSAgree *bool `json:"letsEncryptTOSAgree" name:"lets-encrypt-tos-agree" usage:"Required if --lets-encrypt=enabled. If true, you agree to the Let's Encrypt terms of service (default false)"` SetPodSecurityEnforceProfile *bool `json:"setPodSecurityEnforceProfile" usage:"Set the PodSecurity profile on created namespaces (default true)"` PodSecurityEnforceProfile string `json:"podSecurityEnforceProfile" usage:"The name of the PodSecurity profile to set (default baseline)" wrangler:"nullable"` - HttpEndpointPattern *string `json:"httpEndpointPattern" name:"http-endpoint-pattern" usage:"Go template for formatting application http endpoints. Valid variables to use are: App, Container, Namespace, Hash and ClusterDomain. (default pattern is {{hashConcat 8 .Container .App .Namespace | truncate}}.{{.ClusterDomain}})" wrangler:"nullable"` + HTTPEndpointPattern *string `json:"httpEndpointPattern" name:"http-endpoint-pattern" usage:"Go template for formatting application http endpoints. Valid variables to use are: App, Container, Namespace, Hash and ClusterDomain. (default pattern is {{hashConcat 8 .Container .App .Namespace | truncate}}.{{.ClusterDomain}})" wrangler:"nullable"` InternalClusterDomain string `json:"internalClusterDomain" usage:"The Kubernetes internal cluster domain (default svc.cluster.local)" wrangler:"nullable"` AcornDNS *string `json:"acornDNS" name:"acorn-dns" usage:"enabled|disabled|auto. If enabled, containers created by Acorn will get public FQDNs. Auto functions as disabled if a custom clusterDomain has been supplied (default auto)"` AcornDNSEndpoint *string `json:"acornDNSEndpoint" name:"acorn-dns-endpoint" usage:"The URL to access the Acorn DNS service"` diff --git a/pkg/apis/api.acorn.io/v1/zz_generated.deepcopy.go b/pkg/apis/api.acorn.io/v1/zz_generated.deepcopy.go index 534d2bc89..15ac99f47 100644 --- a/pkg/apis/api.acorn.io/v1/zz_generated.deepcopy.go +++ b/pkg/apis/api.acorn.io/v1/zz_generated.deepcopy.go @@ -427,8 +427,8 @@ func (in *Config) DeepCopyInto(out *Config) { *out = new(bool) **out = **in } - if in.HttpEndpointPattern != nil { - in, out := &in.HttpEndpointPattern, &out.HttpEndpointPattern + if in.HTTPEndpointPattern != nil { + in, out := &in.HTTPEndpointPattern, &out.HTTPEndpointPattern *out = new(string) **out = **in } diff --git a/pkg/apis/internal.acorn.io/group.go b/pkg/apis/internal.acorn.io/group.go index ce583cdb0..d898df630 100644 --- a/pkg/apis/internal.acorn.io/group.go +++ b/pkg/apis/internal.acorn.io/group.go @@ -1,3 +1,3 @@ -package internal_acorn_io +package internalacornio var Group = "internal.acorn.io" diff --git a/pkg/apis/internal.acorn.io/v1/appspec.go b/pkg/apis/internal.acorn.io/v1/appspec.go index ba64cf6ae..6ef38d9c8 100644 --- a/pkg/apis/internal.acorn.io/v1/appspec.go +++ b/pkg/apis/internal.acorn.io/v1/appspec.go @@ -87,7 +87,7 @@ type PortBinding struct { Protocol Protocol `json:"protocol,omitempty"` Hostname string `json:"hostname,omitempty"` // Deprecated Use Hostname instead - ZZ_ServiceName string `json:"serviceName,omitempty"` + ZZServiceName string `json:"serviceName,omitempty"` // Deprecated Has no meaning, publish=true is always assumed Publish bool `json:"publish,omitempty"` // Deprecated Has no meaning, all ports are exposed by default, if this is true @@ -402,7 +402,7 @@ type Permissions struct { ServiceName string `json:"serviceName,omitempty"` Rules []PolicyRule `json:"rules,omitempty"` // Deprecated, use Rules with the 'scopes: ["cluster"]' field - ZZ_ClusterRules []PolicyRule `json:"clusterRules,omitempty"` + ZZClusterRules []PolicyRule `json:"clusterRules,omitempty"` } func (in Permissions) Grants(currentNamespace string, forService string, requested PolicyRule) bool { @@ -425,7 +425,7 @@ individualRuleLoop: func (in Permissions) GetRules() []PolicyRule { result := in.Rules - for _, rule := range in.ZZ_ClusterRules { + for _, rule := range in.ZZClusterRules { if len(rule.Scopes) == 0 { rule.Scopes = append(rule.Scopes, "cluster") } @@ -438,7 +438,7 @@ func (in *Permissions) HasRules() bool { if in == nil { return false } - return len(in.Rules) > 0 || len(in.ZZ_ClusterRules) > 0 + return len(in.Rules) > 0 || len(in.ZZClusterRules) > 0 } func (in *Permissions) Get() Permissions { diff --git a/pkg/apis/internal.acorn.io/v1/event.go b/pkg/apis/internal.acorn.io/v1/event.go index 6ece28105..1e793664b 100644 --- a/pkg/apis/internal.acorn.io/v1/event.go +++ b/pkg/apis/internal.acorn.io/v1/event.go @@ -87,11 +87,11 @@ func NowMicro() MicroTime { // the OpenAPI spec of this type. // // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators -func (_ MicroTime) OpenAPISchemaType() []string { return []string{"string"} } +func (MicroTime) OpenAPISchemaType() []string { return []string{"string"} } // OpenAPISchemaFormat is used by the kube-openapi generator when constructing // the OpenAPI spec of this type. -func (_ MicroTime) OpenAPISchemaFormat() string { return "date-time" } +func (MicroTime) OpenAPISchemaFormat() string { return "date-time" } // DeepCopyInto returns a deep-copy of the MicroTime value. The underlying time.Time // type is effectively immutable in the time API, so it is safe to diff --git a/pkg/apis/internal.acorn.io/v1/imageinstance.go b/pkg/apis/internal.acorn.io/v1/imageinstance.go index bfe0b73aa..2504f8cb0 100644 --- a/pkg/apis/internal.acorn.io/v1/imageinstance.go +++ b/pkg/apis/internal.acorn.io/v1/imageinstance.go @@ -48,10 +48,10 @@ type ImageInstance struct { // Remote indicates that this image has not been locally cached to the internal registry // meaning that it may not exist at the location recorded in the Repo field if the user // has deleted the image after the fact - ZZ_Remote bool `json:"remote,omitempty"` - Repo string `json:"repo,omitempty"` - Digest string `json:"digest,omitempty"` - Tags []string `json:"tags,omitempty"` + ZZRemote bool `json:"remote,omitempty"` + Repo string `json:"repo,omitempty"` + Digest string `json:"digest,omitempty"` + Tags []string `json:"tags,omitempty"` } func (in *ImageInstance) ShortID() string { diff --git a/pkg/apis/internal.acorn.io/v1/map.go b/pkg/apis/internal.acorn.io/v1/map.go index 83651612f..a5d9b5a55 100644 --- a/pkg/apis/internal.acorn.io/v1/map.go +++ b/pkg/apis/internal.acorn.io/v1/map.go @@ -106,16 +106,16 @@ func translateObject(data any) (ret any, err error) { return data, nil } -func (in *GenericMap) DeepCopyInto(out *GenericMap) { +func (g *GenericMap) DeepCopyInto(out *GenericMap) { var err error - if *out, err = Mapify(in.GetData()); err != nil { + if *out, err = Mapify(g.GetData()); err != nil { logrus.WithError(err).Errorf("failed to deep copy into [%T]", out) } } -func (in GenericMap) DeepCopy() GenericMap { +func (g GenericMap) DeepCopy() GenericMap { var out GenericMap - in.DeepCopyInto(&out) + g.DeepCopyInto(&out) return out } diff --git a/pkg/apis/internal.acorn.io/v1/ports.go b/pkg/apis/internal.acorn.io/v1/ports.go index 0895c2f98..3521f9ff9 100644 --- a/pkg/apis/internal.acorn.io/v1/ports.go +++ b/pkg/apis/internal.acorn.io/v1/ports.go @@ -133,30 +133,27 @@ func parsePortBindingTuple(left, right string) (PortBinding, error) { TargetPort: rightNum, Protocol: ProtocolHTTP, }, nil - } else { - // app:80 format - return PortBinding{ - TargetServiceName: left, - TargetPort: rightNum, - }, nil } + // app:80 format + return PortBinding{ + TargetServiceName: left, + TargetPort: rightNum, + }, nil } else if leftIsNum && !rightIsNum { // 80:service format return PortBinding{ Port: leftNum, TargetServiceName: right, }, nil - } else { - if strings.Contains(left, ".") { - // hostname:service - return PortBinding{ - Hostname: left, - TargetServiceName: right, - Protocol: ProtocolHTTP, - }, nil - } - return PortBinding{}, fmt.Errorf("[%s] must be a hostname containing a \".\"", left) + } else if strings.Contains(left, ".") { + // hostname:service + return PortBinding{ + Hostname: left, + TargetServiceName: right, + Protocol: ProtocolHTTP, + }, nil } + return PortBinding{}, fmt.Errorf("[%s] must be a hostname containing a \".\"", left) } func parsePortTuple(left, right string) (PortDef, error) { diff --git a/pkg/apis/internal.acorn.io/v1/unmarshal.go b/pkg/apis/internal.acorn.io/v1/unmarshal.go index c9e5f0d7a..5e43d39f6 100644 --- a/pkg/apis/internal.acorn.io/v1/unmarshal.go +++ b/pkg/apis/internal.acorn.io/v1/unmarshal.go @@ -588,8 +588,8 @@ func (in *ContainerImageBuilderSpec) UnmarshalJSON(data []byte) error { func (in *PortBinding) UnmarshalJSON(data []byte) error { defer func() { - if in.ZZ_ServiceName != "" && in.Hostname == "" { - in.Hostname = in.ZZ_ServiceName + if in.ZZServiceName != "" && in.Hostname == "" { + in.Hostname = in.ZZServiceName } }() diff --git a/pkg/apis/internal.acorn.io/v1/zz_generated.deepcopy.go b/pkg/apis/internal.acorn.io/v1/zz_generated.deepcopy.go index 0bec3f406..0ce63e9c3 100644 --- a/pkg/apis/internal.acorn.io/v1/zz_generated.deepcopy.go +++ b/pkg/apis/internal.acorn.io/v1/zz_generated.deepcopy.go @@ -2588,8 +2588,8 @@ func (in *Permissions) DeepCopyInto(out *Permissions) { (*in)[i].DeepCopyInto(&(*out)[i]) } } - if in.ZZ_ClusterRules != nil { - in, out := &in.ZZ_ClusterRules, &out.ZZ_ClusterRules + if in.ZZClusterRules != nil { + in, out := &in.ZZClusterRules, &out.ZZClusterRules *out = make([]PolicyRule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) diff --git a/pkg/apis/internal.admin.acorn.io/group.go b/pkg/apis/internal.admin.acorn.io/group.go index 09d0fd702..09f6a369d 100644 --- a/pkg/apis/internal.admin.acorn.io/group.go +++ b/pkg/apis/internal.admin.acorn.io/group.go @@ -1,3 +1,3 @@ -package internal_admin_acorn_io +package internaladminacornio var Group = "internal.admin.acorn.io" diff --git a/pkg/apis/internal.admin.acorn.io/v1/scheme.go b/pkg/apis/internal.admin.acorn.io/v1/scheme.go index 57564025e..9e539e314 100644 --- a/pkg/apis/internal.admin.acorn.io/v1/scheme.go +++ b/pkg/apis/internal.admin.acorn.io/v1/scheme.go @@ -1,7 +1,7 @@ package v1 import ( - internal_admin_acorn_io "github.com/acorn-io/runtime/pkg/apis/internal.admin.acorn.io" + internaladminacornio "github.com/acorn-io/runtime/pkg/apis/internal.admin.acorn.io" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -10,7 +10,7 @@ import ( const Version = "v1" var SchemeGroupVersion = schema.GroupVersion{ - Group: internal_admin_acorn_io.Group, + Group: internaladminacornio.Group, Version: Version, } diff --git a/pkg/appdefinition/lookup.go b/pkg/appdefinition/lookup.go index 7cbf1da94..4b0adefc3 100644 --- a/pkg/appdefinition/lookup.go +++ b/pkg/appdefinition/lookup.go @@ -212,9 +212,8 @@ func GetImageReferenceForServiceName(svcName string, appSpec *v1.AppSpec, imageD return findContainerImage(imageData, "", imageDef.Build) } else if imageDef.AcornBuild != nil { return findContainerImage(imageData, "", imageDef.Build) - } else { - return findImageInImageData(imageData, svcName) } + return findImageInImageData(imageData, svcName) } return "", false diff --git a/pkg/autoupgrade/daemon.go b/pkg/autoupgrade/daemon.go index 59496cb60..131a25009 100644 --- a/pkg/autoupgrade/daemon.go +++ b/pkg/autoupgrade/daemon.go @@ -193,7 +193,7 @@ func (d *daemon) refreshImages(ctx context.Context, apps map[kclient.ObjectKey]v ) // If we have autoUpgradeTagPattern, we need to use it to compare the current tag against all the tags - tagPattern, isPattern := AutoUpgradePattern(app.Spec.Image) + tagPattern, isPattern := Pattern(app.Spec.Image) if isPattern { nextAppImage, updated, err = findLatestTagForImageWithPattern(ctx, d.client, current.Identifier(), imageKey.namespace, imageKey.image, tagPattern) if err != nil { @@ -297,7 +297,7 @@ func calcNextCheck(defaultInterval time.Duration, lastUpdate time.Time, app v1.A } func removeTagPattern(image string) string { - p, ok := AutoUpgradePattern(image) + p, ok := Pattern(image) if !ok { return image } @@ -305,8 +305,8 @@ func removeTagPattern(image string) string { return strings.TrimSuffix(image, ":"+p) } -// AutoUpgradePattern returns the tag and a boolean indicating whether it is actually a pattern (versus a concrete tag) -func AutoUpgradePattern(image string) (string, bool) { +// Pattern returns the tag and a boolean indicating whether it is actually a pattern (versus a concrete tag) +func Pattern(image string) (string, bool) { // This first bit is adapted from https://github.com/google/go-containerregistry/blob/main/pkg/name/tag.go // Split on ":" parts := strings.Split(image, ":") @@ -324,14 +324,14 @@ func AutoUpgradePattern(image string) (string, bool) { // 2. A non-empty interval // 3. app.Spec.NotifyUpgrade set to true func Implied(image, interval string, notify bool) bool { - if _, isPattern := AutoUpgradePattern(image); isPattern || interval != "" || notify { + if _, isPattern := Pattern(image); isPattern || interval != "" || notify { return true } return false } func Mode(appSpec v1.AppInstanceSpec) (string, bool) { - _, isPat := AutoUpgradePattern(appSpec.Image) + _, isPat := Pattern(appSpec.Image) on := appSpec.GetAutoUpgrade() || isPat if !on { diff --git a/pkg/build/assemble.go b/pkg/build/assemble.go index 4267a3f93..c3d61111c 100644 --- a/pkg/build/assemble.go +++ b/pkg/build/assemble.go @@ -206,9 +206,8 @@ func retryGetImage(d name.Digest, opts []remote.Option) (result ggcrv1.Image, er result, err = remote.Image(d, opts...) if err == nil { return - } else { - logrus.Warnf("failed to find newly created manifest %s, retrying: %v", d.String(), err) } + logrus.Warnf("failed to find newly created manifest %s, retrying: %v", d.String(), err) time.Sleep(time.Second) } diff --git a/pkg/build/authprovider/provider.go b/pkg/build/authprovider/provider.go index f96c82573..e9cdb509e 100644 --- a/pkg/build/authprovider/provider.go +++ b/pkg/build/authprovider/provider.go @@ -26,7 +26,7 @@ func (a *AuthProvider) Register(server *grpc.Server) { auth.RegisterAuthServer(server, a) } -func (a *AuthProvider) Credentials(ctx context.Context, request *auth.CredentialsRequest) (*auth.CredentialsResponse, error) { +func (a *AuthProvider) Credentials(_ context.Context, request *auth.CredentialsRequest) (*auth.CredentialsResponse, error) { if a.keychain == nil { return &auth.CredentialsResponse{}, nil } @@ -52,14 +52,14 @@ func (a *AuthProvider) Credentials(ctx context.Context, request *auth.Credential }, nil } -func (a *AuthProvider) FetchToken(ctx context.Context, request *auth.FetchTokenRequest) (*auth.FetchTokenResponse, error) { +func (a *AuthProvider) FetchToken(context.Context, *auth.FetchTokenRequest) (*auth.FetchTokenResponse, error) { return nil, fmt.Errorf("not supported") } -func (a *AuthProvider) GetTokenAuthority(ctx context.Context, request *auth.GetTokenAuthorityRequest) (*auth.GetTokenAuthorityResponse, error) { +func (a *AuthProvider) GetTokenAuthority(context.Context, *auth.GetTokenAuthorityRequest) (*auth.GetTokenAuthorityResponse, error) { return nil, status.Errorf(codes.Unavailable, "client side tokens disabled") } -func (a *AuthProvider) VerifyTokenAuthority(ctx context.Context, request *auth.VerifyTokenAuthorityRequest) (*auth.VerifyTokenAuthorityResponse, error) { +func (a *AuthProvider) VerifyTokenAuthority(context.Context, *auth.VerifyTokenAuthorityRequest) (*auth.VerifyTokenAuthorityResponse, error) { return nil, fmt.Errorf("not supported") } diff --git a/pkg/build/build.go b/pkg/build/build.go index 59dbed331..9e58daf99 100644 --- a/pkg/build/build.go +++ b/pkg/build/build.go @@ -301,7 +301,7 @@ func buildAcorns(ctx *buildContext, acorns map[string]v1.AcornBuilderSpec) (map[ for _, entry := range typed.Sorted(acorns) { key, acornImage := entry.Key, entry.Value - if _, auto := autoupgrade.AutoUpgradePattern(acornImage.Image); auto || acornImage.AutoUpgrade { + if _, auto := autoupgrade.Pattern(acornImage.Image); auto || acornImage.AutoUpgrade { // skip auto upgrade continue } diff --git a/pkg/build/remotekeychain.go b/pkg/build/remotekeychain.go index 925f4e801..1faabd6fb 100644 --- a/pkg/build/remotekeychain.go +++ b/pkg/build/remotekeychain.go @@ -38,6 +38,7 @@ func (r *RemoteKeyChain) run(ctx context.Context) { defer func() { cancel() go func() { + //nolint:revive for range msgs { } }() diff --git a/pkg/buildclient/client.go b/pkg/buildclient/client.go index 12d00f32d..8ca95adf2 100644 --- a/pkg/buildclient/client.go +++ b/pkg/buildclient/client.go @@ -28,7 +28,7 @@ func wsURL(url string) string { return url } -type CredentialLookup func(ctx context.Context, serverAddress string) (*apiv1.RegistryAuth, bool, error) +type CredentialLookup func(serverAddress string) (*apiv1.RegistryAuth, bool, error) type WebSocketDialer func(ctx context.Context, urlStr string, requestHeader http.Header) (*websocket.Conn, *http.Response, error) @@ -110,7 +110,7 @@ func Stream(ctx context.Context, cwd string, streams *streams.Output, dialer Web } else if msg.AppImage != nil { return msg.AppImage, nil } else if msg.RegistryServerAddress != "" { - cm := lookupCred(ctx, creds, msg.RegistryServerAddress) + cm := lookupCred(creds, msg.RegistryServerAddress) if cm != nil && cm.RegistryAuth != nil { // Mark the credential as used credHits.Insert(msg.RegistryServerAddress) @@ -158,7 +158,7 @@ func Stream(ctx context.Context, cwd string, streams *streams.Output, dialer Web return nil, fmt.Errorf("build failed") } -func lookupCred(ctx context.Context, creds CredentialLookup, serverAddress string) (result *Message) { +func lookupCred(creds CredentialLookup, serverAddress string) (result *Message) { result = &Message{ RegistryServerAddress: serverAddress, } @@ -167,7 +167,7 @@ func lookupCred(ctx context.Context, creds CredentialLookup, serverAddress strin return } - cred, found, err := creds(ctx, serverAddress) + cred, found, err := creds(serverAddress) if err != nil { logrus.Errorf("failed to lookup credential for server address %s: %v", serverAddress, err) return diff --git a/pkg/buildclient/filesync.go b/pkg/buildclient/filesync.go index c80798388..f07c38a8e 100644 --- a/pkg/buildclient/filesync.go +++ b/pkg/buildclient/filesync.go @@ -93,7 +93,7 @@ func (f *FileServer) DiffCopy(server filesync.FileSync_DiffCopyServer) error { return nil } -func (f *FileServer) TarStream(server filesync.FileSync_TarStreamServer) error { +func (f *FileServer) TarStream(filesync.FileSync_TarStreamServer) error { panic("unsupported") } diff --git a/pkg/cli/acorn.go b/pkg/cli/acorn.go index 7a48cfb2c..063671b11 100644 --- a/pkg/cli/acorn.go +++ b/pkg/cli/acorn.go @@ -34,9 +34,9 @@ func New() *cobra.Command { } root.AddCommand( NewAll(cmdContext), - NewApiServer(cmdContext), + NewAPIServer(cmdContext), NewBuild(cmdContext), - NewBuildServer(cmdContext), + NewBuildServer(), NewCheck(cmdContext), NewContainer(cmdContext), NewJob(cmdContext), @@ -71,10 +71,10 @@ func New() *cobra.Command { NewTag(cmdContext), NewVolume(cmdContext), NewWait(cmdContext), - NewVersion(cmdContext), + NewVersion(), NewKubectl(cmdContext), NewDashboard(cmdContext), - NewLocal(cmdContext), + NewLocal(), ) // This will produce an error if the project flag doesn't exist or a completion function has already // been registered for this flag. Not returning the error since neither of these is likely occur. @@ -136,6 +136,6 @@ func (a *Acorn) PersistentPre(_ *cobra.Command, _ []string) error { return nil } -func (a *Acorn) Run(cmd *cobra.Command, args []string) error { +func (a *Acorn) Run(cmd *cobra.Command, _ []string) error { return cmd.Help() } diff --git a/pkg/cli/all.go b/pkg/cli/all.go index 0ffc1d0b9..778b9083a 100644 --- a/pkg/cli/all.go +++ b/pkg/cli/all.go @@ -26,7 +26,7 @@ type All struct { client ClientFactory } -func (a *All) Run(cmd *cobra.Command, args []string) error { +func (a *All) Run(cmd *cobra.Command, _ []string) error { if !a.Quiet { fmt.Println("") fmt.Println("ACORNS:") diff --git a/pkg/cli/apiserver.go b/pkg/cli/apiserver.go index e59ca6c2c..b5af0d125 100644 --- a/pkg/cli/apiserver.go +++ b/pkg/cli/apiserver.go @@ -12,7 +12,7 @@ var ( opts = minkserver.DefaultOpts() ) -func NewApiServer(c CommandContext) *cobra.Command { +func NewAPIServer(c CommandContext) *cobra.Command { api := &APIServer{client: c.ClientFactory} cmd := cli.Command(api, cobra.Command{ Use: "api-server [flags] [ACORN_NAME...]", @@ -28,7 +28,7 @@ type APIServer struct { client ClientFactory } -func (a *APIServer) Run(cmd *cobra.Command, args []string) error { +func (a *APIServer) Run(cmd *cobra.Command, _ []string) error { cfg, err := server.New(server.Config{ Version: cmd.Version, DefaultOpts: opts, diff --git a/pkg/cli/auth.go b/pkg/cli/auth.go index 300f7fb5f..f5a520e42 100644 --- a/pkg/cli/auth.go +++ b/pkg/cli/auth.go @@ -1,15 +1,13 @@ package cli import ( - "context" - apiv1 "github.com/acorn-io/runtime/pkg/apis/api.acorn.io/v1" "github.com/acorn-io/runtime/pkg/imagesource" "github.com/acorn-io/runtime/pkg/tags" "github.com/google/go-containerregistry/pkg/name" ) -func getAuthForImage(ctx context.Context, clientFactory ClientFactory, image string) (*apiv1.RegistryAuth, error) { +func getAuthForImage(clientFactory ClientFactory, image string) (*apiv1.RegistryAuth, error) { if tags.IsLocalReference(image) { return nil, nil } @@ -30,6 +28,6 @@ func getAuthForImage(ctx context.Context, clientFactory ClientFactory, image str return nil, err } - auth, _, err := creds(ctx, ref.Context().RegistryStr()) + auth, _, err := creds(ref.Context().RegistryStr()) return auth, err } diff --git a/pkg/cli/build.go b/pkg/cli/build.go index 6e86afe49..0abf122cf 100644 --- a/pkg/cli/build.go +++ b/pkg/cli/build.go @@ -79,7 +79,7 @@ func (s *Build) Run(cmd *cobra.Command, args []string) error { if s.Push { for _, tag := range s.Tag { - auth, err := getAuthForImage(cmd.Context(), s.client, tag) + auth, err := getAuthForImage(s.client, tag) if err != nil { return err } diff --git a/pkg/cli/builder/table/funcs.go b/pkg/cli/builder/table/funcs.go index 9e19ce002..1e0b495d4 100644 --- a/pkg/cli/builder/table/funcs.go +++ b/pkg/cli/builder/table/funcs.go @@ -58,7 +58,7 @@ func Name(obj any) (string, error) { return "", fmt.Errorf("invalid obj %T", obj) } -func Noop(obj any) string { +func Noop(any) string { return "" } diff --git a/pkg/cli/buildserver.go b/pkg/cli/buildserver.go index 91fd3e529..9f91497bb 100644 --- a/pkg/cli/buildserver.go +++ b/pkg/cli/buildserver.go @@ -13,7 +13,7 @@ import ( "inet.af/tcpproxy" ) -func NewBuildServer(c CommandContext) *cobra.Command { +func NewBuildServer() *cobra.Command { cmd := cli.Command(&BuildServer{}, cobra.Command{ Use: "build-server [flags] DIRECTORY", Hidden: true, diff --git a/pkg/cli/check.go b/pkg/cli/check.go index 73a435658..8b17a0f70 100644 --- a/pkg/cli/check.go +++ b/pkg/cli/check.go @@ -31,7 +31,7 @@ type Check struct { client ClientFactory } -func (a *Check) Run(cmd *cobra.Command, args []string) error { +func (a *Check) Run(cmd *cobra.Command, _ []string) error { checkOpts := install.CheckOptions{RuntimeImage: a.Image, IngressClassName: a.IngressClassName, Namespace: a.TestNamespace} checkresult := install.RunChecks(cmd.Context(), checkOpts, install.CheckRBAC, diff --git a/pkg/cli/copy.go b/pkg/cli/copy.go index 9d54f4dc1..ffc02bf9f 100644 --- a/pkg/cli/copy.go +++ b/pkg/cli/copy.go @@ -73,7 +73,7 @@ func (a *ImageCopy) Run(cmd *cobra.Command, args []string) (err error) { return fmt.Errorf("image %s has no specified registry", args[0]) } - sourceAuth, err := getAuthForImage(cmd.Context(), a.client, args[0]) + sourceAuth, err := getAuthForImage(a.client, args[0]) if err != nil { return err } @@ -92,7 +92,7 @@ func (a *ImageCopy) Run(cmd *cobra.Command, args []string) (err error) { return a.copyTag(source, args[1], sourceOpts) } - destAuth, err := getAuthForImage(cmd.Context(), a.client, args[1]) + destAuth, err := getAuthForImage(a.client, args[1]) if err != nil { return err } diff --git a/pkg/cli/images.go b/pkg/cli/images.go index 235f5a1eb..bd2f80882 100644 --- a/pkg/cli/images.go +++ b/pkg/cli/images.go @@ -137,7 +137,7 @@ func (a *Image) Run(cmd *cobra.Command, args []string) error { tagToMatch = image.Tags[0] } - return printContainerImages(images, cmd.Context(), c, a, args, tagToMatch) + return printContainerImages(cmd.Context(), c, images, a, tagToMatch) } out := table.NewWriter(tables.ImageAcorn, false, a.Output) @@ -236,7 +236,7 @@ type imageContainerPrint struct { ImageID string } -func printContainerImages(images []apiv1.Image, ctx context.Context, c client.Client, a *Image, args []string, tagToMatch string) error { +func printContainerImages(ctx context.Context, c client.Client, images []apiv1.Image, a *Image, tagToMatch string) error { out := table.NewWriter(tables.ImageContainer, a.Quiet, a.Output) if a.Quiet { @@ -246,7 +246,7 @@ func printContainerImages(images []apiv1.Image, ctx context.Context, c client.Cl } for _, image := range images { - containerImages, err := getImageContainers(c, ctx, image) + containerImages, err := getImageContainers(ctx, c, image) if err != nil { return err } @@ -284,8 +284,8 @@ func printContainerImages(images []apiv1.Image, ctx context.Context, c client.Cl return out.Err() } -func getImageContainers(c client.Client, ctx context.Context, image apiv1.Image) ([]imageContainer, error) { - imageContainers := []imageContainer{} +func getImageContainers(ctx context.Context, c client.Client, image apiv1.Image) ([]imageContainer, error) { + var imageContainers []imageContainer imgDetails, err := c.ImageDetails(ctx, image.Name, nil) if err != nil { @@ -302,7 +302,7 @@ func getImageContainers(c client.Client, ctx context.Context, image apiv1.Image) } func newImageContainerList(image apiv1.Image, containers map[string]v1.ContainerData) []imageContainer { - imageContainers := []imageContainer{} + var imageContainers []imageContainer for k, v := range containers { imageContainerObject := imageContainer{ diff --git a/pkg/cli/images_detail.go b/pkg/cli/images_detail.go index 035f49643..8e383490a 100644 --- a/pkg/cli/images_detail.go +++ b/pkg/cli/images_detail.go @@ -41,7 +41,7 @@ func (a *ImageDetails) Run(cmd *cobra.Command, args []string) error { nested = args[1] } - auth, err = getAuthForImage(cmd.Context(), a.client, args[0]) + auth, err = getAuthForImage(a.client, args[0]) if err != nil { return err } diff --git a/pkg/cli/images_sign.go b/pkg/cli/images_sign.go index 1ef4f7c62..5b074b117 100644 --- a/pkg/cli/images_sign.go +++ b/pkg/cli/images_sign.go @@ -63,7 +63,7 @@ func (a *ImageSign) Run(cmd *cobra.Command, args []string) error { return err } - auth, err := getAuthForImage(cmd.Context(), a.client, imageName) + auth, err := getAuthForImage(a.client, imageName) if err != nil { return err } diff --git a/pkg/cli/images_verify.go b/pkg/cli/images_verify.go index b332c21d6..39b0dee16 100644 --- a/pkg/cli/images_verify.go +++ b/pkg/cli/images_verify.go @@ -54,7 +54,7 @@ func (a *ImageVerify) Run(cmd *cobra.Command, args []string) error { return err } - auth, err := getAuthForImage(cmd.Context(), a.client, imageName) + auth, err := getAuthForImage(a.client, imageName) if err != nil { return err } diff --git a/pkg/cli/install.go b/pkg/cli/install.go index 1bf1f59d0..50018beb8 100644 --- a/pkg/cli/install.go +++ b/pkg/cli/install.go @@ -66,7 +66,7 @@ func (i *Install) dev(ctx context.Context, imageName string, opts *install.Optio return err } - auth, ok, err := creds.Get(ctx, ref.Context().RegistryStr()) + auth, ok, err := creds.Get(ref.Context().RegistryStr()) if err != nil { return err } @@ -78,7 +78,7 @@ func (i *Install) dev(ctx context.Context, imageName string, opts *install.Optio return install.Dev(ctx, imageName, auth, opts) } -func (i *Install) Run(cmd *cobra.Command, args []string) error { +func (i *Install) Run(cmd *cobra.Command, _ []string) error { var image = system.DefaultImage() if i.Image != "" { image = i.Image diff --git a/pkg/cli/kube.go b/pkg/cli/kube.go index a7fa75885..7ff073242 100644 --- a/pkg/cli/kube.go +++ b/pkg/cli/kube.go @@ -45,7 +45,7 @@ func (s *Kube) Run(cmd *cobra.Command, args []string) error { } if s.WriteFile != "" { - data, err := c.KubeConfig(cmd.Context(), &client.KubeProxyAddressOptions{ + data, err := c.KubeConfig(&client.KubeProxyAddressOptions{ Region: s.Region, }) if err != nil { diff --git a/pkg/cli/local.go b/pkg/cli/local.go index da40d0cdd..092796e1c 100644 --- a/pkg/cli/local.go +++ b/pkg/cli/local.go @@ -5,23 +5,23 @@ import ( "github.com/spf13/cobra" ) -func NewLocal(c CommandContext) *cobra.Command { +func NewLocal() *cobra.Command { cmd := cli.Command(&Local{}, cobra.Command{ SilenceUsage: true, Short: "Manage local development acorn runtime", Hidden: true, }) - cmd.AddCommand(NewLocalServer(c)) - cmd.AddCommand(NewLocalLogs(c)) - cmd.AddCommand(NewLocalRm(c)) - cmd.AddCommand(NewLocalStart(c)) - cmd.AddCommand(NewLocalStop(c)) + cmd.AddCommand(NewLocalServer()) + cmd.AddCommand(NewLocalLogs()) + cmd.AddCommand(NewLocalRm()) + cmd.AddCommand(NewLocalStart()) + cmd.AddCommand(NewLocalStop()) return cmd } type Local struct { } -func (a *Local) Run(cmd *cobra.Command, args []string) error { +func (a *Local) Run(*cobra.Command, []string) error { return nil } diff --git a/pkg/cli/local_logs.go b/pkg/cli/local_logs.go index 420a1673f..e216f1845 100644 --- a/pkg/cli/local_logs.go +++ b/pkg/cli/local_logs.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" ) -func NewLocalLogs(c CommandContext) *cobra.Command { +func NewLocalLogs() *cobra.Command { cmd := cli.Command(&LocalLogs{}, cobra.Command{ Use: "logs [flags]", Aliases: []string{"log"}, @@ -20,7 +20,7 @@ type LocalLogs struct { local.LogOptions } -func (a *LocalLogs) Run(cmd *cobra.Command, args []string) error { +func (a *LocalLogs) Run(cmd *cobra.Command, _ []string) error { c, err := local.NewContainer(cmd.Context()) if err != nil { return err diff --git a/pkg/cli/local_rm.go b/pkg/cli/local_rm.go index 8444574ea..e289c8d04 100644 --- a/pkg/cli/local_rm.go +++ b/pkg/cli/local_rm.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" ) -func NewLocalRm(c CommandContext) *cobra.Command { +func NewLocalRm() *cobra.Command { cmd := cli.Command(&LocalRm{}, cobra.Command{ Use: "rm [flags]", Aliases: []string{"delete"}, @@ -22,7 +22,7 @@ type LocalRm struct { State bool `usage:"Include associated state (acorns, secrets and volume data)"` } -func (a *LocalRm) Run(cmd *cobra.Command, args []string) error { +func (a *LocalRm) Run(cmd *cobra.Command, _ []string) error { c, err := local.NewContainer(cmd.Context()) if err != nil { return err diff --git a/pkg/cli/local_server.go b/pkg/cli/local_server.go index f8fabe19b..823fcedb1 100644 --- a/pkg/cli/local_server.go +++ b/pkg/cli/local_server.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" ) -func NewLocalServer(c CommandContext) *cobra.Command { +func NewLocalServer() *cobra.Command { cmd := cli.Command(&Server{}, cobra.Command{ SilenceUsage: true, Short: "Run local development server", @@ -18,6 +18,6 @@ func NewLocalServer(c CommandContext) *cobra.Command { type Server struct { } -func (a *Server) Run(cmd *cobra.Command, args []string) error { +func (a *Server) Run(cmd *cobra.Command, _ []string) error { return local.ServerRun(cmd.Context()) } diff --git a/pkg/cli/local_start.go b/pkg/cli/local_start.go index 66d303b07..28c06a5b8 100644 --- a/pkg/cli/local_start.go +++ b/pkg/cli/local_start.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" ) -func NewLocalStart(c CommandContext) *cobra.Command { +func NewLocalStart() *cobra.Command { cmd := cli.Command(&LocalStart{}, cobra.Command{ Use: "start [flags]", Aliases: []string{"delete"}, @@ -21,7 +21,7 @@ type LocalStart struct { Delete bool `usage:"Delete existing server before starting"` } -func (a *LocalStart) Run(cmd *cobra.Command, args []string) (err error) { +func (a *LocalStart) Run(cmd *cobra.Command, _ []string) (err error) { c, err := local.NewContainer(cmd.Context()) if err != nil { return err diff --git a/pkg/cli/local_stop.go b/pkg/cli/local_stop.go index 33822ada4..8a961adfa 100644 --- a/pkg/cli/local_stop.go +++ b/pkg/cli/local_stop.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" ) -func NewLocalStop(c CommandContext) *cobra.Command { +func NewLocalStop() *cobra.Command { cmd := cli.Command(&LocalStop{}, cobra.Command{ Use: "stop [flags]", Aliases: []string{"delete"}, @@ -21,7 +21,7 @@ func NewLocalStop(c CommandContext) *cobra.Command { type LocalStop struct { } -func (a *LocalStop) Run(cmd *cobra.Command, args []string) error { +func (a *LocalStop) Run(cmd *cobra.Command, _ []string) error { c, err := local.NewContainer(cmd.Context()) if err != nil { return err diff --git a/pkg/cli/project_create.go b/pkg/cli/project_create.go index 179ea2123..fb3cbfac9 100644 --- a/pkg/cli/project_create.go +++ b/pkg/cli/project_create.go @@ -44,9 +44,8 @@ func (a *ProjectCreate) Run(cmd *cobra.Command, args []string) error { for _, projectName := range args { if err := project.Create(cmd.Context(), a.client.Options(), projectName, a.DefaultRegion, a.SupportedRegions); err != nil { return err - } else { - fmt.Println(projectName) } + fmt.Println(projectName) } return nil } diff --git a/pkg/cli/project_update.go b/pkg/cli/project_update.go index a693e5d2e..13b494a91 100644 --- a/pkg/cli/project_update.go +++ b/pkg/cli/project_update.go @@ -43,8 +43,8 @@ func (a *ProjectUpdate) Run(cmd *cobra.Command, args []string) error { } if err := project.Update(cmd.Context(), a.client.Options(), projectsDetails[0], a.DefaultRegion, a.SupportedRegions); err != nil { return err - } else { - fmt.Println(projectsDetails[0].FullName) } + + fmt.Println(projectsDetails[0].FullName) return nil } diff --git a/pkg/cli/pull.go b/pkg/cli/pull.go index 7b6c5c879..b0472685a 100644 --- a/pkg/cli/pull.go +++ b/pkg/cli/pull.go @@ -32,7 +32,7 @@ func (s *Pull) Run(cmd *cobra.Command, args []string) error { return err } - auth, err := getAuthForImage(cmd.Context(), s.client, args[0]) + auth, err := getAuthForImage(s.client, args[0]) if err != nil { return err } diff --git a/pkg/cli/push.go b/pkg/cli/push.go index ee26e2adb..e5442c676 100644 --- a/pkg/cli/push.go +++ b/pkg/cli/push.go @@ -31,7 +31,7 @@ func (s *Push) Run(cmd *cobra.Command, args []string) error { return err } - auth, err := getAuthForImage(cmd.Context(), s.client, args[0]) + auth, err := getAuthForImage(s.client, args[0]) if err != nil { return err } diff --git a/pkg/cli/rm_helper.go b/pkg/cli/rm_helper.go index 40af58316..bbfd8c0da 100644 --- a/pkg/cli/rm_helper.go +++ b/pkg/cli/rm_helper.go @@ -15,6 +15,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" k8swait "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/util/retry" + kclient "sigs.k8s.io/controller-runtime/pkg/client" "github.com/acorn-io/runtime/pkg/client" "github.com/spf13/cobra" @@ -80,31 +81,27 @@ func removeVolume(arg string, c client.Client, cmd *cobra.Command, force bool) e if v != nil { fmt.Println("Removed volume: " + vol) continue - } else { - fmt.Printf("Error: No such volume: %s\n", vol) } + + fmt.Printf("Error: No such volume: %s\n", vol) } return nil } func deleteOthers(ctx context.Context, c client.Client, arg string) (bool, error) { _, err := c.ContainerReplicaGet(ctx, arg) - if apierrors.IsNotFound(err) { - } else if err != nil { - return false, err - } else { + if err == nil { _, err = c.ContainerReplicaDelete(ctx, arg) if err == nil { fmt.Println("Removed container: " + arg) } return true, err + } else if kclient.IgnoreNotFound(err) != nil { + return false, err } _, err = c.VolumeGet(ctx, arg) - if apierrors.IsNotFound(err) { - } else if err != nil { - return false, err - } else { + if err == nil { _, err = c.VolumeDelete(ctx, arg) if err == nil { fmt.Println("Removed volume: " + arg) @@ -112,16 +109,19 @@ func deleteOthers(ctx context.Context, c client.Client, arg string) (bool, error return true, err } - _, err = c.SecretGet(ctx, arg) - if apierrors.IsNotFound(err) { - } else if err != nil { + if kclient.IgnoreNotFound(err) != nil { return false, err - } else { + } + + _, err = c.SecretGet(ctx, arg) + if err == nil { _, err = c.SecretDelete(ctx, arg) if err == nil { fmt.Println("Removed secret: " + arg) } return true, err + } else if kclient.IgnoreNotFound(err) != nil { + return false, err } return false, nil diff --git a/pkg/cli/run.go b/pkg/cli/run.go index 14b369ca6..b93077a27 100644 --- a/pkg/cli/run.go +++ b/pkg/cli/run.go @@ -160,11 +160,10 @@ func (s RunArgs) ToOpts() (client.AppRunOptions, error) { if s.EnvFile != "" { envData, err := os.ReadFile(s.EnvFile) - if os.IsNotExist(err) { - } else if err != nil { - return opts, err - } else { + if err == nil { opts.Env = append(opts.Env, v1.ParseNameValues(false, strings.Split(string(envData), "\n")...)...) + } else if err != nil && !os.IsNotExist(err) { + return opts, err } } @@ -268,7 +267,7 @@ func (s *Run) Run(cmd *cobra.Command, args []string) (err error) { } err = client.TranslateNotAllowed(err) if naErr := (*imagerules.ErrImageNotAllowed)(nil); errors.As(err, &naErr) { - if _, isPattern := autoupgrade.AutoUpgradePattern(image); isPattern { + if _, isPattern := autoupgrade.Pattern(image); isPattern { err.(*imagerules.ErrImageNotAllowed).Image = image logrus.Debugf("Valid tags for pattern %s were not allowed to run: %v", image, naErr) if choice, promptErr := rulerequest.HandleNotAllowed(s.Dangerous, image); promptErr != nil { diff --git a/pkg/cli/testdata/MockClient.go b/pkg/cli/testdata/MockClient.go index f8aacba10..9b61f8126 100644 --- a/pkg/cli/testdata/MockClient.go +++ b/pkg/cli/testdata/MockClient.go @@ -147,7 +147,7 @@ type MockClient struct { EventItem *apiv1.Event } -func (m *MockClient) KubeConfig(ctx context.Context, opts *client.KubeProxyAddressOptions) ([]byte, error) { +func (m *MockClient) KubeConfig(opts *client.KubeProxyAddressOptions) ([]byte, error) { //TODO implement me panic("implement me") } diff --git a/pkg/cli/uninstall.go b/pkg/cli/uninstall.go index 6b9246014..824d88cb8 100644 --- a/pkg/cli/uninstall.go +++ b/pkg/cli/uninstall.go @@ -27,7 +27,7 @@ type Uninstall struct { client ClientFactory } -func (u *Uninstall) Run(cmd *cobra.Command, args []string) error { +func (u *Uninstall) Run(cmd *cobra.Command, _ []string) error { return uninstall.Uninstall(cmd.Context(), &uninstall.Options{ All: u.All, Force: u.Force, diff --git a/pkg/cli/version.go b/pkg/cli/version.go index 084ac330a..c49dc7883 100644 --- a/pkg/cli/version.go +++ b/pkg/cli/version.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" ) -func NewVersion(c CommandContext) *cobra.Command { +func NewVersion() *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "Version information for acorn", diff --git a/pkg/client/app.go b/pkg/client/app.go index c57cbb095..52c1f3162 100644 --- a/pkg/client/app.go +++ b/pkg/client/app.go @@ -188,11 +188,10 @@ func (c *DefaultClient) DevSessionRenew(ctx context.Context, name string, client func (c *DefaultClient) DevSessionRelease(ctx context.Context, name string) error { // Don't release a devsession for removing apps app, err := c.AppGet(ctx, name) - if apierrors.IsNotFound(err) { - } else if err != nil { - return err - } else if !app.DeletionTimestamp.IsZero() { + if err == nil && !app.DeletionTimestamp.IsZero() { return nil + } else if kclient.IgnoreNotFound(err) != nil { + return err } devSession := &apiv1.DevSession{} diff --git a/pkg/client/client.go b/pkg/client/client.go index 87917ef2c..21928c20a 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -294,10 +294,10 @@ type Client interface { GetClient() (kclient.WithWatch, error) KubeProxyAddress(ctx context.Context, opts *KubeProxyAddressOptions) (string, error) - KubeConfig(ctx context.Context, opts *KubeProxyAddressOptions) ([]byte, error) + KubeConfig(opts *KubeProxyAddressOptions) ([]byte, error) } -type CredentialLookup func(ctx context.Context, serverAddress string) (*apiv1.RegistryAuth, bool, error) +type CredentialLookup func(serverAddress string) (*apiv1.RegistryAuth, bool, error) type AcornImageBuildOptions struct { BuilderName string @@ -445,7 +445,7 @@ func generateKubeConfig(restConfig *rest.Config) ([]byte, error) { return clientcmd.Write(*config) } -func (c *DefaultClient) getRESTConfig(ctx context.Context, opts *KubeProxyAddressOptions) (*rest.Config, error) { +func (c *DefaultClient) getRESTConfig(opts *KubeProxyAddressOptions) (*rest.Config, error) { if opts == nil || opts.Region == "" { return c.RESTConfig, nil } @@ -490,8 +490,8 @@ func (c *DefaultClient) getRESTConfig(ctx context.Context, opts *KubeProxyAddres return clientcmd.RESTConfigFromKubeConfig(parsed.Config) } -func (c *DefaultClient) KubeConfig(ctx context.Context, opts *KubeProxyAddressOptions) ([]byte, error) { - restConfig, err := c.getRESTConfig(ctx, opts) +func (c *DefaultClient) KubeConfig(opts *KubeProxyAddressOptions) ([]byte, error) { + restConfig, err := c.getRESTConfig(opts) if err != nil { return nil, err } @@ -499,7 +499,7 @@ func (c *DefaultClient) KubeConfig(ctx context.Context, opts *KubeProxyAddressOp } func (c *DefaultClient) KubeProxyAddress(ctx context.Context, opts *KubeProxyAddressOptions) (string, error) { - restConfig, err := c.getRESTConfig(ctx, opts) + restConfig, err := c.getRESTConfig(opts) if err != nil { return "", err } diff --git a/pkg/client/deferred.go b/pkg/client/deferred.go index 4149edbdb..c5f02e3c5 100644 --- a/pkg/client/deferred.go +++ b/pkg/client/deferred.go @@ -480,11 +480,11 @@ func (d *DeferredClient) GetClient() (client.WithWatch, error) { return d.Client.GetClient() } -func (d *DeferredClient) KubeConfig(ctx context.Context, opts *KubeProxyAddressOptions) ([]byte, error) { +func (d *DeferredClient) KubeConfig(opts *KubeProxyAddressOptions) ([]byte, error) { if err := d.create(); err != nil { return nil, err } - return d.Client.KubeConfig(ctx, opts) + return d.Client.KubeConfig(opts) } func (d *DeferredClient) KubeProxyAddress(ctx context.Context, opts *KubeProxyAddressOptions) (string, error) { diff --git a/pkg/client/image.go b/pkg/client/image.go index 0f52b17af..43f482c99 100644 --- a/pkg/client/image.go +++ b/pkg/client/image.go @@ -266,7 +266,7 @@ func (c *DefaultClient) ImageList(ctx context.Context) ([]apiv1.Image, error) { // FindImage finds an image if exists and returns whether it was found by tag func FindImage(ctx context.Context, c Client, name string) (*apiv1.Image, string, error) { // Early filter autoupgrade patterns, as they will fail lookup since the reference cannot be parsed - if _, ok := autoupgrade.AutoUpgradePattern(name); ok { + if _, ok := autoupgrade.Pattern(name); ok { return nil, "", images.ErrImageNotFound{ImageSearch: name} } diff --git a/pkg/client/multi.go b/pkg/client/multi.go index e751b7c48..c7ab65324 100644 --- a/pkg/client/multi.go +++ b/pkg/client/multi.go @@ -687,12 +687,12 @@ func (m *MultiClient) GetClient() (kclient.WithWatch, error) { return c.GetClient() } -func (m *MultiClient) KubeConfig(ctx context.Context, opts *KubeProxyAddressOptions) ([]byte, error) { +func (m *MultiClient) KubeConfig(opts *KubeProxyAddressOptions) ([]byte, error) { c, err := m.Factory.ForProject(context.Background(), m.Factory.DefaultProject()) if err != nil { panic(err) } - return c.KubeConfig(ctx, opts) + return c.KubeConfig(opts) } func (m *MultiClient) KubeProxyAddress(ctx context.Context, opts *KubeProxyAddressOptions) (string, error) { diff --git a/pkg/computeclasses/computeclasses.go b/pkg/computeclasses/computeclasses.go index 01cb4067f..ddd74470b 100644 --- a/pkg/computeclasses/computeclasses.go +++ b/pkg/computeclasses/computeclasses.go @@ -23,7 +23,7 @@ var ( ErrInvalidClass = errors.New("compute class is invalid") ) -type memoryQuantities struct { +type MemoryQuantities struct { Max *resource.Quantity Min *resource.Quantity Def *resource.Quantity @@ -37,24 +37,24 @@ func parseQuantity(memory string) (resource.Quantity, error) { return resource.ParseQuantity(memory) } -func ParseComputeClassMemory(memory apiv1.ComputeClassMemory) (memoryQuantities, error) { - var quantities memoryQuantities +func ParseComputeClassMemory(memory apiv1.ComputeClassMemory) (MemoryQuantities, error) { + var quantities MemoryQuantities minInt, err := parseQuantity(memory.Min) if err != nil { - return memoryQuantities{}, err + return MemoryQuantities{}, err } quantities.Min = &minInt maxInt, err := parseQuantity(memory.Max) if err != nil { - return memoryQuantities{}, err + return MemoryQuantities{}, err } quantities.Max = &maxInt defInt, err := parseQuantity(memory.Default) if err != nil { - return memoryQuantities{}, err + return MemoryQuantities{}, err } quantities.Def = &defInt @@ -62,7 +62,7 @@ func ParseComputeClassMemory(memory apiv1.ComputeClassMemory) (memoryQuantities, for i, value := range memory.Values { valueInt, err := parseQuantity(value) if err != nil { - return memoryQuantities{}, err + return MemoryQuantities{}, err } quantities.Values[i] = &valueInt } @@ -70,14 +70,14 @@ func ParseComputeClassMemory(memory apiv1.ComputeClassMemory) (memoryQuantities, return quantities, nil } -func ParseComputeClassMemoryInternal(memory internaladminv1.ComputeClassMemory) (memoryQuantities, error) { +func ParseComputeClassMemoryInternal(memory internaladminv1.ComputeClassMemory) (MemoryQuantities, error) { if memory.RequestScaler < 0 || memory.RequestScaler > 1 { - return memoryQuantities{}, errors.New("request scaler value must be between 0 and 1, inclusive") + return MemoryQuantities{}, errors.New("request scaler value must be between 0 and 1, inclusive") } return ParseComputeClassMemory(apiv1.ComputeClassMemoryFromInternalAdmin(memory)) } -func memoryInValues(parsedMemory memoryQuantities, memory resource.Quantity) bool { +func memoryInValues(parsedMemory MemoryQuantities, memory resource.Quantity) bool { value := memory.Value() for _, allowedMemory := range parsedMemory.Values { if allowedMemory != nil && value == allowedMemory.Value() { diff --git a/pkg/config/config.go b/pkg/config/config.go index c09153cab..134fb9152 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -80,8 +80,8 @@ func complete(ctx context.Context, c *apiv1.Config, getter kclient.Reader, inclu if c.BuilderPerProject == nil { c.BuilderPerProject = profile.BuilderPerProject } - if z.Dereference(c.HttpEndpointPattern) == "" { - c.HttpEndpointPattern = profile.HttpEndpointPattern + if z.Dereference(c.HTTPEndpointPattern) == "" { + c.HTTPEndpointPattern = profile.HTTPEndpointPattern } if c.WorkloadMemoryDefault == nil { c.WorkloadMemoryDefault = profile.WorkloadMemoryDefault @@ -201,7 +201,7 @@ func setClusterDomains(ctx context.Context, c *apiv1.Config, getter kclient.Read if shouldLookupAcornDNSDomain { dnsSecret := &corev1.Secret{} err = getter.Get(ctx, router.Key(system.Namespace, system.DNSSecretName), dnsSecret) - if err != nil && !apierror.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return err } domain := string(dnsSecret.Data["domain"]) @@ -335,8 +335,8 @@ func merge(oldConfig, newConfig *apiv1.Config) *apiv1.Config { } mergedConfig.ClusterDomains = newConfig.ClusterDomains } - if newConfig.HttpEndpointPattern != nil { - mergedConfig.HttpEndpointPattern = newConfig.HttpEndpointPattern + if newConfig.HTTPEndpointPattern != nil { + mergedConfig.HTTPEndpointPattern = newConfig.HTTPEndpointPattern } if newConfig.AcornDNS != nil { mergedConfig.AcornDNS = newConfig.AcornDNS @@ -557,7 +557,7 @@ func Set(ctx context.Context, client kclient.Client, cfg *apiv1.Config) error { Name: system.Namespace, }, }) - if err != nil && !apierror.IsAlreadyExists(err) && !meta.IsNoMatchError(err) { + if kclient.IgnoreNotFound(err) != nil && !meta.IsNoMatchError(err) { return err } diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index aab765e48..095c02919 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestAcornDNSDisabledNoLookupsHappen(t *testing.T) { +func TestAcornDNSDisabledNoLookupsHappen(*testing.T) { s := "not exactly disabled, but any string that doesn't equal" + " auto or enabled should be treated as disabled" _ = complete(context.Background(), &apiv1.Config{ diff --git a/pkg/controller/acornimagebuildinstance/buildinstance.go b/pkg/controller/acornimagebuildinstance/buildinstance.go index 03f7a0342..63e4e9ed4 100644 --- a/pkg/controller/acornimagebuildinstance/buildinstance.go +++ b/pkg/controller/acornimagebuildinstance/buildinstance.go @@ -6,7 +6,7 @@ import ( "github.com/acorn-io/runtime/pkg/config" ) -func MarkRecorded(req router.Request, resp router.Response) error { +func MarkRecorded(req router.Request, _ router.Response) error { cfg, err := config.Get(req.Ctx, req.Client) if err != nil { return err diff --git a/pkg/controller/appdefinition/acorn.go b/pkg/controller/appdefinition/acorn.go index f58aba604..94330b5aa 100644 --- a/pkg/controller/appdefinition/acorn.go +++ b/pkg/controller/appdefinition/acorn.go @@ -166,7 +166,7 @@ func scopeLinks(app *v1.AppInstance, bindings v1.ServiceBindings) (result v1.Ser func toAcorn(appInstance *v1.AppInstance, tag name.Reference, pullSecrets *PullSecrets, acornName, configHash string, acorn v1.Acorn) *v1.AppInstance { var image string - pattern, isPattern := autoupgrade.AutoUpgradePattern(acorn.Image) + pattern, isPattern := autoupgrade.Pattern(acorn.Image) if isPattern { image = acorn.Image diff --git a/pkg/controller/appdefinition/deploy.go b/pkg/controller/appdefinition/deploy.go index cd8204b34..ba0ab5e6a 100644 --- a/pkg/controller/appdefinition/deploy.go +++ b/pkg/controller/appdefinition/deploy.go @@ -2,7 +2,6 @@ package appdefinition import ( "crypto/sha256" - _ "embed" "encoding/hex" "encoding/json" "errors" @@ -98,36 +97,41 @@ func DeploySpec(req router.Request, resp router.Response) (err error) { } else if len(objs) > 0 { result = append(result, objs...) } - if objs, err := ToFunctions(req, appInstance, tag, pullSecrets, interpolator); err != nil { + objs, err := ToFunctions(req, appInstance, tag, pullSecrets, interpolator) + if err != nil { return err - } else { - result = append(result, objs...) } - if objs, err := toRouters(req.Ctx, req.Client, appInstance); err != nil { + result = append(result, objs...) + + objs, err = toRouters(req.Ctx, req.Client, appInstance) + if err != nil { return err - } else { - result = append(result, objs...) } - if objs, err := toJobs(req, appInstance, pullSecrets, tag, interpolator); err != nil { + result = append(result, objs...) + + objs, err = toJobs(req, appInstance, pullSecrets, tag, interpolator) + if err != nil { return err - } else { - result = append(result, objs...) } - if objs, err := services.ToAcornServices(req.Ctx, req.Client, interpolator, appInstance); err != nil { + result = append(result, objs...) + + objs, err = services.ToAcornServices(req.Ctx, req.Client, interpolator, appInstance) + if err != nil { return err - } else { - result = append(result, objs...) } - if objs, err := toPVCs(req, appInstance); err != nil { + result = append(result, objs...) + + objs, err = toPVCs(req, appInstance) + if err != nil { return err - } else { - result = append(result, objs...) } - if objs, err := toAcorns(req, appInstance, tag, pullSecrets); err != nil { + result = append(result, objs...) + + objs, err = toAcorns(req, appInstance, tag, pullSecrets) + if err != nil { return err - } else { - result = append(result, objs...) } + result = append(result, objs...) // Secrets go in first so that they are created/updated before things that depend on them. resp.Objects(pullSecrets.Objects()...) diff --git a/pkg/controller/appdefinition/error.go b/pkg/controller/appdefinition/error.go index e9ecfd514..92551e8b1 100644 --- a/pkg/controller/appdefinition/error.go +++ b/pkg/controller/appdefinition/error.go @@ -10,7 +10,7 @@ import ( kclient "sigs.k8s.io/controller-runtime/pkg/client" ) -func OnError(req router.Request, resp router.Response, err error) error { +func OnError(req router.Request, _ router.Response, err error) error { if apierrors.IsConflict(err) { return err } diff --git a/pkg/controller/appdefinition/generation.go b/pkg/controller/appdefinition/generation.go index 513159f93..6a72d8a79 100644 --- a/pkg/controller/appdefinition/generation.go +++ b/pkg/controller/appdefinition/generation.go @@ -6,7 +6,7 @@ import ( "github.com/acorn-io/runtime/pkg/autoupgrade" ) -func UpdateObservedFields(req router.Request, resp router.Response) error { +func UpdateObservedFields(req router.Request, _ router.Response) error { app := req.Object.(*v1.AppInstance) app.Status.ObservedImageDigest = app.Status.AppImage.Digest app.Status.ObservedGeneration = app.Generation diff --git a/pkg/controller/appdefinition/namespace.go b/pkg/controller/appdefinition/namespace.go index a01217fe7..949cab46b 100644 --- a/pkg/controller/appdefinition/namespace.go +++ b/pkg/controller/appdefinition/namespace.go @@ -59,7 +59,7 @@ func RequireNamespace(h router.Handler) router.Handler { }) } -func AddAcornProjectLabel(req router.Request, resp router.Response) error { +func AddAcornProjectLabel(req router.Request, _ router.Response) error { app := req.Object.(*v1.AppInstance) var projectNamespace corev1.Namespace diff --git a/pkg/controller/appdefinition/pullappimage.go b/pkg/controller/appdefinition/pullappimage.go index d5e08c8ce..0eb30865b 100644 --- a/pkg/controller/appdefinition/pullappimage.go +++ b/pkg/controller/appdefinition/pullappimage.go @@ -9,7 +9,6 @@ import ( v1 "github.com/acorn-io/runtime/pkg/apis/internal.acorn.io/v1" "github.com/acorn-io/runtime/pkg/autoupgrade" "github.com/acorn-io/runtime/pkg/condition" - "github.com/acorn-io/runtime/pkg/event" "github.com/acorn-io/runtime/pkg/images" "github.com/acorn-io/runtime/pkg/tags" imagename "github.com/google/go-containerregistry/pkg/name" @@ -17,7 +16,7 @@ import ( kclient "sigs.k8s.io/controller-runtime/pkg/client" ) -func PullAppImage(transport http.RoundTripper, recorder event.Recorder) router.HandlerFunc { +func PullAppImage(transport http.RoundTripper) router.HandlerFunc { return pullAppImage(transport, pullClient{ pull: images.PullAppImage, }) @@ -109,48 +108,44 @@ func pullAppImage(transport http.RoundTripper, client pullClient) router.Handler // If the determined image is not new, this returns empty strings. func determineTargetImage(appInstance *v1.AppInstance) (string, string) { _, on := autoupgrade.Mode(appInstance.Spec) - pattern, isPattern := autoupgrade.AutoUpgradePattern(appInstance.Spec.Image) + pattern, isPattern := autoupgrade.Pattern(appInstance.Spec.Image) if on { if appInstance.Status.AvailableAppImage != "" || appInstance.Status.ConfirmUpgradeAppImage != "" { if appInstance.Status.AvailableAppImage != "" { // AvailableAppImage is not blank, use it and reset the other fields return appInstance.Status.AvailableAppImage, "" - } else { - // ConfirmUpgradeAppImage is not blank. Normally, we shouldn't get the desiredImage from it. That should - // be done explicitly by the user via the apps/confirmupgrade subresource (which would set it to the - // AvailableAppImage field). But if AppImage.ID is blank, this app has never had an image pulled. So, do the initial pull. - if appInstance.Status.Staged.AppImage.Name == "" { - return appInstance.Status.ConfirmUpgradeAppImage, "" - } else { - return "", fmt.Sprintf("confirm upgrade to %v", appInstance.Status.ConfirmUpgradeAppImage) - } } - } else { - // Neither AvailableAppImage nor ConfirmUpgradeAppImage is set. - if isPattern { - if appInstance.Status.Staged.AppImage.Name == "" { - // Need to trigger a sync since this app has never had a concrete image set - autoupgrade.Sync() - return "", fmt.Sprintf("waiting for image to satisfy auto-upgrade tag %v", pattern) - } else { - return "", "" - } - } else { - if appInstance.Spec.Image == appInstance.Status.Staged.AppImage.Name { - return "", "" - } else { - return appInstance.Spec.Image, "" - } + // ConfirmUpgradeAppImage is not blank. Normally, we shouldn't get the desiredImage from it. That should + // be done explicitly by the user via the apps/confirmupgrade subresource (which would set it to the + // AvailableAppImage field). But if AppImage.ID is blank, this app has never had an image pulled. So, do the initial pull. + if appInstance.Status.Staged.AppImage.Name == "" { + return appInstance.Status.ConfirmUpgradeAppImage, "" } + return "", fmt.Sprintf("confirm upgrade to %v", appInstance.Status.ConfirmUpgradeAppImage) } - } else { - // Auto-upgrade is off. Only need to pull if spec and status are not equal or we're trying to trigger a repull - if appInstance.Spec.Image != appInstance.Status.Staged.AppImage.Name || - appInstance.Status.AvailableAppImage == appInstance.Spec.Image { - return appInstance.Spec.Image, "" - } else { + + // Neither AvailableAppImage nor ConfirmUpgradeAppImage is set. + if isPattern { + if appInstance.Status.Staged.AppImage.Name == "" { + // Need to trigger a sync since this app has never had a concrete image set + autoupgrade.Sync() + return "", fmt.Sprintf("waiting for image to satisfy auto-upgrade tag %v", pattern) + } + return "", "" + } + + if appInstance.Spec.Image == appInstance.Status.Staged.AppImage.Name { return "", "" } + + return appInstance.Spec.Image, "" + } + + // Auto-upgrade is off. Only need to pull if spec and status are not equal or we're trying to trigger a repull + if appInstance.Spec.Image != appInstance.Status.Staged.AppImage.Name || + appInstance.Status.AvailableAppImage == appInstance.Spec.Image { + return appInstance.Spec.Image, "" } + return "", "" } diff --git a/pkg/controller/appdefinition/volume.go b/pkg/controller/appdefinition/volume.go index b8f43dfe4..76987c578 100644 --- a/pkg/controller/appdefinition/volume.go +++ b/pkg/controller/appdefinition/volume.go @@ -170,12 +170,12 @@ func toPVCs(req router.Request, appInstance *v1.AppInstance) (result []kclient.O volumeClassName = pv.Labels[labels.AcornVolumeClass] } - if volClass, ok := volumeClasses[volumeClassName]; !ok { + volClass, ok := volumeClasses[volumeClassName] + if !ok { return nil, fmt.Errorf("%s has an invalid volume class %s", vol, volumeBinding.Class) - } else { - pvc.Spec.StorageClassName = &volClass.StorageClassName - pvc.Labels[labels.AcornVolumeClass] = volClass.Name } + pvc.Spec.StorageClassName = &volClass.StorageClassName + pvc.Labels[labels.AcornVolumeClass] = volClass.Name if volumeBinding.Size != "" { pvc.Spec.Resources.Requests[corev1.ResourceStorage] = *v1.MustParseResourceQuantity(volumeBinding.Size) @@ -183,12 +183,12 @@ func toPVCs(req router.Request, appInstance *v1.AppInstance) (result []kclient.O } else { if volumeRequest.Class != "" { // Specifically allowing volume classes that are inactive. - if volClass, ok := volumeClasses[volumeRequest.Class]; !ok && volumeBinding.Class == "" { + volClass, ok := volumeClasses[volumeRequest.Class] + if !ok { return nil, fmt.Errorf("%s has an invalid volume class %s", vol, volumeRequest.Class) - } else { - pvc.Spec.StorageClassName = &volClass.StorageClassName - pvc.Labels[labels.AcornVolumeClass] = volClass.Name } + pvc.Spec.StorageClassName = &volClass.StorageClassName + pvc.Labels[labels.AcornVolumeClass] = volClass.Name } pvName, err := LookupExistingPV(req, appInstance, vol) if err != nil { diff --git a/pkg/controller/appdefinition/volume_bind.go b/pkg/controller/appdefinition/volume_bind.go index 643a88e4a..81299f53d 100644 --- a/pkg/controller/appdefinition/volume_bind.go +++ b/pkg/controller/appdefinition/volume_bind.go @@ -8,7 +8,7 @@ import ( apierror "k8s.io/apimachinery/pkg/api/errors" ) -func ReleaseVolume(req router.Request, resp router.Response) error { +func ReleaseVolume(req router.Request, _ router.Response) error { pv := req.Object.(*corev1.PersistentVolume) if pv.Labels[labels.AcornManaged] == "true" && pv.Status.Phase == corev1.VolumeReleased && diff --git a/pkg/controller/appstatus/containers.go b/pkg/controller/appstatus/containers.go index 60108f3bc..2bd5b9289 100644 --- a/pkg/controller/appstatus/containers.go +++ b/pkg/controller/appstatus/containers.go @@ -10,7 +10,6 @@ import ( "github.com/acorn-io/runtime/pkg/ports" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - apierror "k8s.io/apimachinery/pkg/api/errors" klabels "k8s.io/apimachinery/pkg/labels" "k8s.io/kubectl/pkg/util/deployment" kclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -49,11 +48,7 @@ func (a *appStatusRenderer) readContainers() error { dep := appsv1.Deployment{} err = a.c.Get(a.ctx, router.Key(a.app.Status.Namespace, containerName), &dep) - if apierror.IsNotFound(err) { - // do nothing - } else if err != nil { - return err - } else { + if err == nil { cs.Defined = true cs.UpToDate = dep.Annotations[labels.AcornAppGeneration] == strconv.Itoa(int(a.app.Generation)) && dep.Annotations[labels.AcornConfigHashAnnotation] == hash cs.ReadyReplicaCount = dep.Status.ReadyReplicas @@ -67,6 +62,8 @@ func (a *appStatusRenderer) readContainers() error { return err } } + } else if kclient.IgnoreNotFound(err) != nil { + return err } if cs.LinkOverride != "" { diff --git a/pkg/controller/appstatus/functions.go b/pkg/controller/appstatus/functions.go index 9c23033d0..890b9bd8c 100644 --- a/pkg/controller/appstatus/functions.go +++ b/pkg/controller/appstatus/functions.go @@ -9,7 +9,7 @@ import ( "github.com/acorn-io/runtime/pkg/labels" "github.com/acorn-io/runtime/pkg/ports" appsv1 "k8s.io/api/apps/v1" - apierror "k8s.io/apimachinery/pkg/api/errors" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) func (a *appStatusRenderer) readFunctions() error { @@ -45,11 +45,7 @@ func (a *appStatusRenderer) readFunctions() error { dep := appsv1.Deployment{} err = a.c.Get(a.ctx, router.Key(a.app.Status.Namespace, functionName), &dep) - if apierror.IsNotFound(err) { - // do nothing - } else if err != nil { - return err - } else { + if err == nil { cs.Defined = true cs.UpToDate = dep.Annotations[labels.AcornAppGeneration] == strconv.Itoa(int(a.app.Generation)) && dep.Annotations[labels.AcornConfigHashAnnotation] == hash cs.ReadyReplicaCount = dep.Status.ReadyReplicas @@ -63,6 +59,8 @@ func (a *appStatusRenderer) readFunctions() error { return err } } + } else if kclient.IgnoreNotFound(err) != nil { + return err } if cs.LinkOverride != "" { diff --git a/pkg/controller/appstatus/jobs.go b/pkg/controller/appstatus/jobs.go index 5a6cedb8b..1ae836b37 100644 --- a/pkg/controller/appstatus/jobs.go +++ b/pkg/controller/appstatus/jobs.go @@ -13,6 +13,7 @@ import ( batchv1 "k8s.io/api/batch/v1" apierror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) func (a *appStatusRenderer) readJobs() error { @@ -69,11 +70,7 @@ func (a *appStatusRenderer) readJobs() error { if apierror.IsNotFound(err) { var cronJob batchv1.CronJob err := a.c.Get(a.ctx, router.Key(a.app.Status.Namespace, jobName), &cronJob) - if apierror.IsNotFound(err) { - // do nothing - } else if err != nil { - return err - } else { + if err == nil { c.CreationTime = &cronJob.CreationTimestamp c.LastRun = cronJob.Status.LastScheduleTime c.CompletionTime = cronJob.Status.LastSuccessfulTime @@ -100,23 +97,25 @@ func (a *appStatusRenderer) readJobs() error { return err } c.NextRun = nextRun + } else if kclient.IgnoreNotFound(err) != nil { + return err } } else if err != nil { return err - } else { - c.CreationTime = &job.CreationTimestamp - c.CompletionTime = job.Status.CompletionTime - c.LastRun = job.Status.StartTime - c.Defined = true - c.UpToDate = job.Annotations[labels.AcornAppGeneration] == strconv.Itoa(int(a.app.Generation)) && (c.Skipped || job.Annotations[labels.AcornConfigHashAnnotation] == hash) - if job.Status.Succeeded > 0 { - c.CreateEventSucceeded = true - c.Ready = c.UpToDate - } else if job.Status.Failed > 0 { - c.ErrorCount = int(job.Status.Failed) - } else if job.Status.Active > 0 && c.RunningCount == 0 { - c.RunningCount = int(job.Status.Active) - } + } + + c.CreationTime = &job.CreationTimestamp + c.CompletionTime = job.Status.CompletionTime + c.LastRun = job.Status.StartTime + c.Defined = true + c.UpToDate = job.Annotations[labels.AcornAppGeneration] == strconv.Itoa(int(a.app.Generation)) && (c.Skipped || job.Annotations[labels.AcornConfigHashAnnotation] == hash) + if job.Status.Succeeded > 0 { + c.CreateEventSucceeded = true + c.Ready = c.UpToDate + } else if job.Status.Failed > 0 { + c.ErrorCount = int(job.Status.Failed) + } else if job.Status.Active > 0 && c.RunningCount == 0 { + c.RunningCount = int(job.Status.Active) } if c.LinkOverride != "" { diff --git a/pkg/controller/appstatus/replicas.go b/pkg/controller/appstatus/replicas.go index 5f74448d1..6ca746cd4 100644 --- a/pkg/controller/appstatus/replicas.go +++ b/pkg/controller/appstatus/replicas.go @@ -52,7 +52,7 @@ func (a *appStatusRenderer) getReplicasSummary(nameLabel string) (map[string]v1. } } - transition, errored := containerMessages(&pod, append(pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses...)) + transition, errored := containerMessages(append(pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses...)) summary.TransitioningMessages = append(summary.TransitioningMessages, transition...) summary.ErrorMessages = append(summary.ErrorMessages, errored...) @@ -68,7 +68,7 @@ func (a *appStatusRenderer) getReplicasSummary(nameLabel string) (map[string]v1. return result, nil } -func containerMessages(pod *corev1.Pod, status []corev1.ContainerStatus) (transitionMessages, errorMessages []string) { +func containerMessages(status []corev1.ContainerStatus) (transitionMessages, errorMessages []string) { for _, container := range status { if container.State.Waiting != nil { if container.LastTerminationState.Terminated != nil { diff --git a/pkg/controller/builder/builder.go b/pkg/controller/builder/builder.go index 3809d7ee5..442577859 100644 --- a/pkg/controller/builder/builder.go +++ b/pkg/controller/builder/builder.go @@ -30,7 +30,7 @@ func createBuilderObjects(req router.Request, resp router.Response) (string, str return "", "", nil, err } - depotToken, depotProjectId, err := getDepotKey(req.Ctx, req.Client, builder.Namespace) + depotToken, depotProjectID, err := getDepotKey(req.Ctx, req.Client, builder.Namespace) if err != nil { return "", "", nil, err } @@ -46,7 +46,7 @@ func createBuilderObjects(req router.Request, resp router.Response) (string, str } objs := imagesystem.BuilderObjects(name, system.ImagesNamespace, forNamespace, system.DefaultImage(), - pubKey, privKey, depotToken, depotProjectId, builder.Status.UUID, registryDNS, cfg) + pubKey, privKey, depotToken, depotProjectID, builder.Status.UUID, registryDNS, cfg) if *cfg.BuilderPerProject { resp.Objects(objs...) diff --git a/pkg/controller/config/devconfig.go b/pkg/controller/config/devconfig.go index de8471313..dce34efc3 100644 --- a/pkg/controller/config/devconfig.go +++ b/pkg/controller/config/devconfig.go @@ -8,8 +8,8 @@ import ( "github.com/acorn-io/runtime/pkg/system" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) func PurgeDevConfig(req router.Request, resp router.Response) error { @@ -38,7 +38,7 @@ func PurgeDevConfig(req router.Request, resp router.Response) error { Namespace: system.Namespace, }, }) - if err != nil && !apierror.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return err } } diff --git a/pkg/controller/config/dns.go b/pkg/controller/config/dns.go index c2e1ef9b1..3299aad34 100644 --- a/pkg/controller/config/dns.go +++ b/pkg/controller/config/dns.go @@ -14,10 +14,9 @@ import ( "github.com/acorn-io/runtime/pkg/system" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/strings/slices" - "sigs.k8s.io/controller-runtime/pkg/client" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) func NewDNSConfigHandler() router.Handler { @@ -42,7 +41,7 @@ func (h *configHandler) Handle(req router.Request, resp router.Response) error { dnsSecret := &corev1.Secret{} err = req.Client.Get(req.Ctx, router.Key(system.Namespace, system.DNSSecretName), dnsSecret) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return err } domain := string(dnsSecret.Data["domain"]) @@ -83,7 +82,7 @@ func (h *configHandler) Handle(req router.Request, resp router.Response) error { // Secret exists. Update it sec := &corev1.Secret{} - err = req.Client.Get(req.Ctx, client.ObjectKey{ + err = req.Client.Get(req.Ctx, kclient.ObjectKey{ Name: system.DNSSecretName, Namespace: system.Namespace, }, uncached.Get(sec)) @@ -101,8 +100,8 @@ func (h *configHandler) Handle(req router.Request, resp router.Response) error { } } - if !strings.EqualFold(*cfg.LetsEncrypt, "disabled") && domain != "" && token != "" { - if err := tls.ProvisionWildcardCert(req, resp, domain, token); err != nil { + if !strings.EqualFold(*cfg.LetsEncrypt, "disabled") && domain != "" { + if err := tls.ProvisionWildcardCert(req, resp, domain); err != nil { return err } } diff --git a/pkg/controller/config/dns_test.go b/pkg/controller/config/dns_test.go index 4304062cf..e215ca32a 100644 --- a/pkg/controller/config/dns_test.go +++ b/pkg/controller/config/dns_test.go @@ -139,24 +139,24 @@ func TestDisabling(t *testing.T) { // simply not panic. This is enough for the handler to assume the call succeeded and move on type mockClient struct{} -func (t *mockClient) CreateRecords(endpoint, domain, token string, records []dns.RecordRequest) error { +func (t *mockClient) CreateRecords(string, string, string, []dns.RecordRequest) error { return nil } -func (t *mockClient) ReserveDomain(endpoint string) (string, string, error) { +func (t *mockClient) ReserveDomain(string) (string, string, error) { return "test.oss-acorn.io", "token", nil } -func (t *mockClient) Renew(endpoint, domain, token string, renew dns.RenewRequest) (dns.RenewResponse, error) { +func (t *mockClient) Renew(string, string, string, dns.RenewRequest) (dns.RenewResponse, error) { //TODO implement me panic("implement me") } -func (t *mockClient) DeleteRecord(endpoint, domain, fqdn, token string) error { +func (t *mockClient) DeleteRecord(string, string, string, string) error { //TODO implement me panic("implement me") } -func (t *mockClient) PurgeRecords(endpoint, domain, token string) error { +func (t *mockClient) PurgeRecords(string, string, string) error { return nil } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index aaf36f4a4..4877d167a 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -30,7 +30,7 @@ import ( ) var ( - dnsRenewPeriodHours = 24 * time.Hour + dnsRenewPeriod = 24 * time.Hour ) type Controller struct { @@ -76,7 +76,7 @@ func New(ctx context.Context) (*Controller, error) { return nil, err } - err = routes(router, cfg, registryTransport, event.NewRecorder(client)) + err = routes(router, cfg, registryTransport) if err != nil { return nil, err } @@ -101,15 +101,14 @@ func (c *Controller) Start(ctx context.Context) error { if _, err := config.Get(ctx, c.Router.Backend()); err == nil { success = true break - } else { - time.Sleep(time.Millisecond * 100) } + time.Sleep(time.Millisecond * 100) } if !success { panic("couldn't initialize client cache") } dnsInit := dns.NewDaemon(c.Router.Backend()) - go wait.UntilWithContext(ctx, dnsInit.RenewAndSync, dnsRenewPeriodHours) + go wait.UntilWithContext(ctx, dnsInit.RenewAndSync, dnsRenewPeriod) autoupgrade.StartSync(ctx, c.Router.Backend()) }() diff --git a/pkg/controller/devsession/devsession.go b/pkg/controller/devsession/devsession.go index 45524cfbb..57b59c521 100644 --- a/pkg/controller/devsession/devsession.go +++ b/pkg/controller/devsession/devsession.go @@ -28,7 +28,7 @@ func ExpireDevSession(req router.Request, resp router.Response) error { func OverlayDevSession(next router.Handler) router.Handler { return router.HandlerFunc(func(req router.Request, resp router.Response) error { - oldGeneration, err := updateAppForDevSession(req, resp) + oldGeneration, err := updateAppForDevSession(req) if err != nil { return err } @@ -78,7 +78,7 @@ func mergeSecretBindings(base, overlay v1.AppInstanceSpec) (result []v1.SecretBi return } -func updateAppForDevSession(req router.Request, resp router.Response) (int64, error) { +func updateAppForDevSession(req router.Request) (int64, error) { if req.Object == nil { return 0, nil } diff --git a/pkg/controller/gc/gc.go b/pkg/controller/gc/gc.go index b3dd6175a..2926d266f 100644 --- a/pkg/controller/gc/gc.go +++ b/pkg/controller/gc/gc.go @@ -7,7 +7,7 @@ import ( corev1 "k8s.io/api/core/v1" ) -func GCOrphans(req router.Request, resp router.Response) error { +func Orphans(req router.Request, _ router.Response) error { if !req.Object.GetDeletionTimestamp().IsZero() { return nil } diff --git a/pkg/controller/images/images.go b/pkg/controller/images/images.go index 4a1577a15..7ef7e16c1 100644 --- a/pkg/controller/images/images.go +++ b/pkg/controller/images/images.go @@ -15,7 +15,7 @@ import ( func MigrateRemoteImages(req router.Request, _ router.Response) error { image := req.Object.(*v1.ImageInstance) - if !image.ZZ_Remote || image.Repo == "" || image.Digest == "" { + if !image.ZZRemote || image.Repo == "" || image.Digest == "" { return nil } apps := &v1.AppInstanceList{} diff --git a/pkg/controller/jobs/finalize.go b/pkg/controller/jobs/finalize.go index eae930b97..788d144d4 100644 --- a/pkg/controller/jobs/finalize.go +++ b/pkg/controller/jobs/finalize.go @@ -20,7 +20,7 @@ const ( DestroyJobFinalizer = "jobs.acorn.io/destroy" ) -func JobPodOrphanCleanup(req router.Request, resp router.Response) error { +func JobPodOrphanCleanup(req router.Request, _ router.Response) error { pod := req.Object.(*corev1.Pod) // pods with "controller-uid" and "job-name" on them are created by batchv1.Job if pod.Labels[labels.AcornJobName] != "" && @@ -32,7 +32,7 @@ func JobPodOrphanCleanup(req router.Request, resp router.Response) error { return nil } -func JobCleanup(req router.Request, resp router.Response) error { +func JobCleanup(req router.Request, _ router.Response) error { job := req.Object.(*batchv1.Job) if job.Status.Failed == 0 || job.Spec.Selector == nil { return nil @@ -119,10 +119,10 @@ func FinalizeDestroyJob(req router.Request, resp router.Response) error { if done(job) { continue - } else { - resp.DisablePrune() - resp.RetryAfter(15 * time.Second) } + + resp.DisablePrune() + resp.RetryAfter(15 * time.Second) } return nil diff --git a/pkg/controller/jobs/output.go b/pkg/controller/jobs/output.go index c289f242d..ae211eaa4 100644 --- a/pkg/controller/jobs/output.go +++ b/pkg/controller/jobs/output.go @@ -112,7 +112,7 @@ func (h *Handler) runCommand(ctx context.Context, pod *corev1.Pod, command ...st }, nil } -func (h *Handler) SaveJobOutput(req router.Request, resp router.Response) error { +func (h *Handler) SaveJobOutput(req router.Request, _ router.Response) error { pod := req.Object.(*corev1.Pod) jobName := pod.Labels[labels.AcornJobName] @@ -154,7 +154,7 @@ func (h *Handler) SaveJobOutput(req router.Request, resp router.Response) error return err } - secretName := jobs.GetJobOutputSecretName(req.Ctx, pod.Namespace, jobName) + secretName := jobs.GetJobOutputSecretName(pod.Namespace, jobName) data, err := h.runCommand(req.Ctx, pod, "/usr/local/bin/acorn-job-get-output") if err != nil { diff --git a/pkg/controller/local/pods.go b/pkg/controller/local/pods.go index ac990ac9b..15f6c9192 100644 --- a/pkg/controller/local/pods.go +++ b/pkg/controller/local/pods.go @@ -6,7 +6,7 @@ import ( corev1 "k8s.io/api/core/v1" ) -func DeletePods(req router.Request, resp router.Response) error { +func DeletePods(req router.Request, _ router.Response) error { pod := req.Object.(*corev1.Pod) for _, container := range pod.Spec.Containers { if container.Image == system.LocalImage { diff --git a/pkg/controller/local/storage.go b/pkg/controller/local/storage.go index 775410185..a239d1bc1 100644 --- a/pkg/controller/local/storage.go +++ b/pkg/controller/local/storage.go @@ -28,7 +28,7 @@ func NewCreateFolder() (router.Handler, error) { return router.HandlerFunc(createFolder), nil } -func CleanupStorage(req router.Request, resp router.Response) error { +func CleanupStorage(req router.Request, _ router.Response) error { pv := req.Object.(*corev1.PersistentVolume) if pv.DeletionTimestamp.IsZero() || len(pv.Finalizers) == 0 || pv.Finalizers[0] != FinalizerID { return nil @@ -48,7 +48,7 @@ func CleanupStorage(req router.Request, resp router.Response) error { return req.Client.Update(req.Ctx, pv) } -func createFolder(req router.Request, resp router.Response) error { +func createFolder(req router.Request, _ router.Response) error { pvc := req.Object.(*corev1.PersistentVolumeClaim) if z.Dereference(pvc.Spec.StorageClassName) != storageClass || pvc.Status.Phase != corev1.ClaimPending || pvc.Spec.VolumeName != "" { return nil diff --git a/pkg/controller/permissions/consumerpermissions.go b/pkg/controller/permissions/consumerpermissions.go index 23c168690..890f1acfa 100644 --- a/pkg/controller/permissions/consumerpermissions.go +++ b/pkg/controller/permissions/consumerpermissions.go @@ -115,7 +115,7 @@ func CheckConsumerPermsAuthorized(ctx context.Context, c kclient.Client, appInst return denied, nil } -func ConsumerPermissions(req router.Request, resp router.Response) error { +func ConsumerPermissions(req router.Request, _ router.Response) error { app := req.Object.(*v1.AppInstance) iraEnabled, err := config.GetFeature(req.Ctx, req.Client, profiles.FeatureImageRoleAuthorizations) diff --git a/pkg/controller/pvc/markandsave.go b/pkg/controller/pvc/markandsave.go index 0e22fbca1..c7bb9d3bd 100644 --- a/pkg/controller/pvc/markandsave.go +++ b/pkg/controller/pvc/markandsave.go @@ -10,7 +10,7 @@ import ( kclient "sigs.k8s.io/controller-runtime/pkg/client" ) -func MarkAndSave(req router.Request, resp router.Response) error { +func MarkAndSave(req router.Request, _ router.Response) error { pvc := req.Object.(*corev1.PersistentVolumeClaim) if pvc.Spec.VolumeName == "" { return nil diff --git a/pkg/controller/quota/quota.go b/pkg/controller/quota/quota.go index 62d44612c..392476474 100644 --- a/pkg/controller/quota/quota.go +++ b/pkg/controller/quota/quota.go @@ -211,7 +211,7 @@ func addStorage(req router.Request, appInstance *v1.AppInstance, quotaRequest *a if boundSecret(name, appInstance.Spec.Secrets) { continue } - quotaRequest.Spec.Resources.Secrets += 1 + quotaRequest.Spec.Resources.Secrets++ } return nil } diff --git a/pkg/controller/resolvedofferings/computeclass.go b/pkg/controller/resolvedofferings/computeclass.go index b03cc7eb2..73ef02261 100644 --- a/pkg/controller/resolvedofferings/computeclass.go +++ b/pkg/controller/resolvedofferings/computeclass.go @@ -8,9 +8,9 @@ import ( "github.com/acorn-io/runtime/pkg/computeclasses" "github.com/acorn-io/z" - apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/utils/strings/slices" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) // resolveComputeClasses resolves the compute class information for each container in the AppInstance @@ -38,7 +38,7 @@ func resolveComputeClasses(req router.Request, cfg *apiv1.Config, appInstance *v Class: defaultCC, } cc, err := computeclasses.GetAsProjectComputeClassInstance(req.Ctx, req.Client, appInstance.Status.Namespace, defaultCC) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return err } diff --git a/pkg/controller/routes.go b/pkg/controller/routes.go index 7b74aaff6..75ada9251 100644 --- a/pkg/controller/routes.go +++ b/pkg/controller/routes.go @@ -30,7 +30,6 @@ import ( "github.com/acorn-io/runtime/pkg/controller/secrets" "github.com/acorn-io/runtime/pkg/controller/service" "github.com/acorn-io/runtime/pkg/controller/tls" - "github.com/acorn-io/runtime/pkg/event" "github.com/acorn-io/runtime/pkg/labels" "github.com/acorn-io/runtime/pkg/local/webhook" "github.com/acorn-io/runtime/pkg/project" @@ -53,7 +52,7 @@ var ( }) ) -func routes(router *router.Router, cfg *rest.Config, registryTransport http.RoundTripper, recorder event.Recorder) error { +func routes(router *router.Router, cfg *rest.Config, registryTransport http.RoundTripper) error { jobsHandler, err := jobs.NewHandler(cfg) if err != nil { return err @@ -66,9 +65,9 @@ func routes(router *router.Router, cfg *rest.Config, registryTransport http.Roun appRouter.HandlerFunc(appdefinition.AssignNamespace) // AppImage preparation, checks and promotion - appRouter.HandlerFunc(appdefinition.PullAppImage(registryTransport, recorder)) // pulls image to .status.Staged.AppImage - appRouter.HandlerFunc(permissions.CheckPermissions) // checks if newly staged image is allowed and that permissions are requested and granted properly - appRouter.HandlerFunc(permissions.CopyPromoteStagedAppImage) // if the above checks pass, the staged image is promoted to app.Status.AppImage and everything below will use that image + appRouter.HandlerFunc(appdefinition.PullAppImage(registryTransport)) // pulls image to .status.Staged.AppImage + appRouter.HandlerFunc(permissions.CheckPermissions) // checks if newly staged image is allowed and that permissions are requested and granted properly + appRouter.HandlerFunc(permissions.CopyPromoteStagedAppImage) // if the above checks pass, the staged image is promoted to app.Status.AppImage and everything below will use that image appRouter.HandlerFunc(appstatus.PrepareStatus) // --- @@ -116,26 +115,26 @@ func routes(router *router.Router, cfg *rest.Config, registryTransport http.Roun router.Type(&v1.AcornImageBuildInstance{}).HandlerFunc(defaults.SetDefaultRegion) router.Type(&v1.AcornImageBuildInstance{}).HandlerFunc(acornimagebuildinstance.MarkRecorded) - router.Type(&v1.ServiceInstance{}).HandlerFunc(gc.GCOrphans) + router.Type(&v1.ServiceInstance{}).HandlerFunc(gc.Orphans) router.Type(&v1.EventInstance{}).HandlerFunc(eventinstance.GCExpired()) router.Type(&batchv1.Job{}).Selector(managedSelector).HandlerFunc(jobs.JobCleanup) - router.Type(&rbacv1.ClusterRole{}).Selector(managedSelector).HandlerFunc(gc.GCOrphans) - router.Type(&rbacv1.ClusterRoleBinding{}).Selector(managedSelector).HandlerFunc(gc.GCOrphans) + router.Type(&rbacv1.ClusterRole{}).Selector(managedSelector).HandlerFunc(gc.Orphans) + router.Type(&rbacv1.ClusterRoleBinding{}).Selector(managedSelector).HandlerFunc(gc.Orphans) router.Type(&corev1.PersistentVolumeClaim{}).Selector(managedSelector).HandlerFunc(pvc.MarkAndSave) router.Type(&corev1.PersistentVolume{}).Selector(managedSelector).HandlerFunc(appdefinition.ReleaseVolume) router.Type(&corev1.Namespace{}).Selector(managedSelector).HandlerFunc(namespace.DeleteOrphaned) // This will only catch namespace deletes when the controller is running, but that's fine for now. router.Type(&corev1.Namespace{}).IncludeRemoved().HandlerFunc(namespace.DeleteProjectOnNamespaceDelete) - router.Type(&appsv1.DaemonSet{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.GCOrphans) - router.Type(&appsv1.Deployment{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.GCOrphans) - router.Type(&corev1.Service{}).Selector(managedSelector).HandlerFunc(gc.GCOrphans) - router.Type(&policyv1.PodDisruptionBudget{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.GCOrphans) - router.Type(&corev1.Pod{}).Selector(managedSelector).HandlerFunc(gc.GCOrphans) + router.Type(&appsv1.DaemonSet{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.Orphans) + router.Type(&appsv1.Deployment{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.Orphans) + router.Type(&corev1.Service{}).Selector(managedSelector).HandlerFunc(gc.Orphans) + router.Type(&policyv1.PodDisruptionBudget{}).Namespace(system.ImagesNamespace).HandlerFunc(gc.Orphans) + router.Type(&corev1.Pod{}).Selector(managedSelector).HandlerFunc(gc.Orphans) router.Type(&corev1.Pod{}).Selector(managedSelector).HandlerFunc(jobs.JobPodOrphanCleanup) router.Type(&corev1.Pod{}).Selector(managedSelector).HandlerFunc(jobsHandler.SaveJobOutput) - router.Type(&netv1.Ingress{}).Selector(managedSelector).Namespace(system.ImagesNamespace).HandlerFunc(gc.GCOrphans) + router.Type(&netv1.Ingress{}).Selector(managedSelector).Namespace(system.ImagesNamespace).HandlerFunc(gc.Orphans) router.Type(&corev1.Secret{}).Selector(managedSelector).Name(system.DNSSecretName).Namespace(system.Namespace).HandlerFunc(secrets.HandleDNSSecret) router.Type(&netv1.Ingress{}).Selector(managedSelector).Name(system.DNSIngressName).Namespace(system.Namespace).Middleware(ingress.RequireLBs).Handler(ingress.NewDNSHandler()) router.Type(&corev1.Secret{}).Selector(managedSelector).Name(system.TLSSecretName).Namespace(system.Namespace).Middleware(tls.RequireSecretTypeTLS).HandlerFunc(tls.RenewCert) // renew (expired) TLS certificate @@ -143,7 +142,7 @@ func routes(router *router.Router, cfg *rest.Config, registryTransport http.Roun router.Type(&corev1.Service{}).Selector(managedSelector).HandlerFunc(networkpolicy.ForService) router.Type(&netv1.Ingress{}).Selector(managedSelector).HandlerFunc(networkpolicy.ForIngress) router.Type(&appsv1.Deployment{}).Namespace(system.ImagesNamespace).HandlerFunc(networkpolicy.ForBuilder) - router.Type(&netv1.NetworkPolicy{}).Selector(managedSelector).HandlerFunc(gc.GCOrphans) + router.Type(&netv1.NetworkPolicy{}).Selector(managedSelector).HandlerFunc(gc.Orphans) router.Type(&internaladminv1.ImageRoleAuthorizationInstance{}).HandlerFunc(permissions.BumpImageRoleAuthorizations) router.Type(&internaladminv1.ClusterImageRoleAuthorizationInstance{}).HandlerFunc(permissions.BumpClusterImageRoleAuthorizations) diff --git a/pkg/controller/scheduling/scheduling.go b/pkg/controller/scheduling/scheduling.go index c3ede5914..216499e51 100644 --- a/pkg/controller/scheduling/scheduling.go +++ b/pkg/controller/scheduling/scheduling.go @@ -91,7 +91,7 @@ func addScheduling(req router.Request, appInstance *v1.AppInstance, workloads ma appInstance.Status.Scheduling[sidecarName] = v1.Scheduling{Requirements: *sidecarRequirements} } - affinity, tolerations = Nodes(req, computeClass) + affinity, tolerations = Nodes(computeClass) priorityClassName, err := priorityClassName(req, computeClass) if err != nil { @@ -124,7 +124,7 @@ func addScheduling(req router.Request, appInstance *v1.AppInstance, workloads ma } // Nodes returns the Affinity and Tolerations from a ComputeClass if they exist -func Nodes(req router.Request, computeClass *adminv1.ProjectComputeClassInstance) (*corev1.Affinity, []corev1.Toleration) { +func Nodes(computeClass *adminv1.ProjectComputeClassInstance) (*corev1.Affinity, []corev1.Toleration) { if computeClass == nil { return nil, nil } diff --git a/pkg/controller/tls/certs.go b/pkg/controller/tls/certs.go index 3b002f938..af7466e71 100644 --- a/pkg/controller/tls/certs.go +++ b/pkg/controller/tls/certs.go @@ -20,7 +20,7 @@ import ( ) // ProvisionWildcardCert provisions a Let's Encrypt wildcard certificate for *..oss-acorn.io -func ProvisionWildcardCert(req router.Request, resp router.Response, domain, token string) error { +func ProvisionWildcardCert(req router.Request, resp router.Response, domain string) error { logrus.Debugf("Provisioning wildcard cert for %v", domain) // Ensure that we have a Let's Encrypt account ready leUser, err := ensureLEUser(req.Ctx, req.Client) diff --git a/pkg/controller/tls/letsencrypt.go b/pkg/controller/tls/letsencrypt.go index b59332b1f..6c1336f7d 100644 --- a/pkg/controller/tls/letsencrypt.go +++ b/pkg/controller/tls/letsencrypt.go @@ -30,7 +30,6 @@ import ( "github.com/go-acme/lego/v4/registration" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kclient "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -170,9 +169,8 @@ func matchLeURLToEnv(url string) string { return "staging" } else if url == LetsEncryptURLProduction { return "enabled" - } else { - return "disabled" } + return "disabled" } // toHash returns a hash of the configurable fields of the LEUser @@ -233,7 +231,7 @@ func ensureLEUser(ctx context.Context, client kclient.Client) (*LEUser, error) { leAccountSecret := &corev1.Secret{} err = client.Get(ctx, router.Key(system.Namespace, system.LEAccountSecretName), leAccountSecret) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, err } @@ -342,18 +340,17 @@ func stillValid(cert []byte) bool { // (a) unreadable certificate -> renew logrus.Errorf("problem parsing certificate: %v", err) return false - } else { - timeToExpire := x509crt.NotAfter.Sub(time.Now().UTC()) - if timeToExpire > 7*24*time.Hour { - // (b) cert is still valid for more than 7 days -> good to go - logrus.Debugf("certificate for %s is still valid until %s (%d hours)", x509crt.Subject.CommonName, x509crt.NotAfter, int(timeToExpire.Hours())) - return true - } else { - // (c) cert is expired -> renew - logrus.Infof("certificate for %s is expiring after %s (%d hours) and should be renewed", x509crt.Subject.CommonName, x509crt.NotAfter, int(timeToExpire.Hours())) - return false - } } + + timeToExpire := x509crt.NotAfter.Sub(time.Now().UTC()) + if timeToExpire > 7*24*time.Hour { + // (b) cert is still valid for more than 7 days -> good to go + logrus.Debugf("certificate for %s is still valid until %s (%d hours)", x509crt.Subject.CommonName, x509crt.NotAfter, int(timeToExpire.Hours())) + return true + } + // (c) cert is expired -> renew + logrus.Infof("certificate for %s is expiring after %s (%d hours) and should be renewed", x509crt.Subject.CommonName, x509crt.NotAfter, int(timeToExpire.Hours())) + return false } // mustRenew returns true if the certificate must be renewed, either because the Let's Encrypt settings changed, the certificate is invalid or it's about to expire @@ -393,7 +390,7 @@ func (u *LEUser) dnsChallenge(ctx context.Context, domain string) (*certificate. dnsSecret := &corev1.Secret{} err = c.Get(ctx, router.Key(system.Namespace, system.DNSSecretName), dnsSecret) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, err } token := string(dnsSecret.Data["token"]) diff --git a/pkg/controller/tls/provider.go b/pkg/controller/tls/provider.go index b26753b10..04b19575a 100644 --- a/pkg/controller/tls/provider.go +++ b/pkg/controller/tls/provider.go @@ -30,12 +30,12 @@ func NewACMEDNS01ChallengeProvider(endpoint, domain, token string) *ACMEDNS01Cha } } -func (d *ACMEDNS01ChallengeProvider) Present(domain, token, keyAuth string) error { +func (d *ACMEDNS01ChallengeProvider) Present(domain, _, keyAuth string) error { fqdn, value := dns01.GetRecord(domain, keyAuth) return d.client.SetTXTRecord(fqdn, value) } -func (d *ACMEDNS01ChallengeProvider) CleanUp(domain, token, keyAuth string) error { +func (d *ACMEDNS01ChallengeProvider) CleanUp(domain, _, _ string) error { return d.client.DeleteDNSRecord(domain) } diff --git a/pkg/cosign/find.go b/pkg/cosign/find.go index ec502a43b..828ca4504 100644 --- a/pkg/cosign/find.go +++ b/pkg/cosign/find.go @@ -19,11 +19,11 @@ func FindSignatureImage(imageRef name.Reference, opts ...remote.Option) (name.Ta img, err := remote.Image(tag, opts...) return tag, img, err - } else { - digeststr, err := SimpleDigest(imageRef, opts...) - if err != nil { - return name.Tag{}, nil, err - } - return FindSignatureImage(imageRef.Context().Digest(digeststr), opts...) } + + digeststr, err := SimpleDigest(imageRef, opts...) + if err != nil { + return name.Tag{}, nil, err + } + return FindSignatureImage(imageRef.Context().Digest(digeststr), opts...) } diff --git a/pkg/credentials/store.go b/pkg/credentials/store.go index 7f868d30f..93ac5b629 100644 --- a/pkg/credentials/store.go +++ b/pkg/credentials/store.go @@ -36,7 +36,7 @@ func normalize(cred apiv1.Credential) apiv1.Credential { return cred } -func (s *Store) Get(ctx context.Context, serverAddress string) (*apiv1.RegistryAuth, bool, error) { +func (s *Store) Get(serverAddress string) (*apiv1.RegistryAuth, bool, error) { serverAddress = imagesystem.NormalizeServerAddress(serverAddress) store, err := s.getStore(serverAddress) if err != nil { diff --git a/pkg/dev/dev.go b/pkg/dev/dev.go index d7108a6cf..4856f52b9 100644 --- a/pkg/dev/dev.go +++ b/pkg/dev/dev.go @@ -332,7 +332,7 @@ func buildLoop(ctx context.Context, c client.Client, hash clientHash, opts *Opti opts.Run.Name = appName eg, ctx := errgroup.WithContext(ctx) eg.Go(func() error { - return DevPorts(ctx, c, logger, appName) + return Ports(ctx, c, logger, appName) }) eg.Go(func() error { return LogLoop(ctx, c, appName, &client.LogOptions{ diff --git a/pkg/dev/ports.go b/pkg/dev/ports.go index c673d2a54..929079ea8 100644 --- a/pkg/dev/ports.go +++ b/pkg/dev/ports.go @@ -16,7 +16,7 @@ import ( "k8s.io/client-go/util/retry" ) -func DevPorts(ctx context.Context, c client.Client, logger Logger, appName string) error { +func Ports(ctx context.Context, c client.Client, logger Logger, appName string) error { wc, err := c.GetClient() if err != nil { return err diff --git a/pkg/encryption/nacl/decrypt.go b/pkg/encryption/nacl/decrypt.go index d6281f498..9512240a8 100644 --- a/pkg/encryption/nacl/decrypt.go +++ b/pkg/encryption/nacl/decrypt.go @@ -49,9 +49,8 @@ func DecryptNamespacedData(ctx context.Context, c kclient.Reader, data []byte, n data, err := key.Decrypt(data) if err == nil { return data, nil - } else { - errs = append(errs, fmt.Errorf("pubkey %s: %w", KeyBytesToB64String(key.PublicKey), err)) } + errs = append(errs, fmt.Errorf("pubkey %s: %w", KeyBytesToB64String(key.PublicKey), err)) } return nil, &ErrUnableToDecrypt{ @@ -59,7 +58,7 @@ func DecryptNamespacedData(ctx context.Context, c kclient.Reader, data []byte, n } } -func (k *NaclKey) Decrypt(encData []byte) ([]byte, error) { +func (k *Key) Decrypt(encData []byte) ([]byte, error) { pubKeyString := KeyBytesToB64String(k.PublicKey) preppedData, err := unwrapForDecryption(encData) if err != nil { diff --git a/pkg/encryption/nacl/keys.go b/pkg/encryption/nacl/keys.go index a7c8e79a3..b76bed26b 100644 --- a/pkg/encryption/nacl/keys.go +++ b/pkg/encryption/nacl/keys.go @@ -2,7 +2,7 @@ package nacl import ( "context" - crypto_rand "crypto/rand" + "crypto/rand" "encoding/base64" "encoding/json" "fmt" @@ -22,8 +22,8 @@ const ( naclNSUID = "ns-uid" ) -type NaclKeys map[string]*NaclKey -type NaclKey struct { +type Keys map[string]*Key +type Key struct { AcornNamespace string Primary *bool PublicKey *[32]byte @@ -40,7 +40,7 @@ type naclStoredKey struct { PublicKey *[32]byte `json:"publicKey,omitempty"` } -func GetOrCreatePrimaryNaclKey(ctx context.Context, c kclient.Client, namespace string) (*NaclKey, error) { +func GetOrCreatePrimaryNaclKey(ctx context.Context, c kclient.Client, namespace string) (*Key, error) { existing, err := getExistingSecret(ctx, c, namespace) if apierrors.IsNotFound(err) { return generateNewKeys(ctx, c, namespace, nil) @@ -56,7 +56,7 @@ func GetOrCreatePrimaryNaclKey(ctx context.Context, c kclient.Client, namespace return keys["primary"], nil } -func GetPrimaryNaclKey(ctx context.Context, c kclient.Reader, publicKey, namespace string) (*NaclKey, error) { +func GetPrimaryNaclKey(ctx context.Context, c kclient.Reader, publicKey, namespace string) (*Key, error) { existing, err := getExistingSecret(ctx, c, namespace) if apierrors.IsNotFound(err) { return nil, &ErrKeyNotFound{} @@ -79,7 +79,7 @@ func GetPrimaryNaclKey(ctx context.Context, c kclient.Reader, publicKey, namespa return keys["primary"], nil } -func GetAllNaclKeys(ctx context.Context, c kclient.Reader, namespace string) (NaclKeys, error) { +func GetAllNaclKeys(ctx context.Context, c kclient.Reader, namespace string) (Keys, error) { existing, err := getExistingSecret(ctx, c, namespace) if apierrors.IsNotFound(err) { return nil, &ErrKeyNotFound{} @@ -99,11 +99,11 @@ func GetPublicKey(ctx context.Context, c kclient.Reader, namespace string) (stri return "", err } -func generateNewKeys(ctx context.Context, c kclient.Client, namespace string, existing *corev1.Secret) (*NaclKey, error) { - naclKey := &NaclKey{ +func generateNewKeys(ctx context.Context, c kclient.Client, namespace string, existing *corev1.Secret) (*Key, error) { + naclKey := &Key{ AcornNamespace: namespace, } - publicKey, privateKey, err := box.GenerateKey(crypto_rand.Reader) + publicKey, privateKey, err := box.GenerateKey(rand.Reader) if err != nil { return nil, err } @@ -139,7 +139,7 @@ func getExistingSecret(ctx context.Context, c kclient.Reader, namespace string) return existing, err } -func createOrUpdateNaclKeySecret(ctx context.Context, c kclient.Client, key *NaclKey, existing *corev1.Secret) error { +func createOrUpdateNaclKeySecret(ctx context.Context, c kclient.Client, key *Key, existing *corev1.Secret) error { if existing == nil { keyData, err := key.toSecretData(nil) if err != nil { @@ -173,11 +173,12 @@ func createOrUpdateNaclKeySecret(ctx context.Context, c kclient.Client, key *Nac func keyToBytes(key string) (*[32]byte, error) { returnBytes := &[32]byte{} - if bytes, err := base64.RawURLEncoding.DecodeString(key); err != nil { + bytes, err := base64.RawURLEncoding.DecodeString(key) + if err != nil { return nil, err - } else { - copy(returnBytes[:], bytes) } + + copy(returnBytes[:], bytes) return returnBytes, nil } @@ -186,8 +187,8 @@ func KeyBytesToB64String(key *[32]byte) string { return base64.RawURLEncoding.EncodeToString(bytes) } -func secretToNaclKeys(secret *corev1.Secret, namespace string) (NaclKeys, error) { - to := NaclKeys{} +func secretToNaclKeys(secret *corev1.Secret, namespace string) (Keys, error) { + to := Keys{} keystore, ok := secret.Data[naclStoreKey] if !ok { @@ -214,7 +215,7 @@ func secretToNaclKeys(secret *corev1.Secret, namespace string) (NaclKeys, error) if err != nil { return nil, err } - to[pubKeyString] = &NaclKey{ + to[pubKeyString] = &Key{ AcornNamespace: keyInfo.AcornNamespace, Primary: keyInfo.Primary, PublicKey: pubKey, @@ -229,7 +230,7 @@ func secretToNaclKeys(secret *corev1.Secret, namespace string) (NaclKeys, error) return to, nil } -func (k *NaclKey) toSecretData(existingData map[string][]byte) (map[string][]byte, error) { +func (k *Key) toSecretData(existingData map[string][]byte) (map[string][]byte, error) { to := map[string][]byte{ naclNSUID: []byte(k.acornNamespaceUID), } diff --git a/pkg/imagedetails/imagedetails.go b/pkg/imagedetails/imagedetails.go index c044ea20b..65eb3dc26 100644 --- a/pkg/imagedetails/imagedetails.go +++ b/pkg/imagedetails/imagedetails.go @@ -27,7 +27,7 @@ func GetImageIcon(ctx context.Context, c kclient.Client, namespace, imageName, d image := &apiv1.Image{} err := c.Get(ctx, router.Key(namespace, name), image) - if err != nil && !apierror.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, "", err } else if err != nil && apierror.IsNotFound(err) && (tags.IsLocalReference(name) || tags.HasNoSpecifiedRegistry(imageName)) { return nil, "", err @@ -70,8 +70,9 @@ func getImageDetails(ctx context.Context, c kclient.Client, namespace, imageName imageName = strings.ReplaceAll(imageName, "+", "/") name := strings.ReplaceAll(imageName, "/", "+") - if tagPattern, isPattern := autoupgrade.AutoUpgradePattern(imageName); isPattern { - if latestImage, found, err := autoupgrade.FindLatestTagForImageWithPattern(ctx, c, "", namespace, imageName, tagPattern, opts.RemoteOpts...); err != nil { + if tagPattern, isPattern := autoupgrade.Pattern(imageName); isPattern { + latestImage, found, err := autoupgrade.FindLatestTagForImageWithPattern(ctx, c, "", namespace, imageName, tagPattern, opts.RemoteOpts...) + if err != nil { return nil, err } else if !found { // Check and see if no registry was specified on the image. @@ -82,17 +83,17 @@ func getImageDetails(ctx context.Context, c kclient.Client, namespace, imageName } return nil, fmt.Errorf("unable to find an image for %v matching pattern %v", imageName, tagPattern) - } else { - imageName = latestImage - name = strings.ReplaceAll(imageName, "/", "+") } + + imageName = latestImage + name = strings.ReplaceAll(imageName, "/", "+") } image := &apiv1.Image{} err := c.Get(ctx, router.Key(namespace, name), image) - if err != nil && !apierror.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, err - } else if err != nil && apierror.IsNotFound(err) && (tags.IsLocalReference(name) || (opts.NoDefaultReg && tags.HasNoSpecifiedRegistry(imageName))) { + } else if err != nil && (tags.IsLocalReference(name) || (opts.NoDefaultReg && tags.HasNoSpecifiedRegistry(imageName))) { return nil, err } else if err == nil { namespace = image.Namespace diff --git a/pkg/imagepattern/pattern.go b/pkg/imagepattern/pattern.go index a0b479d98..c8d336f7a 100644 --- a/pkg/imagepattern/pattern.go +++ b/pkg/imagepattern/pattern.go @@ -10,17 +10,17 @@ func IsImagePattern(image string) bool { return strings.ContainsAny(image, "#*") } -// We need to know two things about a matching group: it's name and whether it should be sorted alphabetically or -// numerically. pType will be either "alpha" or "numeric" -type namedMatchingGroup struct { +// NamedMatchingGroup represents the information we need to know two things about a matching group: it's name and +// whether it should be sorted alphabetically or numerically. pType will be either "alpha" or "numeric" +type NamedMatchingGroup struct { PType string Name string } // NewMatcher returns a Regexp that can be used to match an image or image tag against a pattern. -// The supplied pattern is NOT a regex. It is acorn's own custom syntax with the following characteristics: +// The supplied pattern is NOT a regexp. It is acorn's own custom syntax with the following characteristics: // - Assumed to be valid docker tag characters: 0-9A-Za-z_.- -// - Outside of the special matching/sorting groups, a tag must match the pattern exactly +// - Outside the special matching/sorting groups, a tag must match the pattern exactly // - There are three special matching/sorting groups: #, *, and ** // - ** indicates a portion of the tag doesn't need to match the pattern and won't be considered for sorting. It is the "wildcard" // - * indicates a portion of the tag that will be matched and sorted alphabetically @@ -30,7 +30,7 @@ type namedMatchingGroup struct { // - "v#.#" - Matches: "v1.0", "v2.0" (return as latest). Doesn't match: "v1.alpha", "1.0", "v1.0.0" // - "v1.0-*" - Matches: "v1.0-alpha", "v1.0-beta" (returned as latest). Doesn't match: "v1.0" // - "v1.#-**" - Matches: "v1.0-cv23jkha", "v1.1-2020-01-01" (returned as latest). -func NewMatcher(pattern string) (*regexp.Regexp, []namedMatchingGroup, error) { +func NewMatcher(pattern string) (*regexp.Regexp, []NamedMatchingGroup, error) { pattern = "^" + pattern + "$" // ** denotes a part of the tag that should be completely ignored for both matching and sorting. Replace it with @@ -38,7 +38,7 @@ func NewMatcher(pattern string) (*regexp.Regexp, []namedMatchingGroup, error) { pattern = strings.ReplaceAll(pattern, "**", `([0-9A-Za-z_./:-]{0,})`) index := 0 - var namedMatchingGroups []namedMatchingGroup + var namedMatchingGroups []NamedMatchingGroup // We are replacing the special cases of "#" and "*" with regex "Named Capturing Groups". We are using this feature // so that later we can sort on each group to find the "latest" image. @@ -52,13 +52,13 @@ func NewMatcher(pattern string) (*regexp.Regexp, []namedMatchingGroup, error) { if strings.Contains(pattern, "*") && (!strings.Contains(pattern, "#") || (strings.Index(pattern, "*") < strings.Index(pattern, "#"))) { pattern = strings.Replace(pattern, "*", fmt.Sprintf(`(?P<%v>[0-9A-Za-z_.-]+)`, name), 1) - namedMatchingGroups = append(namedMatchingGroups, namedMatchingGroup{PType: "alpha", Name: name}) + namedMatchingGroups = append(namedMatchingGroups, NamedMatchingGroup{PType: "alpha", Name: name}) } else { pattern = strings.Replace(pattern, "#", fmt.Sprintf(`(?P<%v>\d+)`, name), 1) - namedMatchingGroups = append(namedMatchingGroups, namedMatchingGroup{PType: "numeric", Name: name}) + namedMatchingGroups = append(namedMatchingGroups, NamedMatchingGroup{PType: "numeric", Name: name}) } - index += 1 + index++ } re, err := regexp.Compile(pattern) diff --git a/pkg/imagerules/imageroleauthorizations.go b/pkg/imagerules/imageroleauthorizations.go index ccd4cebf0..c6a4c2136 100644 --- a/pkg/imagerules/imageroleauthorizations.go +++ b/pkg/imagerules/imageroleauthorizations.go @@ -44,11 +44,11 @@ func GetAuthorizedPermissions(ctx context.Context, c client.Reader, namespace, i authorizedRoles, err := CheckRoleAuthorizations(ctx, c, namespace, imageName, digest, iras.Items, remoteOpts...) if err != nil { - if _, ok := err.(*ErrImageNotAllowed); ok { + var errImageNotAllowed *ErrImageNotAllowed + if errors.As(err, &errImageNotAllowed) { return nil, nil - } else { - return nil, err } + return nil, err } return resolveAuthorizedRoles(ctx, c, namespace, imageName, authorizedRoles) diff --git a/pkg/imagerules/util/helpers.go b/pkg/imagerules/util/helpers.go index 760590cc9..e246c0f2e 100644 --- a/pkg/imagerules/util/helpers.go +++ b/pkg/imagerules/util/helpers.go @@ -21,7 +21,7 @@ const ( ) func GenerateSimpleAllowRule(namespace string, name string, image string, scope string) (*v1.ImageAllowRule, error) { - pattern, isPattern := autoupgrade.AutoUpgradePattern(image) + pattern, isPattern := autoupgrade.Pattern(image) if isPattern { image = strings.TrimRight(image, ":"+pattern) diff --git a/pkg/imageselector/signatures/signatures.go b/pkg/imageselector/signatures/signatures.go index d6023000e..d2c00d55e 100644 --- a/pkg/imageselector/signatures/signatures.go +++ b/pkg/imageselector/signatures/signatures.go @@ -2,6 +2,7 @@ package signatures import ( "context" + "errors" "fmt" "github.com/acorn-io/baaah/pkg/merr" @@ -64,11 +65,12 @@ func VerifySignatureRule(ctx context.Context, c client.Reader, namespace string, if err == nil { anyOfOK = true break - } else { - if _, ok := err.(*cosign.VerificationError); !ok { - e := fmt.Errorf(".signatures.anyOf.%d: %w", anyOfRuleIndex, err) - anyOfErrs = append(anyOfErrs, e) - } + } + + var verificationError *cosign.VerificationError + if !errors.As(err, &verificationError) { + e := fmt.Errorf(".signatures.anyOf.%d: %w", anyOfRuleIndex, err) + anyOfErrs = append(anyOfErrs, e) } } if !anyOfOK { diff --git a/pkg/imagesource/helper.go b/pkg/imagesource/helper.go index b91e5f992..1b2acb8c4 100644 --- a/pkg/imagesource/helper.go +++ b/pkg/imagesource/helper.go @@ -40,7 +40,7 @@ func NewImageSource(acornConfig string, file, argsFile string, args, platforms [ result.Platforms = platforms // If the image is a pattern, auto-upgrade is on, so assume no default registry - _, isPattern := autoupgrade.AutoUpgradePattern(result.Image) + _, isPattern := autoupgrade.Pattern(result.Image) result.NoDefaultRegistry = noDefaultReg || isPattern return } diff --git a/pkg/imagesystem/buildertemplate.go b/pkg/imagesystem/buildertemplate.go index 303789c95..1b33afd83 100644 --- a/pkg/imagesystem/buildertemplate.go +++ b/pkg/imagesystem/buildertemplate.go @@ -18,7 +18,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -func BuilderObjects(name, namespace, forNamespace, buildKitImage, pub, privKey, depotToken, depotProjectId, builderUID, forwardAddress string, cfg *apiv1.Config) []client.Object { +func BuilderObjects(name, namespace, forNamespace, buildKitImage, pub, privKey, depotToken, depotProjectID, builderUID, forwardAddress string, cfg *apiv1.Config) []client.Object { secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -28,7 +28,7 @@ func BuilderObjects(name, namespace, forNamespace, buildKitImage, pub, privKey, "pub": []byte(pub), "priv": []byte(privKey), "depotToken": []byte(depotToken), - "depotProjectId": []byte(depotProjectId), + "depotProjectId": []byte(depotProjectID), }, } @@ -225,7 +225,7 @@ func BuilderObjects(name, namespace, forNamespace, buildKitImage, pub, privKey, }, } - if depotToken != "" && depotProjectId != "" { + if depotToken != "" && depotProjectID != "" { // Drop buildkit deployment.Spec.Template.Spec.Containers = []corev1.Container{ deployment.Spec.Template.Spec.Containers[1], diff --git a/pkg/imagesystem/registry.go b/pkg/imagesystem/registry.go index 25b63e326..0bc145f46 100644 --- a/pkg/imagesystem/registry.go +++ b/pkg/imagesystem/registry.go @@ -17,7 +17,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" + kclient "sigs.k8s.io/controller-runtime/pkg/client" ) func NormalizeServerAddress(address string) string { @@ -27,7 +27,7 @@ func NormalizeServerAddress(address string) string { return address } -func GetInternalRepoForNamespace(ctx context.Context, c client.Reader, namespace string) (name.Repository, bool, error) { +func GetInternalRepoForNamespace(ctx context.Context, c kclient.Reader, namespace string) (name.Repository, bool, error) { cfg, err := config.Get(ctx, c) if err != nil { return name.Repository{}, false, err @@ -46,7 +46,7 @@ func GetInternalRepoForNamespace(ctx context.Context, c client.Reader, namespace return n, false, err } -func GetRuntimePullableInternalRepoForNamespace(ctx context.Context, c client.Reader, namespace string) (name.Repository, error) { +func GetRuntimePullableInternalRepoForNamespace(ctx context.Context, c kclient.Reader, namespace string) (name.Repository, error) { cfg, err := config.Get(ctx, c) if err != nil { return name.Repository{}, err @@ -63,7 +63,7 @@ func GetRuntimePullableInternalRepoForNamespace(ctx context.Context, c client.Re return name.NewRepository(fmt.Sprintf("%s/acorn/%s", address, namespace)) } -func GetRuntimePullableInternalRepoForNamespaceAndID(ctx context.Context, c client.Reader, namespace, imageID string) (name.Reference, error) { +func GetRuntimePullableInternalRepoForNamespaceAndID(ctx context.Context, c kclient.Reader, namespace, imageID string) (name.Reference, error) { var ( repo name.Repository ) @@ -73,7 +73,7 @@ func GetRuntimePullableInternalRepoForNamespaceAndID(ctx context.Context, c clie if err != nil { return nil, err } - } else if err != nil && !apierrors.IsNotFound(err) { + } else if kclient.IgnoreNotFound(err) != nil { return nil, err } else { repo, err = GetRuntimePullableInternalRepoForNamespace(ctx, c, namespace) @@ -84,7 +84,7 @@ func GetRuntimePullableInternalRepoForNamespaceAndID(ctx context.Context, c clie return repo.Digest("sha256:" + imageID), nil } -func GetInternalRepoForNamespaceAndID(ctx context.Context, c client.Reader, namespace, imageID string) (name.Reference, error) { +func GetInternalRepoForNamespaceAndID(ctx context.Context, c kclient.Reader, namespace, imageID string) (name.Reference, error) { var ( repo name.Repository ) @@ -94,7 +94,7 @@ func GetInternalRepoForNamespaceAndID(ctx context.Context, c client.Reader, name if err != nil { return nil, err } - } else if err != nil && !apierrors.IsNotFound(err) { + } else if kclient.IgnoreNotFound(err) != nil { return nil, err } else { repo, _, err = GetInternalRepoForNamespace(ctx, c, namespace) @@ -105,7 +105,7 @@ func GetInternalRepoForNamespaceAndID(ctx context.Context, c client.Reader, name return repo.Digest("sha256:" + imageID), nil } -func GetRegistryObjects(ctx context.Context, c client.Reader) (result []client.Object, _ error) { +func GetRegistryObjects(ctx context.Context, c kclient.Reader) (result []kclient.Object, _ error) { cfg, err := config.Get(ctx, c) if err != nil { return nil, err @@ -159,7 +159,7 @@ func GetRegistryObjects(ctx context.Context, c client.Reader) (result []client.O ) } - sa := registryServiceAccount(system.ImagesNamespace) + sa := registryServiceAccount() result = append(result, sa) result = append(result, @@ -175,7 +175,7 @@ func GetRegistryObjects(ctx context.Context, c client.Reader) (result []client.O return result, nil } -func GetClusterInternalRegistryDNSName(ctx context.Context, c client.Reader) (string, error) { +func GetClusterInternalRegistryDNSName(ctx context.Context, c kclient.Reader) (string, error) { cfg, err := config.Get(ctx, c) if err != nil { return "", err @@ -187,7 +187,7 @@ func IsClusterInternalRegistryAddressReference(url string) bool { return strings.HasPrefix(url, "127.") } -func GetClusterInternalRegistryAddress(ctx context.Context, c client.Reader) (string, error) { +func GetClusterInternalRegistryAddress(ctx context.Context, c kclient.Reader) (string, error) { port, err := getRegistryPort(ctx, c) if err != nil { return "", err @@ -195,9 +195,9 @@ func GetClusterInternalRegistryAddress(ctx context.Context, c client.Reader) (st return fmt.Sprintf("127.0.0.1:%d", port), nil } -func getRegistryPort(ctx context.Context, c client.Reader) (int, error) { +func getRegistryPort(ctx context.Context, c kclient.Reader) (int, error) { var service corev1.Service - err := c.Get(ctx, client.ObjectKey{Name: system.RegistryName, Namespace: system.ImagesNamespace}, &service) + err := c.Get(ctx, kclient.ObjectKey{Name: system.RegistryName, Namespace: system.ImagesNamespace}, &service) if err != nil { return 0, fmt.Errorf("getting %s/%s service: %w", system.ImagesNamespace, system.RegistryName, err) } @@ -210,7 +210,7 @@ func getRegistryPort(ctx context.Context, c client.Reader) (int, error) { return 0, fmt.Errorf("failed to find node port for registry %s/%s", system.ImagesNamespace, system.RegistryName) } -func IsNotInternalRepo(ctx context.Context, c client.Reader, namespace, image string) error { +func IsNotInternalRepo(ctx context.Context, c kclient.Reader, namespace, image string) error { if !strings.Contains(image, "/") { return nil } @@ -259,7 +259,7 @@ func isNotInternalRepo(prefix, image string) error { return nil } -func ParseAndEnsureNotInternalRepo(ctx context.Context, c client.Reader, namespace, image string) (name.Reference, error) { +func ParseAndEnsureNotInternalRepo(ctx context.Context, c kclient.Reader, namespace, image string) (name.Reference, error) { if err := IsNotInternalRepo(ctx, c, namespace, image); err != nil { return nil, err } diff --git a/pkg/imagesystem/registrytemplate.go b/pkg/imagesystem/registrytemplate.go index 39c54f61e..c8c720405 100644 --- a/pkg/imagesystem/registrytemplate.go +++ b/pkg/imagesystem/registrytemplate.go @@ -39,7 +39,7 @@ func registryService(namespace string) []client.Object { } } -func registryServiceAccount(namespace string) client.Object { +func registryServiceAccount() client.Object { return &corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: system.RegistryServiceAccountName, diff --git a/pkg/install/install.go b/pkg/install/install.go index b67984126..00b6e409d 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -184,7 +184,7 @@ func Install(ctx context.Context, image string, opts *Options) error { } // Validate the http-endpoint-pattern - if err := publish.ValidateEndpointPattern(*finalConfForValidation.HttpEndpointPattern); err != nil { + if err := publish.ValidateEndpointPattern(*finalConfForValidation.HTTPEndpointPattern); err != nil { return err } diff --git a/pkg/jobs/jobs.go b/pkg/jobs/jobs.go index 4c2d2f02d..578b44716 100644 --- a/pkg/jobs/jobs.go +++ b/pkg/jobs/jobs.go @@ -27,7 +27,7 @@ const ( Helper = "acorn-job-output-helper" ) -func GetJobOutputSecretName(ctx context.Context, namespace, jobName string) string { +func GetJobOutputSecretName(namespace, jobName string) string { return name.SafeHashConcatName(jobName, "output", namespace) } @@ -96,7 +96,7 @@ func getOutput(ctx context.Context, c kclient.Client, appInstance *v1.AppInstanc } }() - secretName := GetJobOutputSecretName(ctx, appInstance.Status.Namespace, name) + secretName := GetJobOutputSecretName(appInstance.Status.Namespace, name) secret := &corev1.Secret{} if err := c.Get(ctx, router.Key(appInstance.Status.Namespace, secretName), secret); apierror.IsNotFound(err) { diff --git a/pkg/local/docker.go b/pkg/local/docker.go index ddb76db93..1280676ac 100644 --- a/pkg/local/docker.go +++ b/pkg/local/docker.go @@ -163,14 +163,12 @@ func (c *Container) Delete(ctx context.Context, data bool) error { RemoveVolumes: data, Force: true, }) - if client.IsErrNotFound(err) { - } else if err != nil { + if err != nil && !client.IsErrNotFound(err) { return err } if data { - if err := c.c.VolumeRemove(ctx, volumeName, false); client.IsErrNotFound(err) { - } else if err != nil { + if err := c.c.VolumeRemove(ctx, volumeName, false); err != nil && !client.IsErrNotFound(err) { return err } } @@ -239,12 +237,11 @@ func (c *Container) Wait(ctx context.Context) error { for { _, err := c.c.ContainerInspect(ctx, ContainerName) - if client.IsErrNotFound(err) { - } else if err != nil { - return conStatus.Fail(err) - } else { + if err == nil { conStatus.Success() break + } else if err != nil && !client.IsErrNotFound(err) { + return conStatus.Fail(err) } select { @@ -438,8 +435,7 @@ func (c *Container) Stop(ctx context.Context) error { err := c.c.ContainerStop(ctx, ContainerName, container.StopOptions{ Timeout: z.Pointer(5), }) - if client.IsErrNotFound(err) { - } else if err != nil { + if err != nil && !client.IsErrNotFound(err) { return err } return c.DeletePorts(ctx) diff --git a/pkg/local/server_generic.go b/pkg/local/server_generic.go index df0fd3983..1027cdb6f 100644 --- a/pkg/local/server_generic.go +++ b/pkg/local/server_generic.go @@ -4,10 +4,9 @@ package local import ( "context" - _ "embed" "fmt" ) -func ServerRun(ctx context.Context) error { +func ServerRun(context.Context) error { return fmt.Errorf("only supported on linux") } diff --git a/pkg/local/server_linux.go b/pkg/local/server_linux.go index 3762d1f89..d958a755f 100644 --- a/pkg/local/server_linux.go +++ b/pkg/local/server_linux.go @@ -4,7 +4,6 @@ import ( "archive/tar" "bytes" "context" - _ "embed" "encoding/json" "fmt" "io" @@ -39,10 +38,10 @@ func ServerRun(ctx context.Context) error { if f, err := os.Open("/dev/kmsg"); err != nil { return fmt.Errorf("must be ran in a privileged docker container: %w", err) - } else { - _ = f.Close() } + _ = f.Close() + if err := os.WriteFile("/etc/machine-id", []byte(system.LocalImage), 0644); err != nil { return err } @@ -52,12 +51,12 @@ func ServerRun(ctx context.Context) error { return err } - if err := c.DeletePorts(ctx); err != nil { + if err = c.DeletePorts(ctx); err != nil { return err } buf := &bytes.Buffer{} - err = install.PrintObjects("acorn-local", &install.Options{ + if err = install.PrintObjects("acorn-local", &install.Options{ Output: buf, IncludeLocalEnvResources: true, Config: apiv1.Config{ @@ -65,8 +64,7 @@ func ServerRun(ctx context.Context) error { SetPodSecurityEnforceProfile: z.Pointer(false), IgnoreResourceRequirements: z.Pointer(true), }, - }) - if err != nil { + }); err != nil { return err } @@ -106,15 +104,15 @@ func ServerRun(ctx context.Context) error { return err } - if err := os.MkdirAll("/var/lib/rancher/k3s/server/manifests", 0755); err != nil { + if err = os.MkdirAll("/var/lib/rancher/k3s/server/manifests", 0755); err != nil { return err } - if err := os.WriteFile("/var/lib/rancher/k3s/server/manifests/acorn.yaml", data, 0655); err != nil { + if err = os.WriteFile("/var/lib/rancher/k3s/server/manifests/acorn.yaml", data, 0655); err != nil { return err } - if _, err := os.Stat("/sys/fs/cgroup/cgroup.controllers"); err == nil { + if _, err = os.Stat("/sys/fs/cgroup/cgroup.controllers"); err == nil { cmd := exec.Command("/bin/sh", "-c", ` mkdir -p /sys/fs/cgroup/init busybox xargs -rn1 < /sys/fs/cgroup/cgroup.procs > /sys/fs/cgroup/init/cgroup.procs || : @@ -122,7 +120,7 @@ sed -e 's/ / +/g' -e 's/^/+/' <"/sys/fs/cgroup/cgroup.controllers" >"/sys/fs/cgr `) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout - if err := cmd.Run(); err != nil { + if err = cmd.Run(); err != nil { return fmt.Errorf("failed to setup cgroups: %w", err) } } @@ -137,7 +135,7 @@ sed -e 's/ / +/g' -e 's/^/+/' <"/sys/fs/cgroup/cgroup.controllers" >"/sys/fs/cgr return err } - if err := os.MkdirAll("/var/lib/rancher/k3s/agent/images", 0755); err != nil { + if err = os.MkdirAll("/var/lib/rancher/k3s/agent/images", 0755); err != nil { return err } diff --git a/pkg/log/default_log.go b/pkg/log/default_log.go index 658053676..2352c15f0 100644 --- a/pkg/log/default_log.go +++ b/pkg/log/default_log.go @@ -58,7 +58,7 @@ func (d *DefaultLoggerImpl) AppStatus(ready bool, msg string, app *apiv1.App) { } } -func (d *DefaultLoggerImpl) Container(timeStamp metav1.Time, containerName, line string) { +func (d *DefaultLoggerImpl) Container(_ metav1.Time, containerName, line string) { d.lock.Lock() defer d.lock.Unlock() color, ok := d.containerColors[containerName] diff --git a/pkg/log/log.go b/pkg/log/log.go index c84077194..4644ad513 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -419,12 +419,10 @@ func matchesContainer(pod *corev1.Pod, container corev1.Container, options *Opti return pod.Name == podName && container.Name == pod.Labels[applabels.AcornContainerName] } else if pod.Labels[applabels.AcornFunctionName] != "" { return pod.Name == podName && container.Name == pod.Labels[applabels.AcornFunctionName] - } else { - return pod.Name == podName && container.Name == pod.Labels[applabels.AcornJobName] } - } else { - return pod.Name == podName && container.Name == containerName + return pod.Name == podName && container.Name == pod.Labels[applabels.AcornJobName] } + return pod.Name == podName && container.Name == containerName } // user has selected a specific acorn container name (the name seen in the acornfile containers section) diff --git a/pkg/manager/manager.go b/pkg/manager/manager.go index 8cd999016..b9dacf32b 100644 --- a/pkg/manager/manager.go +++ b/pkg/manager/manager.go @@ -111,9 +111,8 @@ func Login(ctx context.Context, cfg *config.CLIConfig, password, address string) user = tokenRequest.Spec.AccountName pass = tokenRequest.Status.Token break - } else { - logrus.Debugf("tokenRequest.Status.Token is empty") } + logrus.Debugf("tokenRequest.Status.Token is empty") } else if passwordIsSpecified && errors.Is(err, ErrTokenNotFound) { return "", "", fmt.Errorf("specified token does not exist; please create a token via the web UI or omit the --password flag to request one via your browser") } else { @@ -142,11 +141,11 @@ func Login(ctx context.Context, cfg *config.CLIConfig, password, address string) } // reload config, could have changed - if newCfg, err := config.ReadCLIConfig(cfg.AcornConfigFile, false); err != nil { + newCfg, err := config.ReadCLIConfig(cfg.AcornConfigFile, false) + if err != nil { return user, pass, err - } else { - *cfg = *newCfg } + *cfg = *newCfg return user, pass, nil } diff --git a/pkg/mocks/mock_client.go b/pkg/mocks/mock_client.go index 5056dde9b..063a74210 100644 --- a/pkg/mocks/mock_client.go +++ b/pkg/mocks/mock_client.go @@ -735,18 +735,18 @@ func (mr *MockClientMockRecorder) JobRestart(arg0, arg1 interface{}) *gomock.Cal } // KubeConfig mocks base method. -func (m *MockClient) KubeConfig(arg0 context.Context, arg1 *client.KubeProxyAddressOptions) ([]byte, error) { +func (m *MockClient) KubeConfig(arg0 *client.KubeProxyAddressOptions) ([]byte, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "KubeConfig", arg0, arg1) + ret := m.ctrl.Call(m, "KubeConfig", arg0) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 } // KubeConfig indicates an expected call of KubeConfig. -func (mr *MockClientMockRecorder) KubeConfig(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockClientMockRecorder) KubeConfig(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KubeConfig", reflect.TypeOf((*MockClient)(nil).KubeConfig), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KubeConfig", reflect.TypeOf((*MockClient)(nil).KubeConfig), arg0) } // KubeProxyAddress mocks base method. diff --git a/pkg/namespace/namespace.go b/pkg/namespace/namespace.go index bba9d94b1..86673d55d 100644 --- a/pkg/namespace/namespace.go +++ b/pkg/namespace/namespace.go @@ -17,7 +17,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -func DenormalizeName(ctx context.Context, c client.Client, namespace, name string) (string, string, error) { +func DenormalizeName(ctx context.Context, c client.Client, _, name string) (string, string, error) { ns, _ := request.NamespaceFrom(ctx) for { prefix, suffix, ok := strings.Cut(name, ".") diff --git a/pkg/profiles/default.go b/pkg/profiles/default.go index dd4d83296..6fb4b5e3b 100644 --- a/pkg/profiles/default.go +++ b/pkg/profiles/default.go @@ -19,8 +19,8 @@ var ( // AutoUpgradeIntervalDefault is the default value for the DefaultImageCheckInterval field AutoUpgradeIntervalDefault = "1m" - // HttpEndpointPatternDefault is a pattern that works with Let's Encrypt - HttpEndpointPatternDefault = "{{hashConcat 8 .Container .App .Namespace | truncate}}.{{.ClusterDomain}}" + // HTTPEndpointPatternDefault is a pattern that works with Let's Encrypt + HTTPEndpointPatternDefault = "{{hashConcat 8 .Container .App .Namespace | truncate}}.{{.ClusterDomain}}" // Features FeatureImageAllowRules = "image-allow-rules" @@ -43,7 +43,7 @@ func defaultProfile() apiv1.Config { CertManagerIssuer: new(string), EventTTL: new(string), Features: FeatureDefaults, - HttpEndpointPattern: z.Pointer(HttpEndpointPatternDefault), + HTTPEndpointPattern: z.Pointer(HTTPEndpointPatternDefault), IgnoreUserLabelsAndAnnotations: new(bool), IngressClassName: new(string), IngressControllerNamespace: new(string), diff --git a/pkg/project/client.go b/pkg/project/client.go index 1147fe80e..7297693e3 100644 --- a/pkg/project/client.go +++ b/pkg/project/client.go @@ -100,7 +100,7 @@ func (p *projectClientFactory) ForProject(ctx context.Context, project string) ( return getClient(ctx, p.cfg, p.opts, project) } -func (p *projectClientFactory) List(ctx context.Context) ([]client.Client, error) { +func (p *projectClientFactory) List(context.Context) ([]client.Client, error) { return p.clients, nil } @@ -240,7 +240,7 @@ func getClient(ctx context.Context, cfg *config.CLIConfig, opts Options, project return nil, err } - cred, ok, err := credStore.Get(ctx, server) + cred, ok, err := credStore.Get(server) if err != nil { return nil, err } else if !ok { diff --git a/pkg/project/operations.go b/pkg/project/operations.go index 6f37add50..30a24b26c 100644 --- a/pkg/project/operations.go +++ b/pkg/project/operations.go @@ -141,7 +141,7 @@ func listAcornServer(ctx context.Context, wg *sync.WaitGroup, creds *credentials defer wg.Done() var projects []string - cred, ok, err := creds.Get(ctx, managerServer) + cred, ok, err := creds.Get(managerServer) if err == nil && ok { subCtx, cancel := context.WithTimeout(ctx, 2*time.Second) projects, err = manager.Projects(subCtx, managerServer, cred.Password) diff --git a/pkg/proxy/proxy.go b/pkg/proxy/proxy.go index ced41f7d2..90d0c3622 100644 --- a/pkg/proxy/proxy.go +++ b/pkg/proxy/proxy.go @@ -17,12 +17,12 @@ var ( type errorResponder struct { } -func (e *errorResponder) Error(w http.ResponseWriter, req *http.Request, err error) { +func (e *errorResponder) Error(w http.ResponseWriter, _ *http.Request, err error) { w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(err.Error())) } -// Mostly copied from "kubectl proxy" code +// Handler is mostly copied from "kubectl proxy" code func Handler(cfg *rest.Config) (http.Handler, error) { host := cfg.Host if !strings.HasSuffix(host, "/") { diff --git a/pkg/publicname/strategy.go b/pkg/publicname/strategy.go index ab57d23a6..1fa247556 100644 --- a/pkg/publicname/strategy.go +++ b/pkg/publicname/strategy.go @@ -20,7 +20,7 @@ type Translator struct { strategy strategy.CompleteStrategy } -func (p *Translator) ListOpts(ctx context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { +func (p *Translator) ListOpts(_ context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { return namespace, opts, nil } @@ -38,7 +38,7 @@ func NewStrategy(strategy strategy.CompleteStrategy) strategy.CompleteStrategy { }, strategy) } -func (p *Translator) ToPublic(ctx context.Context, objs ...runtime.Object) (result []types.Object, _ error) { +func (p *Translator) ToPublic(_ context.Context, objs ...runtime.Object) (result []types.Object, _ error) { for _, obj := range objs { newObj := obj.DeepCopyObject().(types.Object) newObj.SetName(Get(newObj)) diff --git a/pkg/publish/ingress.go b/pkg/publish/ingress.go index b73f754e3..b2d013215 100644 --- a/pkg/publish/ingress.go +++ b/pkg/publish/ingress.go @@ -76,7 +76,7 @@ func toHTTPEndpointHostname(pattern, domain, container, appName, appNamespace st // This should not happen since the pattern in the config (passed to this through pattern) should // always be set to the default if the pattern is "". However, if it is not somehow, set it here. if pattern == "" { - pattern = profiles.HttpEndpointPatternDefault + pattern = profiles.HTTPEndpointPatternDefault } endpointOpts := struct { @@ -191,7 +191,7 @@ func Ingress(req router.Request, svc *v1.ServiceInstance) (result []kclient.Obje dnsSecret := &corev1.Secret{} err = req.Client.Get(req.Ctx, router.Key(system.Namespace, system.DNSSecretName), dnsSecret) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, err } acornDNSDomain := string(dnsSecret.Data["domain"]) @@ -219,7 +219,7 @@ func Ingress(req router.Request, svc *v1.ServiceInstance) (result []kclient.Obje } for _, domain := range cfg.ClusterDomains { - hostname, err := toHTTPEndpointHostname(*cfg.HttpEndpointPattern, domain, targetName, svc.Spec.AppName, svc.Spec.AppNamespace, appInstance) + hostname, err := toHTTPEndpointHostname(*cfg.HTTPEndpointPattern, domain, targetName, svc.Spec.AppName, svc.Spec.AppNamespace, appInstance) if err != nil { return nil, err } diff --git a/pkg/publish/ingress_test.go b/pkg/publish/ingress_test.go index 677e5f9fc..826503825 100644 --- a/pkg/publish/ingress_test.go +++ b/pkg/publish/ingress_test.go @@ -197,7 +197,7 @@ func TestToEndpoint(t *testing.T) { args: args{ domain: "custom-domain.io", serviceName: "app-name-that-is-very-long-and-should-cause-issues", - pattern: profiles.HttpEndpointPatternDefault, + pattern: profiles.HTTPEndpointPatternDefault, appInstance: &v1.AppInstance{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{Name: "green-star", Namespace: "namespace"}, diff --git a/pkg/ref/expr.go b/pkg/ref/expr.go index 87c61ecbb..56bbce68e 100644 --- a/pkg/ref/expr.go +++ b/pkg/ref/expr.go @@ -80,9 +80,7 @@ func Lookup(ctx context.Context, req kclient.Client, out kclient.Object, namespa validSecrets = nil namespace = app.Status.Namespace } - } else if len(parts)-i == 2 && (parts[i] == "secrets" || parts[i] == "secret") { - // support "svc.secrets.name" syntax - } else { + } else if len(parts)-i != 2 || parts[i] != "secrets" && parts[i] != "secret" { // if validSecrets is set then we already found a service and we are evaluating the second // to last part which is invalid as it must be a secret name and the last part at this point return apierrors.NewNotFound(schema.GroupResource{ diff --git a/pkg/secrets/secret.go b/pkg/secrets/secret.go index 1871d7049..cb5105553 100644 --- a/pkg/secrets/secret.go +++ b/pkg/secrets/secret.go @@ -367,7 +367,7 @@ func getSecret(req router.Request, appInstance *v1.AppInstance, name string) (*c func generateSecret(secrets map[string]*corev1.Secret, req router.Request, appInstance *v1.AppInstance, secretName string) (*corev1.Secret, error) { existing, err := getSecret(req, appInstance, secretName) - if err != nil && !apierrors.IsNotFound(err) { + if kclient.IgnoreNotFound(err) != nil { return nil, err } secretRef, ok := appInstance.Status.AppSpec.Secrets[secretName] diff --git a/pkg/server/registry/apigroups/acorn/apps/icon.go b/pkg/server/registry/apigroups/acorn/apps/icon.go index 03bab7458..cb8ca05ea 100644 --- a/pkg/server/registry/apigroups/acorn/apps/icon.go +++ b/pkg/server/registry/apigroups/acorn/apps/icon.go @@ -44,7 +44,7 @@ func (i *Icon) NewConnectOptions() (runtime.Object, bool, string) { return &apiv1.IconOptions{}, false, "" } -func (i *Icon) Connect(ctx context.Context, id string, options runtime.Object, r rest.Responder) (http.Handler, error) { +func (i *Icon) Connect(ctx context.Context, id string, _ runtime.Object, _ rest.Responder) (http.Handler, error) { ns, _ := request.NamespaceFrom(ctx) app := &apiv1.App{} err := i.client.Get(ctx, kclient.ObjectKey{Namespace: ns, Name: id}, app) diff --git a/pkg/server/registry/apigroups/acorn/apps/logs.go b/pkg/server/registry/apigroups/acorn/apps/logs.go index 4355699d8..19193de40 100644 --- a/pkg/server/registry/apigroups/acorn/apps/logs.go +++ b/pkg/server/registry/apigroups/acorn/apps/logs.go @@ -51,7 +51,7 @@ func (i *Logs) NewConnectOptions() (runtime.Object, bool, string) { return &apiv1.LogOptions{}, false, "" } -func (i *Logs) Connect(ctx context.Context, id string, options runtime.Object, r rest.Responder) (http.Handler, error) { +func (i *Logs) Connect(ctx context.Context, id string, options runtime.Object, _ rest.Responder) (http.Handler, error) { ns, _ := request.NamespaceFrom(ctx) app := &apiv1.App{} err := i.client.Get(ctx, kclient.ObjectKey{Namespace: ns, Name: id}, app) diff --git a/pkg/server/registry/apigroups/acorn/apps/pull.go b/pkg/server/registry/apigroups/acorn/apps/pull.go index f51c93905..7f737c922 100644 --- a/pkg/server/registry/apigroups/acorn/apps/pull.go +++ b/pkg/server/registry/apigroups/acorn/apps/pull.go @@ -43,7 +43,7 @@ func (s *PullAppImageStrategy) Create(ctx context.Context, obj types.Object) (ty if err != nil { return nil, err } - if _, pattern := autoupgrade.AutoUpgradePattern(app.Spec.Image); pattern { + if _, pattern := autoupgrade.Pattern(app.Spec.Image); pattern { if app.Status.AppImage.Name != "" { app.Status.AvailableAppImage = app.Status.AppImage.Name } @@ -59,7 +59,7 @@ func (s *PullAppImageStrategy) New() types.Object { return &apiv1.AppPullImage{} } -func (v PullAppImageNameValidator) ValidateName(ctx context.Context, obj runtime.Object) (result field.ErrorList) { +func (v PullAppImageNameValidator) ValidateName(_ context.Context, obj runtime.Object) (result field.ErrorList) { appPullImage := obj.(*apiv1.AppPullImage) if len(strings.Split(appPullImage.Name, ".")) == 2 { result = append(result, field.Invalid(field.NewPath("metadata", "name"), appPullImage.Name, "To update a nested Acorn or a service, update the parent Acorn instead.")) diff --git a/pkg/server/registry/apigroups/acorn/apps/validator.go b/pkg/server/registry/apigroups/acorn/apps/validator.go index 8a6317db5..480e3ca22 100644 --- a/pkg/server/registry/apigroups/acorn/apps/validator.go +++ b/pkg/server/registry/apigroups/acorn/apps/validator.go @@ -77,7 +77,7 @@ func NewValidator(client kclient.Client, clientFactory *client.Factory, deleter } } -func (s *Validator) PrepareForCreate(ctx context.Context, obj runtime.Object) { +func (s *Validator) PrepareForCreate(_ context.Context, obj runtime.Object) { r := obj.(types.Object) if r.GetName() == "" && r.GetGenerateName() == "" { r.SetName(nameGenerator.Generate()) @@ -133,7 +133,7 @@ func (s *Validator) Validate(ctx context.Context, obj runtime.Object) (result fi checkImage = app.Spec.Image ) - tagPattern, isPattern := autoupgrade.AutoUpgradePattern(app.Spec.Image) + tagPattern, isPattern := autoupgrade.Pattern(app.Spec.Image) if isPattern { if latestImage, found, err := autoupgrade.FindLatestTagForImageWithPattern(ctx, s.client, "", app.Namespace, app.Spec.Image, tagPattern); err != nil { result = append(result, field.Invalid(field.NewPath("spec", "image"), app.Spec.Image, err.Error())) diff --git a/pkg/server/registry/apigroups/acorn/builders/port.go b/pkg/server/registry/apigroups/acorn/builders/port.go index ea0b8226a..630a62952 100644 --- a/pkg/server/registry/apigroups/acorn/builders/port.go +++ b/pkg/server/registry/apigroups/acorn/builders/port.go @@ -53,7 +53,7 @@ func (c *BuilderPort) NewConnectOptions() (runtime.Object, bool, string) { return nil, false, "" } -func (c *BuilderPort) Connect(ctx context.Context, id string, options runtime.Object, r registryrest.Responder) (http.Handler, error) { +func (c *BuilderPort) Connect(ctx context.Context, id string, _ runtime.Object, _ registryrest.Responder) (http.Handler, error) { ns, _ := request.NamespaceFrom(ctx) cfg, err := config.Get(ctx, c.client) diff --git a/pkg/server/registry/apigroups/acorn/containers/exec.go b/pkg/server/registry/apigroups/acorn/containers/exec.go index 2e59db8a2..91fb18fae 100644 --- a/pkg/server/registry/apigroups/acorn/containers/exec.go +++ b/pkg/server/registry/apigroups/acorn/containers/exec.go @@ -101,7 +101,7 @@ func (c *ContainerExec) connect(podName, podNamespace, containerName string, exe }), nil } -func (c *ContainerExec) Connect(ctx context.Context, id string, options runtime.Object, r registryrest.Responder) (http.Handler, error) { +func (c *ContainerExec) Connect(ctx context.Context, id string, options runtime.Object, _ registryrest.Responder) (http.Handler, error) { execOpt := options.(*apiv1.ContainerReplicaExecOptions) container := &apiv1.ContainerReplica{} diff --git a/pkg/server/registry/apigroups/acorn/containers/port_forward.go b/pkg/server/registry/apigroups/acorn/containers/port_forward.go index 72780a5c2..0772fa201 100644 --- a/pkg/server/registry/apigroups/acorn/containers/port_forward.go +++ b/pkg/server/registry/apigroups/acorn/containers/port_forward.go @@ -75,7 +75,7 @@ func (c *PortForward) connect(podName, podNamespace string, execOpt *apiv1.Conta }), nil } -func (c *PortForward) Connect(ctx context.Context, id string, options runtime.Object, r registryrest.Responder) (http.Handler, error) { +func (c *PortForward) Connect(ctx context.Context, id string, options runtime.Object, _ registryrest.Responder) (http.Handler, error) { forwardOpts := options.(*apiv1.ContainerReplicaPortForwardOptions) container := &apiv1.ContainerReplica{} diff --git a/pkg/server/registry/apigroups/acorn/containers/translator.go b/pkg/server/registry/apigroups/acorn/containers/translator.go index a86e7de25..3ef02beac 100644 --- a/pkg/server/registry/apigroups/acorn/containers/translator.go +++ b/pkg/server/registry/apigroups/acorn/containers/translator.go @@ -47,7 +47,7 @@ func (t *Translator) FromPublicName(ctx context.Context, namespace, name string) return namespace, strings.Split(containerName, ":")[0], nil } -func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { +func (t *Translator) ListOpts(_ context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { sel := opts.Predicate.Label if sel == nil { sel = klabels.Everything() @@ -63,7 +63,7 @@ func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storag return "", opts, nil } -func (t *Translator) ToPublic(ctx context.Context, objs ...runtime.Object) (result []mtypes.Object, _ error) { +func (t *Translator) ToPublic(_ context.Context, objs ...runtime.Object) (result []mtypes.Object, _ error) { for _, obj := range objs { for _, con := range podToContainers(obj.(*corev1.Pod)) { con := con diff --git a/pkg/server/registry/apigroups/acorn/credentials/strategy.go b/pkg/server/registry/apigroups/acorn/credentials/strategy.go index 7fea2ac57..f53873205 100644 --- a/pkg/server/registry/apigroups/acorn/credentials/strategy.go +++ b/pkg/server/registry/apigroups/acorn/credentials/strategy.go @@ -16,11 +16,11 @@ import ( type Strategy struct { } -func (s *Strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { +func (s *Strategy) PrepareForUpdate(ctx context.Context, obj, _ runtime.Object) { s.PrepareForCreate(ctx, obj) } -func (s *Strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) { +func (s *Strategy) PrepareForCreate(_ context.Context, obj runtime.Object) { cred := obj.(*apiv1.Credential) cred.ServerAddress = imagesystem.NormalizeServerAddress(cred.ServerAddress) } @@ -34,7 +34,7 @@ func (s *Strategy) Validate(ctx context.Context, obj runtime.Object) (result fie } return result } -func (s *Strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) (result field.ErrorList) { +func (s *Strategy) ValidateUpdate(ctx context.Context, obj, _ runtime.Object) (result field.ErrorList) { params := obj.(*apiv1.Credential) return s.Validate(ctx, params) } diff --git a/pkg/server/registry/apigroups/acorn/credentials/translator.go b/pkg/server/registry/apigroups/acorn/credentials/translator.go index 19f4000fc..99eb6e31f 100644 --- a/pkg/server/registry/apigroups/acorn/credentials/translator.go +++ b/pkg/server/registry/apigroups/acorn/credentials/translator.go @@ -22,11 +22,11 @@ type Translator struct { reveal bool } -func (t *Translator) FromPublicName(ctx context.Context, namespace, name string) (string, string, error) { +func (t *Translator) FromPublicName(_ context.Context, namespace, name string) (string, string, error) { return namespace, strings.ReplaceAll(imagesystem.NormalizeServerAddress(name), ":", "-"), nil } -func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { +func (t *Translator) ListOpts(_ context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { if opts.Predicate.Label == nil { opts.Predicate.Label = klabels.Everything() } @@ -38,7 +38,7 @@ func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storag return namespace, opts, nil } -func (t *Translator) ToPublic(ctx context.Context, objs ...runtime.Object) (result []types.Object, _ error) { +func (t *Translator) ToPublic(_ context.Context, objs ...runtime.Object) (result []types.Object, _ error) { for _, obj := range objs { secret := obj.(*corev1.Secret) if secret.Type != apiv1.SecretTypeCredential { diff --git a/pkg/server/registry/apigroups/acorn/imageallowrules/validator.go b/pkg/server/registry/apigroups/acorn/imageallowrules/validator.go index a98ecafe6..17ee183a2 100644 --- a/pkg/server/registry/apigroups/acorn/imageallowrules/validator.go +++ b/pkg/server/registry/apigroups/acorn/imageallowrules/validator.go @@ -11,20 +11,20 @@ import ( type Validator struct{} -func (s *Validator) Validate(ctx context.Context, obj runtime.Object) (result field.ErrorList) { +func (s *Validator) Validate(_ context.Context, obj runtime.Object) (result field.ErrorList) { aiar := obj.(*apiv1.ImageAllowRule) if len(aiar.ImageSelector.NamePatterns) == 0 { return append(result, field.Required(field.NewPath("images"), "the images scope must be set to define which images this rule applies to")) } - result = append(result, validateSignatureRules(ctx, aiar.ImageSelector.Signatures)...) + result = append(result, validateSignatureRules(aiar.ImageSelector.Signatures)...) return } -func (s *Validator) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { +func (s *Validator) ValidateUpdate(ctx context.Context, obj, _ runtime.Object) field.ErrorList { return s.Validate(ctx, obj) } -func validateSignatureRules(ctx context.Context, sigRules []internalv1.SignatureRules) (result field.ErrorList) { +func validateSignatureRules(sigRules []internalv1.SignatureRules) (result field.ErrorList) { for i, rule := range sigRules { if len(rule.SignedBy.AnyOf) == 0 && len(rule.SignedBy.AllOf) == 0 { result = append(result, field.Invalid(field.NewPath("signatures").Index(i).Child("signedBy"), rule.SignedBy, "must not be empty (at least one of anyOf or allOf must be specified)")) diff --git a/pkg/server/registry/apigroups/acorn/images/pull.go b/pkg/server/registry/apigroups/acorn/images/pull.go index 52a5f0f00..05c80b3f3 100644 --- a/pkg/server/registry/apigroups/acorn/images/pull.go +++ b/pkg/server/registry/apigroups/acorn/images/pull.go @@ -58,7 +58,7 @@ func (i *ImagePull) NewConnectOptions() (runtime.Object, bool, string) { return &apiv1.ImagePull{}, false, "" } -func (i *ImagePull) Connect(ctx context.Context, id string, options runtime.Object, r rest.Responder) (http.Handler, error) { +func (i *ImagePull) Connect(ctx context.Context, id string, _ runtime.Object, _ rest.Responder) (http.Handler, error) { id = strings.ReplaceAll(id, "+", "/") ns, _ := request.NamespaceFrom(ctx) diff --git a/pkg/server/registry/apigroups/acorn/images/push.go b/pkg/server/registry/apigroups/acorn/images/push.go index 5772b073f..51074ef9e 100644 --- a/pkg/server/registry/apigroups/acorn/images/push.go +++ b/pkg/server/registry/apigroups/acorn/images/push.go @@ -55,7 +55,7 @@ func (i *ImagePush) New() runtime.Object { return &apiv1.ImagePush{} } -func (i *ImagePush) Connect(ctx context.Context, id string, options runtime.Object, r rest.Responder) (http.Handler, error) { +func (i *ImagePush) Connect(ctx context.Context, id string, _ runtime.Object, _ rest.Responder) (http.Handler, error) { ns, _ := request.NamespaceFrom(ctx) tagName := strings.ReplaceAll(id, "+", "/") diff --git a/pkg/server/registry/apigroups/acorn/info/strategy.go b/pkg/server/registry/apigroups/acorn/info/strategy.go index 7a618dab6..2bff1b3ed 100644 --- a/pkg/server/registry/apigroups/acorn/info/strategy.go +++ b/pkg/server/registry/apigroups/acorn/info/strategy.go @@ -31,7 +31,7 @@ func (s *Strategy) New() types.Object { return &apiv1.Info{} } -func (s *Strategy) List(ctx context.Context, namespace string, options storage.ListOptions) (types.ObjectList, error) { +func (s *Strategy) List(ctx context.Context, _ string, _ storage.ListOptions) (types.ObjectList, error) { var publicKeys []apiv1.EncryptionKey ns, _ := request.NamespaceFrom(ctx) if ns != "" { diff --git a/pkg/server/registry/apigroups/acorn/secrets/translator.go b/pkg/server/registry/apigroups/acorn/secrets/translator.go index c8caa2426..c41f727d1 100644 --- a/pkg/server/registry/apigroups/acorn/secrets/translator.go +++ b/pkg/server/registry/apigroups/acorn/secrets/translator.go @@ -69,11 +69,11 @@ func (t *Translator) FromPublicName(ctx context.Context, namespace, name string) return namespace, name, nil } -func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { +func (t *Translator) ListOpts(_ context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { return namespace, opts, nil } -func (t *Translator) ToPublic(ctx context.Context, objs ...runtime.Object) (result []types.Object, _ error) { +func (t *Translator) ToPublic(_ context.Context, objs ...runtime.Object) (result []types.Object, _ error) { for _, obj := range objs { var keys []string secret := obj.(*corev1.Secret) diff --git a/pkg/server/registry/apigroups/acorn/secrets/validator.go b/pkg/server/registry/apigroups/acorn/secrets/validator.go index 6e5cb9776..91f26353e 100644 --- a/pkg/server/registry/apigroups/acorn/secrets/validator.go +++ b/pkg/server/registry/apigroups/acorn/secrets/validator.go @@ -14,7 +14,7 @@ import ( type Validator struct { } -func (v *Validator) Validate(ctx context.Context, obj runtime.Object) (result field.ErrorList) { +func (v *Validator) Validate(_ context.Context, obj runtime.Object) (result field.ErrorList) { sec := obj.(*apiv1.Secret) if sec.Type != "" { if !v1.SecretTypes[corev1.SecretType(v1.SecretTypePrefix+sec.Type)] && !strings.HasPrefix(sec.Type, v1.SecretTypeCredentialPrefix) { @@ -24,6 +24,6 @@ func (v *Validator) Validate(ctx context.Context, obj runtime.Object) (result fi return } -func (v *Validator) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { +func (v *Validator) ValidateUpdate(ctx context.Context, obj, _ runtime.Object) field.ErrorList { return v.Validate(ctx, obj) } diff --git a/pkg/server/registry/apigroups/acorn/volumes/translator.go b/pkg/server/registry/apigroups/acorn/volumes/translator.go index 802a5a3f4..5eeff359f 100644 --- a/pkg/server/registry/apigroups/acorn/volumes/translator.go +++ b/pkg/server/registry/apigroups/acorn/volumes/translator.go @@ -51,7 +51,7 @@ func (t *Translator) FromPublicName(ctx context.Context, namespace, name string) return "", name, nil } -func (t *Translator) ListOpts(ctx context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { +func (t *Translator) ListOpts(_ context.Context, namespace string, opts storage.ListOptions) (string, storage.ListOptions, error) { sel := opts.Predicate.Label if sel == nil { sel = klabels.Everything() @@ -129,7 +129,7 @@ func (t *Translator) ToPublic(ctx context.Context, objs ...runtime.Object) (resu return } -func (t *Translator) FromPublic(ctx context.Context, obj runtime.Object) (types.Object, error) { +func (t *Translator) FromPublic(_ context.Context, obj runtime.Object) (types.Object, error) { vol := obj.(*apiv1.Volume) pv := &corev1.PersistentVolume{ ObjectMeta: vol.ObjectMeta, diff --git a/pkg/server/registry/apigroups/admin/computeclass/strategy.go b/pkg/server/registry/apigroups/admin/computeclass/strategy.go index 47da7cdc6..23e1413f4 100644 --- a/pkg/server/registry/apigroups/admin/computeclass/strategy.go +++ b/pkg/server/registry/apigroups/admin/computeclass/strategy.go @@ -31,7 +31,7 @@ func (s *Strategy) New() types.Object { return &apiv1.ComputeClass{} } -func (s *Strategy) List(ctx context.Context, namespace string, options storage.ListOptions) (types.ObjectList, error) { +func (s *Strategy) List(ctx context.Context, namespace string, _ storage.ListOptions) (types.ObjectList, error) { clusterComputeClasses := &adminv1.ClusterComputeClassInstanceList{} if err := s.client.List(ctx, clusterComputeClasses); err != nil { return nil, err diff --git a/pkg/server/registry/apigroups/admin/computeclass/validator.go b/pkg/server/registry/apigroups/admin/computeclass/validator.go index f50c2864c..ce861522c 100644 --- a/pkg/server/registry/apigroups/admin/computeclass/validator.go +++ b/pkg/server/registry/apigroups/admin/computeclass/validator.go @@ -53,7 +53,7 @@ func (s *ProjectValidator) Validate(ctx context.Context, obj runtime.Object) (re return append(result, validateMemorySpec(cc.Memory)...) } -func (s *ProjectValidator) ValidateUpdate(ctx context.Context, newObj, oldObj runtime.Object) field.ErrorList { +func (s *ProjectValidator) ValidateUpdate(ctx context.Context, newObj, _ runtime.Object) field.ErrorList { return s.Validate(ctx, newObj) } diff --git a/pkg/server/registry/apigroups/admin/imageroleauthorizations/validator.go b/pkg/server/registry/apigroups/admin/imageroleauthorizations/validator.go index 9698eb113..39fe3fa05 100644 --- a/pkg/server/registry/apigroups/admin/imageroleauthorizations/validator.go +++ b/pkg/server/registry/apigroups/admin/imageroleauthorizations/validator.go @@ -11,7 +11,7 @@ import ( type Validator struct{} -func (s *Validator) Validate(ctx context.Context, obj runtime.Object) (result field.ErrorList) { +func (s *Validator) Validate(_ context.Context, obj runtime.Object) (result field.ErrorList) { aiar := obj.(*adminv1.ImageRoleAuthorization) if len(aiar.Spec.ImageSelector.NamePatterns) == 0 { return append(result, field.Required(field.NewPath("imageSelector", "namePatterns"), "the image selector patterns must be defined to specify which images this rule applies to")) @@ -20,7 +20,7 @@ func (s *Validator) Validate(ctx context.Context, obj runtime.Object) (result fi return } -func (s *Validator) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { +func (s *Validator) ValidateUpdate(ctx context.Context, obj, _ runtime.Object) field.ErrorList { return s.Validate(ctx, obj) } @@ -36,7 +36,7 @@ func validateSignatureRules(sigRules []internalv1.SignatureRules) (result field. type ClusterValidator struct{} -func (s *ClusterValidator) Validate(ctx context.Context, obj runtime.Object) (result field.ErrorList) { +func (s *ClusterValidator) Validate(_ context.Context, obj runtime.Object) (result field.ErrorList) { aiar := obj.(*adminv1.ClusterImageRoleAuthorization) if len(aiar.Spec.ImageSelector.NamePatterns) == 0 { return append(result, field.Required(field.NewPath("imageSelector", "namePatterns"), "the image selector patterns must be defined to specify which images this rule applies to")) @@ -45,6 +45,6 @@ func (s *ClusterValidator) Validate(ctx context.Context, obj runtime.Object) (re return } -func (s *ClusterValidator) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList { +func (s *ClusterValidator) ValidateUpdate(ctx context.Context, obj, _ runtime.Object) field.ErrorList { return s.Validate(ctx, obj) } diff --git a/pkg/tables/converter.go b/pkg/tables/converter.go index 22c8e1aac..9682b2d55 100644 --- a/pkg/tables/converter.go +++ b/pkg/tables/converter.go @@ -50,7 +50,7 @@ func NewConverter(tableDef [][]string) (*Converter, error) { return &c, nil } -func (c Converter) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { +func (c Converter) ConvertToTable(_ context.Context, object runtime.Object, _ runtime.Object) (*metav1.Table, error) { var ( rows []metav1.TableRow listMeta metav1.ListMeta