From 44db34c6d087726b807b8c45e4c441ba310ca599 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:00:54 -0500 Subject: [PATCH 01/35] add updated linter config --- .golangci.yaml | 251 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 196 insertions(+), 55 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index d71846bd1792..71f04e919313 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,74 +1,215 @@ run: timeout: 10m - + allow-parallel-runners: true + exclude-dirs: + - pkg/client build-tags: - - e2e - - upgrade + - e2e + - hpa + - upgrade + +output: + sort-results: true + sort-order: + - linter + - file + show-stats: true - skip-dirs: - - pkg/client - skip-files: - - ".pb.go$" +issues: + uniq-by-line: true + max-issues-per-linter: 0 + max-same-issues: 0 + exclude-rules: + - path: test # Excludes /test, *_test.go etc. + linters: + - gosec + - unparam + - noctx + - protogetter + - linters: ["gocritic"] + # Fixes are non-trivial do in a follow up + text: "ifElseChain" + +linters-settings: + # goimports: + # local-prefixes: knative.dev/pkg + gomodguard: + blocked: + modules: + - github.com/ghodss/yaml: + recommendations: + - sigs.k8s.io/yaml + - go.uber.org/atomic: + recommendations: + - sync/atomic + - io/ioutil: + recommendations: + - os + - io + - github.com/hashicorp/go-multierror: + reason: "use errors.Join" + recommendations: + - errors + - go.uber.org/multierr: + reason: "use errors.Join" + recommendations: + - errors + revive: + rules: + # use unparam linter instead - defaults are better + - name: unused-parameter + disabled: true linters: + disable: + - errcheck enable: + # Check for pass []any as any in variadic func(...any). + - asasalint + + # Only use ASCII chars in indentifiers - asciicheck - - depguard + + # Dangerous unicode characters + - bidichk + + # Checks whether HTTP response body is closed successfully. + - bodyclose + + # Canonicalheader checks whether net/http.Header uses canonical header. + - canonicalheader + + # TODO - do a follow up PR + # # Containedctx is a linter that detects struct contained context.Context + # # field. + # - containedctx + + # TODO - do a follow up PR + # # Check whether the function uses a non-inherited context. + # - contextcheck + + # Copyloopvar is a linter detects places where loop variables are copied. + - copyloopvar + + # Check declaration order of types, consts, vars and funcs. + - decorder + + # Check for two durations multiplied together. + - durationcheck + + # Checks that sentinel errors are prefixed with the Err- and error types + # are suffixed with the -Error. + - errname + + # Errorlint is a linter for that can be used to find code that will cause + # problems with the error wrapping scheme introduced in Go 1.13. - errorlint + + # Detects nested contexts in loops. + - fatcontext + + # Checks that go compiler directive comments (//go:) are valid. + - gocheckcompilerdirectives + + # Provides diagnostics that check for bugs, performance and style issues. + # Extensible without recompilation through dynamic rules. + # Dynamic rules are written declaratively with AST patterns, filters, + # report message and optional suggestion. + - gocritic + + # Gofmt checks whether code was gofmt-ed. By default this tool runs + # with -s option to check for code simplification. + - gofmt + + # Gofumpt checks whether code was gofumpt-ed. + - gofumpt + + # Check import statements are formatted according to the 'goimport' + # command. Reformat imports in autofix mode. + - goimports + + # See config below + - gomodguard + + # Inspects source code for security problems. - gosec - - importas + + # Linter that specializes in simplifying code. + - gosimple + - govet + + # Intrange is a linter to find places where for loops could make use of + # an integer range. + - intrange + + # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). + - loggercheck + + # Finds slice declarations with non-zero initial length. + - makezero + + # Reports wrong mirror patterns of bytes/strings usage + - mirror + + # Finds commonly misspelled English words. + - misspell + + # Finds the code that returns nil even if it checks that the error is not nil. + - nilerr + + # Finds sending HTTP request without context.Context. + - noctx + + # Reports ill-formed or insufficient nolint directives. + - nolintlint + + # Checks for misuse of Sprintf to construct a host with port in a URL. + - nosprintfhostport + + # Checks that fmt.Sprintf can be replaced with a faster alternative. + - perfsprint + + # Finds slice declarations that could potentially be pre-allocated. - prealloc + + # Reports direct reads from proto message fields when getters should be used. + - protogetter + + # Checks that package variables are not reassigned. + - reassign + + # Fast, configurable, extensible, flexible, and beautiful linter for + # Go. Drop-in replacement of golint. - revive + + # Checks for mistakes with OpenTelemetry/Census spans. + - spancheck + + # Stylecheck is a replacement for golint. - stylecheck - - tparallel + + # Tenv is analyzer that detects using os.Setenv instead of t.Setenv + # since Go1.17. + - tenv + + # Linter checks if examples are testable (have an expected output). + - testableexamples + + # Remove unnecessary type conversions. - unconvert + + # Reports unused function parameters and results in your code. - unparam - disable: - - errcheck -linters-settings: - depguard: - rules: - main: - deny: - - pkg: sync/atomic - desc: "please use type-safe atomics from go.uber.org/atomic" - importas: - no-unaliased: true - alias: - - pkg: knative.dev/serving/pkg/apis/autoscaling/v1alpha1 - alias: autoscalingv1alpha1 + # A linter that detect the possibility to use variables/constants from the + # Go standard library. + - usestdlibvars -issues: - include: - # Disable excluding issues about comments from golint. - - EXC0002 + # Finds wasted assignment statements. + - wastedassign + + # Whitespace is a linter that checks for unnecessary newlines at the start + # and end of functions, if, for, etc. + - whitespace - exclude-rules: - - path: test # Excludes /test, *_test.go etc. - linters: - - gosec - - unparam - - # Ignore "context.Context should be the first parameter of a function" errors in tests. - # See: https://github.com/golang/lint/issues/422 - - path: test - text: "context.Context should be the first" - linters: - - revive - - # Allow source and sink receivers in conversion code for clarity. - - path: _conversion\.go - text: "ST1016:" - linters: - - stylecheck - - path: _conversion\.go - text: "receiver name" - linters: - - revive - - # This check has quite a few false positives where there isn't much value in the package comment. - - text: "ST1000: at least one file in a package should have a package comment" - linters: - - stylecheck From 4bd06ebe037b3d4d5912eb0183c326bf84a5917a Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:04:29 -0500 Subject: [PATCH 02/35] fix whitespace linting --- cmd/schema-tweak/main.go | 3 --- cmd/schema-tweak/yaml.go | 1 - pkg/activator/certificate/cache_test.go | 1 - pkg/activator/handler/main_test.go | 1 - pkg/apis/autoscaling/v1alpha1/pa_lifecycle_test.go | 1 - pkg/apis/serving/fieldmask.go | 6 ------ pkg/apis/serving/fieldmask_test.go | 2 -- pkg/apis/serving/k8s_lifecycle.go | 1 - pkg/apis/serving/v1/revision_lifecycle_test.go | 2 -- pkg/apis/serving/v1/service_defaults.go | 1 - pkg/apis/serving/v1/service_lifecycle_test.go | 1 - pkg/autoscaler/aggregation/bucketing_test.go | 1 - pkg/autoscaler/config/config.go | 1 - pkg/autoscaler/scaling/autoscaler.go | 2 -- pkg/http/handler/timeout_test.go | 1 - pkg/queue/breaker_test.go | 1 - pkg/queue/health/probe.go | 1 - pkg/reconciler/accessor/networking/certificate.go | 2 -- pkg/reconciler/certificate/certificate_test.go | 1 - pkg/reconciler/certificate/controller.go | 1 - .../certificate/resources/cert_manager_certificate.go | 1 - pkg/reconciler/configuration/configuration.go | 1 - pkg/reconciler/configuration/configuration_test.go | 1 - pkg/reconciler/domainmapping/reconciler.go | 1 - pkg/reconciler/domainmapping/resources/ingress_test.go | 1 - pkg/reconciler/gc/gc.go | 1 - pkg/reconciler/labeler/accessors.go | 1 - pkg/reconciler/revision/rate_limiter_test.go | 2 -- pkg/reconciler/revision/resolve_test.go | 2 -- pkg/reconciler/revision/resources/meta_test.go | 1 - pkg/reconciler/revision/resources/queue.go | 1 - pkg/reconciler/revision/revision_test.go | 1 - pkg/reconciler/route/config/domain.go | 1 - pkg/reconciler/route/reconcile_resources.go | 2 -- pkg/reconciler/route/resources/ingress_test.go | 1 - pkg/reconciler/route/route_test.go | 1 - pkg/reconciler/route/table_test.go | 1 - pkg/reconciler/route/traffic/rollout_test.go | 2 -- pkg/reconciler/serverlessservice/controller.go | 1 - pkg/reconciler/testing/v1/factory.go | 1 - pkg/resources/pods_test.go | 3 --- pkg/webhook/podspec_dryrun_test.go | 2 -- test/conformance/api/v1/configuration_test.go | 1 - test/conformance/api/v1/revision_test.go | 1 - test/conformance/api/v1/service_test.go | 1 - test/conformance/api/v1/util.go | 1 - test/conformance/runtime/cgroup_test.go | 1 - test/conformance/runtime/user_test.go | 1 - test/conformance/runtime/util.go | 2 -- test/e2e/autoscale.go | 2 -- test/e2e/externaldomaintls/config/dnssetup/main.go | 1 - test/e2e/http2_test.go | 1 - test/e2e/readiness_test.go | 1 - test/e2e/websocket_test.go | 1 - 54 files changed, 74 deletions(-) diff --git a/cmd/schema-tweak/main.go b/cmd/schema-tweak/main.go index c48a68bbecbb..43b06f71ec4f 100644 --- a/cmd/schema-tweak/main.go +++ b/cmd/schema-tweak/main.go @@ -44,7 +44,6 @@ func main() { processFile(file) } - } func processFile(file fs.DirEntry) { @@ -81,7 +80,6 @@ func processFile(file fs.DirEntry) { if err = os.WriteFile(filename, buf.Bytes(), file.Type().Perm()); err != nil { log.Fatalln("failed to write CRD", err) } - } func applyOverrides(root *yaml.Node) { @@ -184,7 +182,6 @@ func updateFeatureFlagProperty(root *yaml.Node, f flagField) { Value: "true", }, ) - } func filterAllowedFields(node *yaml.Node, allowed sets.Set[string], features []flagField) { diff --git a/cmd/schema-tweak/yaml.go b/cmd/schema-tweak/yaml.go index e98642ebbc07..efa47d135303 100644 --- a/cmd/schema-tweak/yaml.go +++ b/cmd/schema-tweak/yaml.go @@ -150,5 +150,4 @@ func deleteKeysExcluding(node *yaml.Node, keys ...string) { i -= 2 // reset index } } - } diff --git a/pkg/activator/certificate/cache_test.go b/pkg/activator/certificate/cache_test.go index de7d2b543562..7ab6c006bf90 100644 --- a/pkg/activator/certificate/cache_test.go +++ b/pkg/activator/certificate/cache_test.go @@ -43,7 +43,6 @@ import ( ) func TestReconcile(t *testing.T) { - tests := []struct { name string secret *corev1.Secret diff --git a/pkg/activator/handler/main_test.go b/pkg/activator/handler/main_test.go index 4ea142dc0207..c1a850c760d3 100644 --- a/pkg/activator/handler/main_test.go +++ b/pkg/activator/handler/main_test.go @@ -234,7 +234,6 @@ func TestActivatorChainHandlerWithFullDuplex(t *testing.T) { wg.Wait() } - } func send(client *http.Client, url string, body []byte, rHost string) error { diff --git a/pkg/apis/autoscaling/v1alpha1/pa_lifecycle_test.go b/pkg/apis/autoscaling/v1alpha1/pa_lifecycle_test.go index 3523b961c083..e2e23399c2da 100644 --- a/pkg/apis/autoscaling/v1alpha1/pa_lifecycle_test.go +++ b/pkg/apis/autoscaling/v1alpha1/pa_lifecycle_test.go @@ -71,7 +71,6 @@ func TestGeneration(t *testing.T) { if e, a := int64(5), r.GetGeneration(); e != a { t.Errorf("getgeneration mismatch expected: %d got: %d", e, a) } - } func TestInactiveFor(t *testing.T) { diff --git a/pkg/apis/serving/fieldmask.go b/pkg/apis/serving/fieldmask.go index 142d42d36fac..cba7049cce8b 100644 --- a/pkg/apis/serving/fieldmask.go +++ b/pkg/apis/serving/fieldmask.go @@ -389,7 +389,6 @@ func HandlerMask(in *corev1.ProbeHandler) *corev1.ProbeHandler { out.GRPC = in.GRPC return out - } // ExecActionMask performs a _shallow_ copy of the Kubernetes ExecAction object to a new @@ -552,7 +551,6 @@ func ConfigMapKeySelectorMask(in *corev1.ConfigMapKeySelector) *corev1.ConfigMap out.LocalObjectReference = in.LocalObjectReference return out - } // SecretKeySelectorMask performs a _shallow_ copy of the Kubernetes SecretKeySelector object to a new @@ -571,7 +569,6 @@ func SecretKeySelectorMask(in *corev1.SecretKeySelector) *corev1.SecretKeySelect out.LocalObjectReference = in.LocalObjectReference return out - } // ConfigMapEnvSourceMask performs a _shallow_ copy of the Kubernetes ConfigMapEnvSource object to a new @@ -589,7 +586,6 @@ func ConfigMapEnvSourceMask(in *corev1.ConfigMapEnvSource) *corev1.ConfigMapEnvS out.LocalObjectReference = in.LocalObjectReference return out - } // SecretEnvSourceMask performs a _shallow_ copy of the Kubernetes SecretEnvSource object to a new @@ -607,7 +603,6 @@ func SecretEnvSourceMask(in *corev1.SecretEnvSource) *corev1.SecretEnvSource { out.LocalObjectReference = in.LocalObjectReference return out - } // EnvFromSourceMask performs a _shallow_ copy of the Kubernetes EnvFromSource object to a new @@ -643,7 +638,6 @@ func ResourceRequirementsMask(in *corev1.ResourceRequirements) *corev1.ResourceR out.Requests = in.Requests return out - } // PodSecurityContextMask performs a _shallow_ copy of the Kubernetes PodSecurityContext object into a new diff --git a/pkg/apis/serving/fieldmask_test.go b/pkg/apis/serving/fieldmask_test.go index de999bc09e5e..b94f18c7efbe 100644 --- a/pkg/apis/serving/fieldmask_test.go +++ b/pkg/apis/serving/fieldmask_test.go @@ -110,7 +110,6 @@ func TestCapabilitiesMask_SecurePodDefaultsEnabled(t *testing.T) { } }) } - } func TestVolumeSourceMask(t *testing.T) { @@ -879,7 +878,6 @@ func TestPodSecurityContextMask_FeatureEnabled(t *testing.T) { } func TestPodSecurityContextMask_SecurePodDefaultsEnabled(t *testing.T) { - // Ensure that users can opt out of better security by explicitly // requesting the Kubernetes default, which is "Unconfined". want := &corev1.PodSecurityContext{ diff --git a/pkg/apis/serving/k8s_lifecycle.go b/pkg/apis/serving/k8s_lifecycle.go index f63060c8b521..aaf977564c2a 100644 --- a/pkg/apis/serving/k8s_lifecycle.go +++ b/pkg/apis/serving/k8s_lifecycle.go @@ -83,7 +83,6 @@ func TransformDeploymentStatus(ds *appsv1.DeploymentStatus) *duckv1.Status { depCondSet.Manage(s).MarkTrue(DeploymentConditionReplicaSetReady) } } - } } diff --git a/pkg/apis/serving/v1/revision_lifecycle_test.go b/pkg/apis/serving/v1/revision_lifecycle_test.go index 7032c94ade52..128d56cb1069 100644 --- a/pkg/apis/serving/v1/revision_lifecycle_test.go +++ b/pkg/apis/serving/v1/revision_lifecycle_test.go @@ -98,7 +98,6 @@ func TestGetContainerConcurrency(t *testing.T) { } }) } - } func TestRevisionIsReady(t *testing.T) { @@ -597,7 +596,6 @@ func TestPropagateAutoscalerStatus_NoOverridingResourcesAvailable(t *testing.T) for _, tc := range cases { t.Run(fmt.Sprintf("ready is %v", tc), func(t *testing.T) { - r := &RevisionStatus{} r.InitializeConditions() apistest.CheckConditionOngoing(r, RevisionConditionReady, t) diff --git a/pkg/apis/serving/v1/service_defaults.go b/pkg/apis/serving/v1/service_defaults.go index be876c3a46cc..df1eba33bd96 100644 --- a/pkg/apis/serving/v1/service_defaults.go +++ b/pkg/apis/serving/v1/service_defaults.go @@ -35,7 +35,6 @@ func (s *Service) SetDefaults(ctx context.Context) { s.Spec.SetDefaults(apis.WithinSpec(ctx)) serving.SetUserInfo(ctx, prevSpec, &s.Spec, s) - } // SetDefaults implements apis.Defaultable diff --git a/pkg/apis/serving/v1/service_lifecycle_test.go b/pkg/apis/serving/v1/service_lifecycle_test.go index 4ba588685ca3..051deae7e4c5 100644 --- a/pkg/apis/serving/v1/service_lifecycle_test.go +++ b/pkg/apis/serving/v1/service_lifecycle_test.go @@ -441,7 +441,6 @@ func TestConfigurationFailurePropagation(t *testing.T) { apistest.CheckConditionFailed(svc, ServiceConditionReady, t) apistest.CheckConditionFailed(svc, ServiceConditionConfigurationsReady, t) apistest.CheckConditionOngoing(svc, ServiceConditionRoutesReady, t) - } func TestConfigurationFailureRecovery(t *testing.T) { diff --git a/pkg/autoscaler/aggregation/bucketing_test.go b/pkg/autoscaler/aggregation/bucketing_test.go index c7c5a290b8c0..1b5a6211b3f0 100644 --- a/pkg/autoscaler/aggregation/bucketing_test.go +++ b/pkg/autoscaler/aggregation/bucketing_test.go @@ -638,7 +638,6 @@ func TestRoundToNDigits(t *testing.T) { if got, want := roundToNDigits(6, 12345), 12345.; got != want { t.Errorf("Rounding = %v, want: %v", got, want) } - } func (t *TimedFloat64Buckets) forEachBucket(now time.Time, acc func(time time.Time, bucket float64)) { diff --git a/pkg/autoscaler/config/config.go b/pkg/autoscaler/config/config.go index 8ae207d338d5..25bc0076b58e 100644 --- a/pkg/autoscaler/config/config.go +++ b/pkg/autoscaler/config/config.go @@ -172,7 +172,6 @@ func validate(lc *autoscalerconfig.Config) (*autoscalerconfig.Config, error) { lc.PanicWindowPercentage > autoscaling.PanicWindowPercentageMax { return nil, fmt.Errorf("panic-window-percentage = %v, must be in [%v, %v] interval", lc.PanicWindowPercentage, autoscaling.PanicWindowPercentageMin, autoscaling.PanicWindowPercentageMax) - } if lc.InitialScale < 0 || (lc.InitialScale == 0 && !lc.AllowZeroInitialScale) { diff --git a/pkg/autoscaler/scaling/autoscaler.go b/pkg/autoscaler/scaling/autoscaler.go index 01f815f5d942..1ecaa4c15cc1 100644 --- a/pkg/autoscaler/scaling/autoscaler.go +++ b/pkg/autoscaler/scaling/autoscaler.go @@ -69,7 +69,6 @@ func New( metricClient metrics.MetricClient, podCounter resources.EndpointsCounter, deciderSpec *DeciderSpec) UniScaler { - var delayer *max.TimeWindow if deciderSpec.ScaleDownDelay > 0 { delayer = max.NewTimeWindow(deciderSpec.ScaleDownDelay, tickInterval) @@ -86,7 +85,6 @@ func newAutoscaler( podCounter podCounter, deciderSpec *DeciderSpec, delayWindow *max.TimeWindow) *autoscaler { - // We always start in the panic mode, if the deployment is scaled up over 1 pod. // If the scale is 0 or 1, normal Autoscaler behavior is fine. // When Autoscaler restarts we lose metric history, which causes us to diff --git a/pkg/http/handler/timeout_test.go b/pkg/http/handler/timeout_test.go index b388e94d5ddd..fb6068cf1e7f 100644 --- a/pkg/http/handler/timeout_test.go +++ b/pkg/http/handler/timeout_test.go @@ -398,7 +398,6 @@ func TestTimeoutHandler(t *testing.T) { }} testTimeoutScenario(t, scenarios) - } func BenchmarkTimeoutHandler(b *testing.B) { diff --git a/pkg/queue/breaker_test.go b/pkg/queue/breaker_test.go index 1fcfe2e86b9d..79044873579a 100644 --- a/pkg/queue/breaker_test.go +++ b/pkg/queue/breaker_test.go @@ -220,7 +220,6 @@ func TestBreakerUpdateConcurrency(t *testing.T) { if got, want := b.Capacity(), 0; got != want { t.Errorf("Capacity() = %d, want: %d", got, want) } - } // Test empty semaphore, token cannot be acquired diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 2aa0d6e27e4d..1ca0c556b639 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -226,7 +226,6 @@ func isHTTPProbeReady(res *http.Response) bool { // GRPCProbe checks that gRPC connection can be established to the address. func GRPCProbe(config GRPCProbeConfigOptions) error { - // Use k8s.io/kubernetes/pkg/probe/dialer_others.go to correspond to OSs other than Windows dialer := &net.Dialer{ Control: func(network, address string, c syscall.RawConn) error { diff --git a/pkg/reconciler/accessor/networking/certificate.go b/pkg/reconciler/accessor/networking/certificate.go index d843175223c7..8f6a45e21259 100644 --- a/pkg/reconciler/accessor/networking/certificate.go +++ b/pkg/reconciler/accessor/networking/certificate.go @@ -41,7 +41,6 @@ type CertificateAccessor interface { // ReconcileCertificate reconciles Certificate to the desired status. func ReconcileCertificate(ctx context.Context, owner kmeta.Accessor, desired *v1alpha1.Certificate, certAccessor CertificateAccessor) (*v1alpha1.Certificate, error) { - recorder := controller.GetEventRecorder(ctx) if recorder == nil { return nil, fmt.Errorf("recorder for reconciling Certificate %s/%s is not created", desired.Namespace, desired.Name) @@ -66,7 +65,6 @@ func ReconcileCertificate(ctx context.Context, owner kmeta.Accessor, desired *v1 } else if !equality.Semantic.DeepEqual(cert.Spec, desired.Spec) || !equality.Semantic.DeepEqual(cert.Annotations, desired.Annotations) || !equality.Semantic.DeepEqual(cert.Labels, desired.Labels) { - // Don't modify the informers copy existing := cert.DeepCopy() existing.Spec = desired.Spec diff --git a/pkg/reconciler/certificate/certificate_test.go b/pkg/reconciler/certificate/certificate_test.go index a4ef1b1719d9..f43b5ff01480 100644 --- a/pkg/reconciler/certificate/certificate_test.go +++ b/pkg/reconciler/certificate/certificate_test.go @@ -908,5 +908,4 @@ func cmSolverService(hostname, namespace string) *corev1.Service { }}, }, } - } diff --git a/pkg/reconciler/certificate/controller.go b/pkg/reconciler/certificate/controller.go index aea5682c48a0..b841c31b2fa0 100644 --- a/pkg/reconciler/certificate/controller.go +++ b/pkg/reconciler/certificate/controller.go @@ -53,7 +53,6 @@ func AnnotateLoggerWithName(ctx context.Context, name string) context.Context { With(zap.String(logkey.ControllerType, name)) return logging.WithLogger(ctx, logger) - } // NewController initializes the controller and is called by the generated code diff --git a/pkg/reconciler/certificate/resources/cert_manager_certificate.go b/pkg/reconciler/certificate/resources/cert_manager_certificate.go index d64602fe2a70..7431e1c68363 100644 --- a/pkg/reconciler/certificate/resources/cert_manager_certificate.go +++ b/pkg/reconciler/certificate/resources/cert_manager_certificate.go @@ -95,7 +95,6 @@ func MakeCertManagerCertificate(cmConfig *config.CertManagerConfig, knCert *v1al commonName = Prefix + knCert.Spec.Domain dnsNames = append(dnsNames, commonName) - } else { //If there was no domain, we can't shorten anything. We must error. return nil, &apis.Condition{ diff --git a/pkg/reconciler/configuration/configuration.go b/pkg/reconciler/configuration/configuration.go index 3de2842e7e12..16350cd27a28 100644 --- a/pkg/reconciler/configuration/configuration.go +++ b/pkg/reconciler/configuration/configuration.go @@ -116,7 +116,6 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, config *v1.Configuration config.Status.MarkLatestCreatedFailed(lcr.Name, rc.GetMessage()) if !equality.Semantic.DeepEqual(beforeReady, config.Status.GetCondition(v1.ConfigurationConditionReady)) { - if lcr.Name == config.Status.LatestReadyRevisionName { recorder.Eventf(config, corev1.EventTypeWarning, "LatestReadyFailed", "Latest ready revision %q has failed", lcr.Name) diff --git a/pkg/reconciler/configuration/configuration_test.go b/pkg/reconciler/configuration/configuration_test.go index b50fabc9332d..48010b776e2c 100644 --- a/pkg/reconciler/configuration/configuration_test.go +++ b/pkg/reconciler/configuration/configuration_test.go @@ -578,7 +578,6 @@ func TestReconcile(t *testing.T) { return configreconciler.NewReconciler(ctx, logging.FromContext(ctx), servingclient.Get(ctx), listers.GetConfigurationLister(), controller.GetEventRecorder(ctx), r) - })) } diff --git a/pkg/reconciler/domainmapping/reconciler.go b/pkg/reconciler/domainmapping/reconciler.go index 3a9dbfc23f90..ef6c4d371cb7 100644 --- a/pkg/reconciler/domainmapping/reconciler.go +++ b/pkg/reconciler/domainmapping/reconciler.go @@ -263,7 +263,6 @@ func (r *Reconciler) reconcileIngress(ctx context.Context, dm *v1beta1.DomainMap } else if !equality.Semantic.DeepEqual(ingress.Spec, desired.Spec) || !equality.Semantic.DeepEqual(ingress.Annotations, desired.Annotations) || !equality.Semantic.DeepEqual(ingress.Labels, desired.Labels) { - // Don't modify the informers copy origin := ingress.DeepCopy() origin.Spec = desired.Spec diff --git a/pkg/reconciler/domainmapping/resources/ingress_test.go b/pkg/reconciler/domainmapping/resources/ingress_test.go index 759e090ba94e..c16ae882dbfe 100644 --- a/pkg/reconciler/domainmapping/resources/ingress_test.go +++ b/pkg/reconciler/domainmapping/resources/ingress_test.go @@ -241,5 +241,4 @@ func TestMakeIngress(t *testing.T) { } }) } - } diff --git a/pkg/reconciler/gc/gc.go b/pkg/reconciler/gc/gc.go index 58cc74778169..3c27c7625bee 100644 --- a/pkg/reconciler/gc/gc.go +++ b/pkg/reconciler/gc/gc.go @@ -89,7 +89,6 @@ func collect( if staleCount >= maxIdx { return nil // Reaches max revs to delete } - } nonStaleCount := count - staleCount diff --git a/pkg/reconciler/labeler/accessors.go b/pkg/reconciler/labeler/accessors.go index 36782ca84711..3320bfa6b2a4 100644 --- a/pkg/reconciler/labeler/accessors.go +++ b/pkg/reconciler/labeler/accessors.go @@ -99,7 +99,6 @@ func makeMetadataPatch( // markRoutingState updates the RoutingStateLabel and bumps the modified time annotation. func markRoutingState(acc kmeta.Accessor, clock clock.PassiveClock, diffLabels, diffAnn map[string]interface{}) { - hasRoute := acc.GetAnnotations()[serving.RoutesAnnotationKey] != "" if val, has := diffAnn[serving.RoutesAnnotationKey]; has { hasRoute = val != nil diff --git a/pkg/reconciler/revision/rate_limiter_test.go b/pkg/reconciler/revision/rate_limiter_test.go index 47aea9a27ed9..cf9cc1cc8a5b 100644 --- a/pkg/reconciler/revision/rate_limiter_test.go +++ b/pkg/reconciler/revision/rate_limiter_test.go @@ -63,7 +63,6 @@ func TestItemExponentialFailureRateLimiter(t *testing.T) { if e, a := 0*time.Millisecond, limiter.When("one"); e != a { t.Errorf("expected %v, got %v", e, a) } - } func TestItemExponentialFailureRateLimiterOverFlow(t *testing.T) { @@ -96,5 +95,4 @@ func TestItemExponentialFailureRateLimiterOverFlow(t *testing.T) { if e, a := 1000*time.Hour, limiter.When("overflow2"); e != a { t.Errorf("expected %v, got %v", e, a) } - } diff --git a/pkg/reconciler/revision/resolve_test.go b/pkg/reconciler/revision/resolve_test.go index ac1942bed380..61ca53680c50 100644 --- a/pkg/reconciler/revision/resolve_test.go +++ b/pkg/reconciler/revision/resolve_test.go @@ -492,7 +492,6 @@ func TestNewResolverTransport(t *testing.T) { } else if tc.wantErr && err == nil { t.Error("Didn't get an error when we wanted it") } else if err == nil { - // If we didn't get an error, make sure everything we wanted to happen happened. //nolint:staticcheck // ignore deprecation since we're not asserting system roots subjects := tr.TLSClientConfig.RootCAs.Subjects() @@ -540,7 +539,6 @@ func TestNewResolverTransport_TLSMinVersion(t *testing.T) { if tr, err := newResolverTransport(path, 100, 100); err != nil { t.Error("Got unexpected err:", err) } else if err == nil { - if diff := cmp.Diff(tc.expectedMinTLS, tr.TLSClientConfig.MinVersion); diff != "" { t.Errorf("expected min TLS version does not match: %s", diff) } diff --git a/pkg/reconciler/revision/resources/meta_test.go b/pkg/reconciler/revision/resources/meta_test.go index 8b03173fdb94..74dc746bda54 100644 --- a/pkg/reconciler/revision/resources/meta_test.go +++ b/pkg/reconciler/revision/resources/meta_test.go @@ -98,7 +98,6 @@ func TestMakeLabels(t *testing.T) { if diff := cmp.Diff(wantSelector, gotSelector); diff != "" { t.Error("makeLabels (-want, +got) =", diff) } - }) } } diff --git a/pkg/reconciler/revision/resources/queue.go b/pkg/reconciler/revision/resources/queue.go index 0483111f6517..1ef7f58e40b0 100644 --- a/pkg/reconciler/revision/resources/queue.go +++ b/pkg/reconciler/revision/resources/queue.go @@ -330,7 +330,6 @@ func makeQueueContainer(rev *v1.Revision, cfg *config.Config) (*corev1.Container if err != nil { return nil, fmt.Errorf("failed to serialize multiple readiness probes: %w", err) } - } else if userContainerReadinessProbe != nil { readinessProbeJSON, err = readiness.EncodeSingleProbe(userContainerReadinessProbe) if err != nil { diff --git a/pkg/reconciler/revision/revision_test.go b/pkg/reconciler/revision/revision_test.go index 83b9d5f3f144..3b8827e56a4c 100644 --- a/pkg/reconciler/revision/revision_test.go +++ b/pkg/reconciler/revision/revision_test.go @@ -84,7 +84,6 @@ func newTestController(t *testing.T, configs []*corev1.ConfigMap, opts ...reconc []controller.Informer, *controller.Impl, *configmap.ManualWatcher) { - ctx, cancel, informers := SetupFakeContextWithCancel(t) t.Cleanup(cancel) // cancel is reentrant, so if necessary callers can call it directly, if needed. configMapWatcher := &configmap.ManualWatcher{Namespace: system.Namespace()} diff --git a/pkg/reconciler/route/config/domain.go b/pkg/reconciler/route/config/domain.go index 2c67a9cbe116..134d75ceba2f 100644 --- a/pkg/reconciler/route/config/domain.go +++ b/pkg/reconciler/route/config/domain.go @@ -131,7 +131,6 @@ func (c *Domain) LookupDomainForLabels(labels map[string]string) string { return "svc." + network.GetClusterDomainName() } for k, v := range c.Domains { - // Ignore if selector doesn't match, or decrease the specificity. if !v.Selector.Matches(labels) || v.Selector.specificity() < specificity { continue diff --git a/pkg/reconciler/route/reconcile_resources.go b/pkg/reconciler/route/reconcile_resources.go index c028be31546c..30297d7ceb58 100644 --- a/pkg/reconciler/route/reconcile_resources.go +++ b/pkg/reconciler/route/reconcile_resources.go @@ -83,7 +83,6 @@ func (c *Reconciler) reconcileIngress( if !equality.Semantic.DeepEqual(ingress.Spec, desired.Spec) || !equality.Semantic.DeepEqual(ingress.Annotations, desired.Annotations) || !equality.Semantic.DeepEqual(ingress.Labels, desired.Labels) { - // It is notable that one reason for differences here may be defaulting. // When that is the case, the Update will end up being a nop because the // webhook will bring them into alignment and no new reconciliation will occur. @@ -253,7 +252,6 @@ func (c *Reconciler) updatePlaceholderServices(ctx context.Context, route *v1.Ro // else: // clusterIPs are immutable thus any transition requires a recreate // ie. "None" <=> "" (blank - request an IP) - } else /* types are the same and not clusterIP */ { canUpdate = true } diff --git a/pkg/reconciler/route/resources/ingress_test.go b/pkg/reconciler/route/resources/ingress_test.go index eb5ecd0d9ef2..6555d44ba45e 100644 --- a/pkg/reconciler/route/resources/ingress_test.go +++ b/pkg/reconciler/route/resources/ingress_test.go @@ -1340,7 +1340,6 @@ func TestMakeIngressACMEChallenges(t *testing.T) { if !cmp.Equal(expected, ci.Rules) { t.Error("Unexpected rules (-want, +got):", cmp.Diff(expected, ci.Rules)) } - } func TestMakeIngressFailToGenerateDomain(t *testing.T) { diff --git a/pkg/reconciler/route/route_test.go b/pkg/reconciler/route/route_test.go index 2caacb5257ce..933d1d236888 100644 --- a/pkg/reconciler/route/route_test.go +++ b/pkg/reconciler/route/route_test.go @@ -100,7 +100,6 @@ func newTestSetup(t *testing.T, opts ...reconcilerOption) ( ctrl *controller.Impl, configMapWatcher *configmap.ManualWatcher, cf context.CancelFunc) { - ctx, cf, informers = SetupFakeContextWithCancel(t) configMapWatcher = &configmap.ManualWatcher{Namespace: system.Namespace()} ctrl = newController(ctx, configMapWatcher, &clock.RealClock{}, opts...) diff --git a/pkg/reconciler/route/table_test.go b/pkg/reconciler/route/table_test.go index 71e7a10255d5..5db58ef998a6 100644 --- a/pkg/reconciler/route/table_test.go +++ b/pkg/reconciler/route/table_test.go @@ -3488,7 +3488,6 @@ func k8sEndpointsWithIngress(r *v1.Route, ing *netv1alpha1.Ingress) *corev1.Endp pair, _ := resources.MakeK8sService(ctx, r, "" /*targetName*/, ing, false /* is private */) return pair.Endpoints - } func simpleIngress(r *v1.Route, tc *traffic.Config, io ...IngressOption) *netv1alpha1.Ingress { diff --git a/pkg/reconciler/route/traffic/rollout_test.go b/pkg/reconciler/route/traffic/rollout_test.go index ebb0a6d08bdc..5296c5b18b4e 100644 --- a/pkg/reconciler/route/traffic/rollout_test.go +++ b/pkg/reconciler/route/traffic/rollout_test.go @@ -1126,7 +1126,6 @@ func TestObserveReady(t *testing.T) { t.Errorf("ObserveReady generated mismatched config: diff(-want,+got):\n%s", cmp.Diff(want, ro)) } - } func TestAdjustPercentage(t *testing.T) { @@ -1358,7 +1357,6 @@ func TestValidateFailures(t *testing.T) { } }) } - } func TestConfigDone(t *testing.T) { diff --git a/pkg/reconciler/serverlessservice/controller.go b/pkg/reconciler/serverlessservice/controller.go index f6b7530bcde1..ad1d63a9a88e 100644 --- a/pkg/reconciler/serverlessservice/controller.go +++ b/pkg/reconciler/serverlessservice/controller.go @@ -43,7 +43,6 @@ func NewController( ctx context.Context, cmw configmap.Watcher, ) *controller.Impl { - logger := logging.FromContext(ctx) serviceInformer := serviceinformer.Get(ctx) endpointsInformer := endpointsinformer.Get(ctx) diff --git a/pkg/reconciler/testing/v1/factory.go b/pkg/reconciler/testing/v1/factory.go index ba71455535f3..f73bb515ae97 100644 --- a/pkg/reconciler/testing/v1/factory.go +++ b/pkg/reconciler/testing/v1/factory.go @@ -202,5 +202,4 @@ func AssertTrackingObject(gvk schema.GroupVersionKind, namespace, name string) f t.Errorf("Object was not tracked - %s, Name=%s, Namespace=%s", gvk.String(), name, namespace) } - } diff --git a/pkg/resources/pods_test.go b/pkg/resources/pods_test.go index 2baa71388e0c..df0b0284b97c 100644 --- a/pkg/resources/pods_test.go +++ b/pkg/resources/pods_test.go @@ -99,7 +99,6 @@ func TestPodReadyUnreadyCount(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - kubeClient := fakek8s.NewSimpleClientset() podsClient := kubeinformers.NewSharedInformerFactory(kubeClient, 0).Core().V1().Pods() for _, p := range tc.pods { @@ -207,7 +206,6 @@ func TestPodIPsSortedByAge(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - kubeClient := fakek8s.NewSimpleClientset() podsClient := kubeinformers.NewSharedInformerFactory(kubeClient, 0).Core().V1().Pods() for _, p := range tc.pods { @@ -412,7 +410,6 @@ func TestPodIPsSplitByAge(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - kubeClient := fakek8s.NewSimpleClientset() podsClient := kubeinformers.NewSharedInformerFactory(kubeClient, 0).Core().V1().Pods() for _, p := range tc.pods { diff --git a/pkg/webhook/podspec_dryrun_test.go b/pkg/webhook/podspec_dryrun_test.go index 0e46f1f0ceb7..b4f0976899a3 100644 --- a/pkg/webhook/podspec_dryrun_test.go +++ b/pkg/webhook/podspec_dryrun_test.go @@ -132,7 +132,6 @@ func TestExtraServiceValidation(t *testing.T) { t.Errorf("Validate got='%v', want='%v'", got.Error(), test.want) } }) - } } @@ -217,7 +216,6 @@ func TestConfigurationValidation(t *testing.T) { t.Errorf("Validate got='%v', want='%v'", got.Error(), test.want) } }) - } } diff --git a/test/conformance/api/v1/configuration_test.go b/test/conformance/api/v1/configuration_test.go index 46e612e820e2..5d4fe9f8a8dd 100644 --- a/test/conformance/api/v1/configuration_test.go +++ b/test/conformance/api/v1/configuration_test.go @@ -70,7 +70,6 @@ func TestConfigurationGetAndList(t *testing.T) { if !configurationFound { t.Fatal("The Configuration that was previously created was not found by listing all Configurations.") } - } func TestUpdateConfigurationMetadata(t *testing.T) { diff --git a/test/conformance/api/v1/revision_test.go b/test/conformance/api/v1/revision_test.go index 5419c7996117..f875bbcb4532 100644 --- a/test/conformance/api/v1/revision_test.go +++ b/test/conformance/api/v1/revision_test.go @@ -66,5 +66,4 @@ func TestRevisionGetAndList(t *testing.T) { if !revisionFound { t.Fatal("The Revision that was previously created was not found by listing all Revisions.") } - } diff --git a/test/conformance/api/v1/service_test.go b/test/conformance/api/v1/service_test.go index 3c9c9833f674..c9f7609fd54e 100644 --- a/test/conformance/api/v1/service_test.go +++ b/test/conformance/api/v1/service_test.go @@ -85,7 +85,6 @@ func TestServiceCreateListAndDelete(t *testing.T) { if err := v1test.DeleteService(clients, names.Service); err != nil { t.Fatal("Error deleting Service") } - } // TestServiceCreateAndUpdate tests both Creation and Update paths for a service. The test performs a series of Update/Validate steps to ensure that diff --git a/test/conformance/api/v1/util.go b/test/conformance/api/v1/util.go index 67891885aa6d..6e068e1bb543 100644 --- a/test/conformance/api/v1/util.go +++ b/test/conformance/api/v1/util.go @@ -57,7 +57,6 @@ func checkForExpectedResponses(ctx context.Context, t testing.TB, clients *test. func validateDomains(t testing.TB, clients *test.Clients, serviceName string, baseExpected []string, tagExpectationPairs []tagExpectation) error { - service, err := clients.ServingClient.Services.Get(context.Background(), serviceName, metav1.GetOptions{}) if err != nil { return fmt.Errorf("could not query service traffic status: %w", err) diff --git a/test/conformance/runtime/cgroup_test.go b/test/conformance/runtime/cgroup_test.go index 12641a19b0b1..5e79debb146b 100644 --- a/test/conformance/runtime/cgroup_test.go +++ b/test/conformance/runtime/cgroup_test.go @@ -192,7 +192,6 @@ func TestShouldHaveCgroupReadOnly(t *testing.T) { t.Errorf("For cgroup %s cgroup.ReadOnly = %v, want: %v", cgroup.Name, *cgroup.ReadOnly, want) } } - } func createResources() corev1.ResourceRequirements { diff --git a/test/conformance/runtime/user_test.go b/test/conformance/runtime/user_test.go index 39b4a82318f7..bee39b553800 100644 --- a/test/conformance/runtime/user_test.go +++ b/test/conformance/runtime/user_test.go @@ -107,5 +107,4 @@ func TestShouldRunAsUserContainerDefault(t *testing.T) { if got, want := ri.Host.User.EUID, unprivilegedUserID; got != want { t.Errorf("euid = %d, want: %d", got, want) } - } diff --git a/test/conformance/runtime/util.go b/test/conformance/runtime/util.go index 0dcdbba3c47f..a65d77369a2d 100644 --- a/test/conformance/runtime/util.go +++ b/test/conformance/runtime/util.go @@ -37,7 +37,6 @@ func fetchRuntimeInfo( t *testing.T, clients *test.Clients, opts ...interface{}) (*test.ResourceNames, *types.RuntimeInfo, error) { - names := &test.ResourceNames{Image: test.Runtime} t.Helper() names.Service = test.ObjectNameForTest(t) @@ -85,7 +84,6 @@ func splitOpts(opts ...interface{}) ([]v1testing.ServiceOption, []interface{}, e default: return nil, nil, fmt.Errorf("invalid option type: %T", t) } - } return serviceOpts, reqOpts, nil } diff --git a/test/e2e/autoscale.go b/test/e2e/autoscale.go index 28616ab74bdc..668d3677033f 100644 --- a/test/e2e/autoscale.go +++ b/test/e2e/autoscale.go @@ -115,7 +115,6 @@ func generateTraffic( pacer vegeta.Pacer, stopChan chan struct{}, target vegeta.Target) error { - // The 0 duration means that the attack will only be controlled by the `Stop` function. results := attacker.Attack(vegeta.NewStaticTargeter(target), pacer, 0, "load-test") defer attacker.Stop() @@ -151,7 +150,6 @@ func generateTraffic( } func newVegetaHTTPClient(ctx *TestContext, url *url.URL) *http.Client { - vegetaTransportDefaults := func(transport *http.Transport) *http.Transport { transport.MaxIdleConnsPerHost = vegeta.DefaultConnections transport.MaxConnsPerHost = vegeta.DefaultMaxConnections diff --git a/test/e2e/externaldomaintls/config/dnssetup/main.go b/test/e2e/externaldomaintls/config/dnssetup/main.go index 5610b27ad51f..6ac3fd11b22c 100644 --- a/test/e2e/externaldomaintls/config/dnssetup/main.go +++ b/test/e2e/externaldomaintls/config/dnssetup/main.go @@ -109,7 +109,6 @@ func waitForDNSRecordVisible(record *config.DNSRecord) error { if !valid { return false, nil } - } return true, nil }); err != nil { diff --git a/test/e2e/http2_test.go b/test/e2e/http2_test.go index f06fb4295885..97efe887fc31 100644 --- a/test/e2e/http2_test.go +++ b/test/e2e/http2_test.go @@ -108,5 +108,4 @@ func TestHelloHTTP2WithEmptyPortName(t *testing.T) { ); err != nil { t.Fatalf("The endpoint %s for Route %s didn't serve the expected status code %v: %v", url, names.Route, http.StatusUpgradeRequired, err) } - } diff --git a/test/e2e/readiness_test.go b/test/e2e/readiness_test.go index b6a356a051a0..62c7ce18fa42 100644 --- a/test/e2e/readiness_test.go +++ b/test/e2e/readiness_test.go @@ -87,7 +87,6 @@ func TestReadinessAlternatePort(t *testing.T) { ); err != nil { t.Fatalf("The endpoint %s for Route %s didn't serve the expected text %q: %v", url, names.Route, test.HelloWorldText, err) } - } func TestReadinessPathAndQuery(t *testing.T) { diff --git a/test/e2e/websocket_test.go b/test/e2e/websocket_test.go index f4c1e3da2332..26a9e57f63f3 100644 --- a/test/e2e/websocket_test.go +++ b/test/e2e/websocket_test.go @@ -327,7 +327,6 @@ func TestWebSocketWithTimeout(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { - names := test.ResourceNames{ Service: test.ObjectNameForTest(t), Image: wsServerTestImageName, From 384425547d551b5fc5219768757e64edabd7a6ac Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:06:54 -0500 Subject: [PATCH 03/35] fix usestdlibvars linter --- pkg/activator/handler/main_test.go | 2 +- pkg/http/handler/timeout_test.go | 2 +- pkg/queue/readiness/probe_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/activator/handler/main_test.go b/pkg/activator/handler/main_test.go index c1a850c760d3..b21a98ca0480 100644 --- a/pkg/activator/handler/main_test.go +++ b/pkg/activator/handler/main_test.go @@ -238,7 +238,7 @@ func TestActivatorChainHandlerWithFullDuplex(t *testing.T) { func send(client *http.Client, url string, body []byte, rHost string) error { r := bytes.NewBuffer(body) - req, err := http.NewRequest("POST", url, r) + req, err := http.NewRequest(http.MethodPost, url, r) if rHost != "" { req.Host = rHost diff --git a/pkg/http/handler/timeout_test.go b/pkg/http/handler/timeout_test.go index fb6068cf1e7f..55109ab900b0 100644 --- a/pkg/http/handler/timeout_test.go +++ b/pkg/http/handler/timeout_test.go @@ -403,7 +403,7 @@ func TestTimeoutHandler(t *testing.T) { func BenchmarkTimeoutHandler(b *testing.B) { writes := [][]byte{[]byte("this"), []byte("is"), []byte("a"), []byte("test")} baseHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) for _, write := range writes { w.Write(write) } diff --git a/pkg/queue/readiness/probe_test.go b/pkg/queue/readiness/probe_test.go index c191d6a01427..1d5c385fe9f0 100644 --- a/pkg/queue/readiness/probe_test.go +++ b/pkg/queue/readiness/probe_test.go @@ -116,7 +116,7 @@ func TestAggressiveFailureNotLoggedOnSuccess(t *testing.T) { // Fail a few times before succeeding to ensure no failures are // misleadingly logged as long as we eventually succeed. if polled.Inc() > 3 { - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) return } From cc2fd646856fdf476a92acdbca1cd0ffe2cfc4bb Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:09:33 -0500 Subject: [PATCH 04/35] fix lint wastedassign --- pkg/activator/net/throttler.go | 2 +- pkg/reconciler/autoscaling/resources/target.go | 3 +-- pkg/reconciler/route/reconcile_resources.go | 1 - 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/pkg/activator/net/throttler.go b/pkg/activator/net/throttler.go index df6793f3e02a..39a2ccd44eb7 100644 --- a/pkg/activator/net/throttler.go +++ b/pkg/activator/net/throttler.go @@ -243,7 +243,7 @@ func (rt *revisionThrottler) try(ctx context.Context, function func(string) erro } func (rt *revisionThrottler) calculateCapacity(backendCount, numTrackers, activatorCount int) int { - targetCapacity := 0 + var targetCapacity int if numTrackers > 0 { // Capacity is computed based off of number of trackers, // when using pod direct routing. diff --git a/pkg/reconciler/autoscaling/resources/target.go b/pkg/reconciler/autoscaling/resources/target.go index 658cbe4401ed..b0efb16988bc 100644 --- a/pkg/reconciler/autoscaling/resources/target.go +++ b/pkg/reconciler/autoscaling/resources/target.go @@ -29,8 +29,7 @@ import ( // `target` is the target value of scaling metric that we autoscaler will aim for; // `total` is the maximum possible value of scaling metric that is permitted on the pod. func ResolveMetricTarget(pa *autoscalingv1alpha1.PodAutoscaler, config *autoscalerconfig.Config) (target, total float64) { - tu := 0. - + var tu float64 switch pa.Metric() { case autoscaling.RPS: total = config.RPSTargetDefault diff --git a/pkg/reconciler/route/reconcile_resources.go b/pkg/reconciler/route/reconcile_resources.go index 30297d7ceb58..0919f2f0f4b2 100644 --- a/pkg/reconciler/route/reconcile_resources.go +++ b/pkg/reconciler/route/reconcile_resources.go @@ -342,7 +342,6 @@ func (c *Reconciler) reconcileRollout( return curRO } // Get the current rollout state as described by the traffic. - nextStepTime := int64(0) logger := logging.FromContext(ctx).Desugar().With( zap.Int("durationSecs", rd)) logger.Debug("Rollout is enabled. Stepping from previous state.") From 8cc3257a967b8b210c6483e276effb801ef31c9d Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:17:23 -0500 Subject: [PATCH 05/35] address unparam linter - container concurrency wasn't being used when assigning pods to activator --- pkg/activator/net/throttler.go | 4 +-- pkg/activator/net/throttler_test.go | 38 ++++++----------------------- 2 files changed, 10 insertions(+), 32 deletions(-) diff --git a/pkg/activator/net/throttler.go b/pkg/activator/net/throttler.go index 39a2ccd44eb7..291292df4c53 100644 --- a/pkg/activator/net/throttler.go +++ b/pkg/activator/net/throttler.go @@ -309,7 +309,7 @@ func (rt *revisionThrottler) updateCapacity(backendCount int) { assigned := rt.podTrackers if rt.containerConcurrency > 0 { rt.resetTrackers() - assigned = assignSlice(rt.podTrackers, ai, ac, rt.containerConcurrency) + assigned = assignSlice(rt.podTrackers, ai, ac) } rt.logger.Debugf("Trackers %d/%d: assignment: %v", ai, ac, assigned) // The actual write out of the assigned trackers has to be under lock. @@ -375,7 +375,7 @@ func pickIndices(numTrackers, selfIndex, numActivators int) (beginIndex, endInde // for this Activator instance. This only matters in case of direct // to pod IP routing, and is irrelevant, when ClusterIP is used. // assignSlice should receive podTrackers sorted by address. -func assignSlice(trackers []*podTracker, selfIndex, numActivators, cc int) []*podTracker { +func assignSlice(trackers []*podTracker, selfIndex, numActivators int) []*podTracker { // When we're unassigned, doesn't matter what we return. lt := len(trackers) if selfIndex == -1 || lt <= 1 { diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index ded1a9363d56..e95a8b68da06 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -1156,43 +1156,43 @@ func TestAssignSlice(t *testing.T) { dest: "3", }} t.Run("notrackers", func(t *testing.T) { - got := assignSlice([]*podTracker{}, 0 /*selfIdx*/, 1 /*numAct*/, 42 /*cc*/) + got := assignSlice([]*podTracker{}, 0 /*selfIdx*/, 1 /*numAct*/) if !cmp.Equal(got, []*podTracker{}, opt) { t.Errorf("Got=%v, want: %v, diff: %s", got, trackers, cmp.Diff([]*podTracker{}, got, opt)) } }) t.Run("idx=1, na=1", func(t *testing.T) { - got := assignSlice(trackers, 1, 1, 1982) + got := assignSlice(trackers, 1, 1) if !cmp.Equal(got, trackers, opt) { t.Errorf("Got=%v, want: %v, diff: %s", got, trackers, cmp.Diff(trackers, got, opt)) } }) t.Run("idx=-1", func(t *testing.T) { - got := assignSlice(trackers, -1, 1, 1982) + got := assignSlice(trackers, -1, 1) if !cmp.Equal(got, trackers, opt) { t.Errorf("Got=%v, want: %v, diff: %s", got, trackers, cmp.Diff(trackers, got, opt)) } }) - t.Run("idx=1", func(t *testing.T) { + t.Run("idx=1 na=3", func(t *testing.T) { cp := append(trackers[:0:0], trackers...) - got := assignSlice(cp, 1, 3, 1984) + got := assignSlice(cp, 1, 3) if !cmp.Equal(got, trackers[1:2], opt) { t.Errorf("Got=%v, want: %v; diff: %s", got, trackers[0:1], cmp.Diff(trackers[1:2], got, opt)) } }) t.Run("len=1", func(t *testing.T) { - got := assignSlice(trackers[0:1], 1, 3, 1988) + got := assignSlice(trackers[0:1], 1, 3) if !cmp.Equal(got, trackers[0:1], opt) { t.Errorf("Got=%v, want: %v; diff: %s", got, trackers[0:1], cmp.Diff(trackers[0:1], got, opt)) } }) - t.Run("idx=1, cc=5", func(t *testing.T) { + t.Run("idx=1, breaker", func(t *testing.T) { trackers := []*podTracker{{ dest: "1", b: queue.NewBreaker(testBreakerParams), @@ -1204,29 +1204,7 @@ func TestAssignSlice(t *testing.T) { b: queue.NewBreaker(testBreakerParams), }} cp := append(trackers[:0:0], trackers...) - got := assignSlice(cp, 1, 2, 5) - want := trackers[1:2] - if !cmp.Equal(got, want, opt) { - t.Errorf("Got=%v, want: %v; diff: %s", got, want, - cmp.Diff(want, got, opt)) - } - if got, want := got[0].b.Capacity(), 0; got != want { - t.Errorf("Capacity for the tail pod = %d, want: %d", got, want) - } - }) - t.Run("idx=1, cc=6", func(t *testing.T) { - trackers := []*podTracker{{ - dest: "1", - b: queue.NewBreaker(testBreakerParams), - }, { - dest: "2", - b: queue.NewBreaker(testBreakerParams), - }, { - dest: "3", - b: queue.NewBreaker(testBreakerParams), - }} - cp := append(trackers[:0:0], trackers...) - got := assignSlice(cp, 1, 2, 6) + got := assignSlice(cp, 1, 2) want := trackers[1:2] if !cmp.Equal(got, want, opt) { t.Errorf("Got=%v, want: %v; diff: %s", got, want, From e0cc35f462c92a8296c10dda90e2623931e013bc Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:19:25 -0500 Subject: [PATCH 06/35] fix tenv linter --- pkg/autoscaler/statforwarder/forwarder_test.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/pkg/autoscaler/statforwarder/forwarder_test.go b/pkg/autoscaler/statforwarder/forwarder_test.go index 22942c544fa2..6defcd279ce6 100644 --- a/pkg/autoscaler/statforwarder/forwarder_test.go +++ b/pkg/autoscaler/statforwarder/forwarder_test.go @@ -20,7 +20,6 @@ import ( "context" "errors" "fmt" - "os" "testing" "time" @@ -99,10 +98,10 @@ func TestForwarderReconcile(t *testing.T) { t.Fatal("Failed to start informers:", err) } - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) f1 := New(ctx, testBs) must(t, LeaseBasedProcessor(ctx, f1, noOp)) - os.Setenv("POD_IP", testIP2) + t.Setenv("POD_IP", testIP2) f2 := New(ctx, testBs) must(t, LeaseBasedProcessor(ctx, f2, noOp)) @@ -195,7 +194,7 @@ func TestForwarderRetryOnSvcCreationFailure(t *testing.T) { waitInformers() }() - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) must(t, LeaseBasedProcessor(ctx, New(ctx, testBs), noOp)) svcCreation := 0 @@ -236,7 +235,7 @@ func TestForwarderRetryOnEndpointsCreationFailure(t *testing.T) { waitInformers() }() - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) must(t, LeaseBasedProcessor(ctx, New(ctx, testBs), noOp)) endpointsCreation := 0 @@ -278,7 +277,7 @@ func TestForwarderRetryOnEndpointsUpdateFailure(t *testing.T) { waitInformers() }() - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) must(t, LeaseBasedProcessor(ctx, New(ctx, testBs), noOp)) endpointsUpdate := 0 @@ -327,7 +326,7 @@ func TestForwarderSkipReconciling(t *testing.T) { waitInformers() }() - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) must(t, LeaseBasedProcessor(ctx, New(ctx, testBs), noOp)) svcCreated := make(chan struct{}) @@ -422,7 +421,7 @@ func TestProcess(t *testing.T) { acceptCount++ acceptCh <- acceptCount } - os.Setenv("POD_IP", testIP1) + t.Setenv("POD_IP", testIP1) f := New(ctx, hash.NewBucketSet(sets.New(bucket1, bucket2))) must(t, LeaseBasedProcessor(ctx, f, accept)) From 3cb7a719e1a4a118a0838aefc67ee0dfc073c7c2 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:22:38 -0500 Subject: [PATCH 07/35] fix stylecheck linter --- pkg/apis/serving/v1/configuration_conversion.go | 4 ++++ pkg/apis/serving/v1/revision_conversion.go | 4 ++++ pkg/apis/serving/v1/route_conversion.go | 4 ++++ pkg/apis/serving/v1/service_conversion.go | 4 ++++ 4 files changed, 16 insertions(+) diff --git a/pkg/apis/serving/v1/configuration_conversion.go b/pkg/apis/serving/v1/configuration_conversion.go index 6f01637ffa93..647e4fb18d7c 100644 --- a/pkg/apis/serving/v1/configuration_conversion.go +++ b/pkg/apis/serving/v1/configuration_conversion.go @@ -24,11 +24,15 @@ import ( ) // ConvertTo implements apis.Convertible +// +//nolint:stylecheck func (source *Configuration) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible +// +//nolint:stylecheck func (sink *Configuration) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/revision_conversion.go b/pkg/apis/serving/v1/revision_conversion.go index 053b7915625a..0cd88b03359a 100644 --- a/pkg/apis/serving/v1/revision_conversion.go +++ b/pkg/apis/serving/v1/revision_conversion.go @@ -24,11 +24,15 @@ import ( ) // ConvertTo implements apis.Convertible +// +//nolint:stylecheck func (source *Revision) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible +// +//nolint:stylecheck func (sink *Revision) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/route_conversion.go b/pkg/apis/serving/v1/route_conversion.go index 50682d0a8d87..b2dcab8b7a76 100644 --- a/pkg/apis/serving/v1/route_conversion.go +++ b/pkg/apis/serving/v1/route_conversion.go @@ -24,11 +24,15 @@ import ( ) // ConvertTo implements apis.Convertible +// +//nolint:stylecheck func (source *Route) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible +// +//nolint:stylecheck func (sink *Route) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/service_conversion.go b/pkg/apis/serving/v1/service_conversion.go index 6f427dc1152c..a77e294c23f9 100644 --- a/pkg/apis/serving/v1/service_conversion.go +++ b/pkg/apis/serving/v1/service_conversion.go @@ -24,11 +24,15 @@ import ( ) // ConvertTo implements apis.Convertible +// +//nolint:stylecheck func (source *Service) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible +// +//nolint:stylecheck func (sink *Service) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } From 65009c65f92f201d5e76f6b8fd89c387770d874a Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Fri, 10 Jan 2025 23:59:09 -0500 Subject: [PATCH 08/35] fix staticheck linter --- pkg/queue/health/probe.go | 3 +-- pkg/reconciler/revision/background.go | 4 ++-- pkg/reconciler/revision/background_test.go | 4 ++-- pkg/reconciler/revision/controller.go | 6 +++--- pkg/reconciler/revision/rate_limiter.go | 4 ++-- test/e2e/grpc_test.go | 2 +- test/test_images/autoscale/autoscale.go | 6 ++---- test/test_images/singlethreaded/main.go | 2 +- 8 files changed, 14 insertions(+), 17 deletions(-) diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 1ca0c556b639..5394e00a7f90 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -237,7 +237,6 @@ func GRPCProbe(config GRPCProbeConfigOptions) error { opts := []grpc.DialOption{ grpc.WithUserAgent(netheader.KubeProbeUAPrefix + config.KubeMajor + "/" + config.KubeMinor), - grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()), // credentials are currently not supported grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { return dialer.DialContext(ctx, "tcp", addr) @@ -249,7 +248,7 @@ func GRPCProbe(config GRPCProbeConfigOptions) error { defer cancel() addr := net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", config.Port)) - conn, err := grpc.DialContext(ctx, addr, opts...) + conn, err := grpc.NewClient(addr, opts...) if err != nil { if errors.Is(err, context.DeadlineExceeded) { diff --git a/pkg/reconciler/revision/background.go b/pkg/reconciler/revision/background.go index 0bef35cba5ff..b5d03a16746b 100644 --- a/pkg/reconciler/revision/background.go +++ b/pkg/reconciler/revision/background.go @@ -42,7 +42,7 @@ type backgroundResolver struct { resolver imageResolver enqueue func(types.NamespacedName) - queue workqueue.RateLimitingInterface + queue workqueue.TypedRateLimitingInterface[any] mu sync.RWMutex results map[types.NamespacedName]*resolveResult @@ -78,7 +78,7 @@ type workItem struct { image string } -func newBackgroundResolver(logger *zap.SugaredLogger, resolver imageResolver, queue workqueue.RateLimitingInterface, enqueue func(types.NamespacedName)) *backgroundResolver { +func newBackgroundResolver(logger *zap.SugaredLogger, resolver imageResolver, queue workqueue.TypedRateLimitingInterface[any], enqueue func(types.NamespacedName)) *backgroundResolver { r := &backgroundResolver{ logger: logger, diff --git a/pkg/reconciler/revision/background_test.go b/pkg/reconciler/revision/background_test.go index 8310b36a9876..1e892966810f 100644 --- a/pkg/reconciler/revision/background_test.go +++ b/pkg/reconciler/revision/background_test.go @@ -148,7 +148,7 @@ func TestResolveInBackground(t *testing.T) { } logger := logtesting.TestLogger(t) - subject := newBackgroundResolver(logger, tt.resolver, workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), cb) + subject := newBackgroundResolver(logger, tt.resolver, workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[any]()), cb) stop := make(chan struct{}) done := subject.Start(stop, 10) @@ -210,7 +210,7 @@ func TestRateLimitPerItem(t *testing.T) { } baseDelay := 50 * time.Millisecond - queue := workqueue.NewRateLimitingQueue(newItemExponentialFailureRateLimiter(baseDelay, 5*time.Second)) + queue := workqueue.NewTypedRateLimitingQueue(newItemExponentialFailureRateLimiter(baseDelay, 5*time.Second)) enqueue := make(chan struct{}) subject := newBackgroundResolver(logger, resolver, queue, func(types.NamespacedName) { diff --git a/pkg/reconciler/revision/controller.go b/pkg/reconciler/revision/controller.go index 614707b6d6ed..70d52583671a 100644 --- a/pkg/reconciler/revision/controller.go +++ b/pkg/reconciler/revision/controller.go @@ -120,11 +120,11 @@ func newControllerWithOptions( userAgent := fmt.Sprintf("knative/%s (serving)", changeset.Get()) - digestResolveQueue := workqueue.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter( + digestResolveQueue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.NewTypedMaxOfRateLimiter( newItemExponentialFailureRateLimiter(1*time.Second, 1000*time.Second), // 10 qps, 100 bucket size. This is only for retry speed and its only the overall factor (not per item) - &workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)}, - ), "digests") + &workqueue.TypedBucketRateLimiter[any]{Limiter: rate.NewLimiter(rate.Limit(10), 100)}, + ), workqueue.TypedRateLimitingQueueConfig[any]{Name: "digests"}) resolver := newBackgroundResolver(logger, &digestResolver{client: kubeclient.Get(ctx), transport: transport, userAgent: userAgent}, digestResolveQueue, impl.EnqueueKey) resolver.Start(ctx.Done(), digestResolutionWorkers) diff --git a/pkg/reconciler/revision/rate_limiter.go b/pkg/reconciler/revision/rate_limiter.go index b4b1c3f31ca9..6ed28b66a400 100644 --- a/pkg/reconciler/revision/rate_limiter.go +++ b/pkg/reconciler/revision/rate_limiter.go @@ -39,9 +39,9 @@ type itemExponentialFailureRateLimiter struct { maxDelay time.Duration } -var _ workqueue.RateLimiter = &itemExponentialFailureRateLimiter{} +var _ workqueue.TypedRateLimiter[any] = &itemExponentialFailureRateLimiter{} -func newItemExponentialFailureRateLimiter(baseDelay time.Duration, maxDelay time.Duration) workqueue.RateLimiter { +func newItemExponentialFailureRateLimiter(baseDelay time.Duration, maxDelay time.Duration) workqueue.TypedRateLimiter[any] { return &itemExponentialFailureRateLimiter{ failures: map[interface{}]int{}, baseDelay: baseDelay, diff --git a/test/e2e/grpc_test.go b/test/e2e/grpc_test.go index bd67d62ef026..d25a686c83ce 100644 --- a/test/e2e/grpc_test.go +++ b/test/e2e/grpc_test.go @@ -90,7 +90,7 @@ func dial(ctx *TestContext, host, domain string) (*grpc.ClientConn, error) { creds = credentials.NewTLS(tlsConfig) } - return grpc.Dial( + return grpc.NewClient( host, grpc.WithAuthority(domain), grpc.WithTransportCredentials(creds), diff --git a/test/test_images/autoscale/autoscale.go b/test/test_images/autoscale/autoscale.go index c1e1769445da..da0c78e78473 100644 --- a/test/test_images/autoscale/autoscale.go +++ b/test/test_images/autoscale/autoscale.go @@ -29,9 +29,7 @@ import ( "knative.dev/serving/test" ) -func init() { - rand.Seed(time.Now().UnixNano()) -} +var mathrand = rand.New(rand.NewSource(time.Now().UnixNano())) // Algorithm from https://stackoverflow.com/a/21854246 @@ -105,7 +103,7 @@ func sleep(d time.Duration) string { func randSleep(randSleepTimeMean time.Duration, randSleepTimeStdDev int) string { start := time.Now() - randRes := time.Duration(rand.NormFloat64()*float64(randSleepTimeStdDev))*time.Millisecond + randSleepTimeMean + randRes := time.Duration(mathrand.NormFloat64()*float64(randSleepTimeStdDev))*time.Millisecond + randSleepTimeMean time.Sleep(randRes) return fmt.Sprintf("Randomly slept for %v.\n", time.Since(start)) } diff --git a/test/test_images/singlethreaded/main.go b/test/test_images/singlethreaded/main.go index 9ce22468682d..2ed3b258a559 100644 --- a/test/test_images/singlethreaded/main.go +++ b/test/test_images/singlethreaded/main.go @@ -30,7 +30,7 @@ import ( var isLocked = atomic.NewBool(false) func handler(w http.ResponseWriter, r *http.Request) { - if isLocked.CAS(false /*was unlocked*/, true /*lock*/) { + if isLocked.CompareAndSwap(false /*was unlocked*/, true /*lock*/) { defer isLocked.Store(false) time.Sleep(500 * time.Millisecond) fmt.Fprintf(w, "One at a time") From b0ce4af6865ee26f2e42554d4b75be20e9f0d805 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 00:01:14 -0500 Subject: [PATCH 09/35] fix perfsprint linter --- cmd/schema-tweak/main.go | 2 +- cmd/schema-tweak/overrides.go | 7 +++---- pkg/activator/handler/context_handler_test.go | 4 ++-- pkg/activator/handler/healthz_handler_test.go | 5 ++--- pkg/activator/handler/probe_handler_test.go | 5 ++--- pkg/apis/autoscaling/annotation_validation.go | 4 ++-- pkg/apis/serving/v1/revision_validation_test.go | 2 +- pkg/gc/config.go | 3 ++- pkg/networking/util.go | 4 ++-- pkg/queue/health/probe.go | 3 ++- pkg/queue/readiness/probe.go | 5 +++-- pkg/reconciler/certificate/certificate.go | 3 ++- pkg/reconciler/certificate/certificate_test.go | 4 ++-- .../resources/cert_manager_certificate_test.go | 11 ++++++----- pkg/reconciler/configuration/resources/revision.go | 3 ++- pkg/reconciler/revision/resolve_test.go | 3 ++- pkg/reconciler/revision/revision_test.go | 4 ++-- test/conformance/api/v1/revision_timeout_test.go | 5 +++-- test/conformance/runtime/cgroup_test.go | 11 ++++++----- test/e2e/autoscale_hpa_test.go | 3 +-- test/e2e/destroypod_test.go | 3 ++- test/e2e/externaldomaintls/util_test.go | 3 ++- .../e2e/systeminternaltls/system_internal_tls_test.go | 5 ++--- test/e2e/timeout_test.go | 5 +++-- test/e2e/websocket.go | 2 +- 25 files changed, 58 insertions(+), 51 deletions(-) diff --git a/cmd/schema-tweak/main.go b/cmd/schema-tweak/main.go index 43b06f71ec4f..8839fea41723 100644 --- a/cmd/schema-tweak/main.go +++ b/cmd/schema-tweak/main.go @@ -147,7 +147,7 @@ func updateFeatureFlags(node *yaml.Node, features []flagField) { } func updateFeatureFlagProperty(root *yaml.Node, f flagField) { - desc := fmt.Sprintf("This is accessible behind a feature flag - %s", f.flag) + desc := "This is accessible behind a feature flag - " + f.flag setString(root, "description", desc) diff --git a/cmd/schema-tweak/overrides.go b/cmd/schema-tweak/overrides.go index 3970da201f97..48b75287bddd 100644 --- a/cmd/schema-tweak/overrides.go +++ b/cmd/schema-tweak/overrides.go @@ -153,9 +153,8 @@ func revSpecOverrides(prefixPath string) []entry { "drop", ), }, { - path: "containers.securityContext.capabilities.add", - description: fmt.Sprintf("This is accessible behind a feature flag - %s", - config.FeatureContainerSpecAddCapabilities), + path: "containers.securityContext.capabilities.add", + description: "This is accessible behind a feature flag - " + config.FeatureContainerSpecAddCapabilities, }, { path: "containers.resources", allowedFields: sets.New( @@ -345,7 +344,7 @@ func revSpecOverrides(prefixPath string) []entry { for _, probe := range probes { entries = append(entries, entry{ - path: fmt.Sprintf("containers.%s", probe), + path: "containers." + probe, allowedFields: sets.New( "initialDelaySeconds", "timeoutSeconds", diff --git a/pkg/activator/handler/context_handler_test.go b/pkg/activator/handler/context_handler_test.go index bfb30b4dbc43..52a73467433f 100644 --- a/pkg/activator/handler/context_handler_test.go +++ b/pkg/activator/handler/context_handler_test.go @@ -135,13 +135,13 @@ func BenchmarkContextHandler(b *testing.B) { for _, test := range tests { req.Header.Set(activator.RevisionHeaderName, test.revisionName) - b.Run(fmt.Sprintf("%s-sequential", test.label), func(b *testing.B) { + b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() for j := 0; j < b.N; j++ { handler.ServeHTTP(resp, req) } }) - b.Run(fmt.Sprintf("%s-parallel", test.label), func(b *testing.B) { + b.Run(test.label+"-parallel", func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { resp := httptest.NewRecorder() for pb.Next() { diff --git a/pkg/activator/handler/healthz_handler_test.go b/pkg/activator/handler/healthz_handler_test.go index 85b47add82c4..b943d5fc4bea 100644 --- a/pkg/activator/handler/healthz_handler_test.go +++ b/pkg/activator/handler/healthz_handler_test.go @@ -18,7 +18,6 @@ package handler import ( "errors" - "fmt" "net/http" "net/http/httptest" "testing" @@ -107,14 +106,14 @@ func BenchmarkHealthHandler(b *testing.B) { for _, test := range tests { handler := HealthHandler{HealthCheck: test.check, NextHandler: baseHandler, Logger: logger} req.Header = test.headers - b.Run(fmt.Sprintf("%s-sequential", test.label), func(b *testing.B) { + b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() for j := 0; j < b.N; j++ { handler.ServeHTTP(resp, req) } }) - b.Run(fmt.Sprintf("%s-parallel", test.label), func(b *testing.B) { + b.Run(test.label+"-parallel", func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { resp := httptest.NewRecorder() for pb.Next() { diff --git a/pkg/activator/handler/probe_handler_test.go b/pkg/activator/handler/probe_handler_test.go index c73ff9735f5a..b1138d1fa982 100644 --- a/pkg/activator/handler/probe_handler_test.go +++ b/pkg/activator/handler/probe_handler_test.go @@ -17,7 +17,6 @@ limitations under the License. package handler import ( - "fmt" "net/http" "net/http/httptest" "testing" @@ -126,14 +125,14 @@ func BenchmarkProbeHandler(b *testing.B) { for _, test := range tests { req.Header = test.headers - b.Run(fmt.Sprintf("%s-sequential", test.label), func(b *testing.B) { + b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() for j := 0; j < b.N; j++ { handler.ServeHTTP(resp, req) } }) - b.Run(fmt.Sprintf("%s-parallel", test.label), func(b *testing.B) { + b.Run(test.label+"-parallel", func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { resp := httptest.NewRecorder() for pb.Next() { diff --git a/pkg/apis/autoscaling/annotation_validation.go b/pkg/apis/autoscaling/annotation_validation.go index 95076a603c56..54d5f3c113a4 100644 --- a/pkg/apis/autoscaling/annotation_validation.go +++ b/pkg/apis/autoscaling/annotation_validation.go @@ -268,9 +268,9 @@ func validateInitialScale(config *autoscalerconfig.Config, m map[string]string) if err != nil { return apis.ErrInvalidValue(v, k) } else if initScaleInt < 0 { - return apis.ErrInvalidValue(v, fmt.Sprintf("%s must be greater than 0", k)) + return apis.ErrInvalidValue(v, k+" must be greater than 0") } else if !config.AllowZeroInitialScale && initScaleInt == 0 { - return apis.ErrInvalidValue(v, fmt.Sprintf("%s=0 not allowed by cluster", k)) + return apis.ErrInvalidValue(v, k+"=0 not allowed by cluster") } } return nil diff --git a/pkg/apis/serving/v1/revision_validation_test.go b/pkg/apis/serving/v1/revision_validation_test.go index ba0769049f55..93ba8ce164f7 100644 --- a/pkg/apis/serving/v1/revision_validation_test.go +++ b/pkg/apis/serving/v1/revision_validation_test.go @@ -989,7 +989,7 @@ func TestRevisionTemplateSpecValidation(t *testing.T) { }, want: (&apis.FieldError{ Message: "invalid value: 0", - Paths: []string{fmt.Sprintf("%s=0 not allowed by cluster", autoscaling.InitialScaleAnnotationKey)}, + Paths: []string{autoscaling.InitialScaleAnnotationKey + "=0 not allowed by cluster"}, }).ViaField("metadata.annotations"), }, { name: "Valid initial scale when cluster allows zero", diff --git a/pkg/gc/config.go b/pkg/gc/config.go index 4218e6fc6ced..dc4c3b849633 100644 --- a/pkg/gc/config.go +++ b/pkg/gc/config.go @@ -18,6 +18,7 @@ package gc import ( "context" + "errors" "fmt" "strconv" "strings" @@ -128,7 +129,7 @@ func parseDisabledOrDuration(val string, toSet *time.Duration) error { return err } if parsed < 0 { - return fmt.Errorf("must be non-negative") + return errors.New("must be non-negative") } *toSet = parsed } diff --git a/pkg/networking/util.go b/pkg/networking/util.go index 643fb1b060a5..7e1d28c851c1 100644 --- a/pkg/networking/util.go +++ b/pkg/networking/util.go @@ -2,7 +2,7 @@ package networking import ( "context" - "fmt" + "errors" "strings" "knative.dev/networking/pkg/apis/networking" @@ -22,7 +22,7 @@ func GetHTTPOption(ctx context.Context, networkConfig *netcfg.Config, annotation case netcfg.HTTPRedirected: return netv1alpha1.HTTPOptionRedirected, nil default: - return "", fmt.Errorf("incorrect http-protocol annotation: " + protocol) + return "", errors.New("incorrect http-protocol annotation: " + protocol) } } diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 5394e00a7f90..569154e1d012 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -24,6 +24,7 @@ import ( "net" "net/http" "net/url" + "strconv" "syscall" "time" @@ -247,7 +248,7 @@ func GRPCProbe(config GRPCProbeConfigOptions) error { defer cancel() - addr := net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", config.Port)) + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(int(config.Port))) conn, err := grpc.NewClient(addr, opts...) if err != nil { diff --git a/pkg/queue/readiness/probe.go b/pkg/queue/readiness/probe.go index b5b09636ccca..5d4566caba35 100644 --- a/pkg/queue/readiness/probe.go +++ b/pkg/queue/readiness/probe.go @@ -18,6 +18,7 @@ package readiness import ( "context" + "errors" "fmt" "io" "os" @@ -164,9 +165,9 @@ func (p *Probe) probeContainerImpl() bool { case innerProbe.Exec != nil: // Should never be reachable. Exec probes to be translated to // TCP probes when container is built. - return fmt.Errorf("exec probe not supported") + return errors.New("exec probe not supported") default: - return fmt.Errorf("no probe found") + return errors.New("no probe found") } }) } diff --git a/pkg/reconciler/certificate/certificate.go b/pkg/reconciler/certificate/certificate.go index c0c15a71bde7..5ae2c34ed2e0 100644 --- a/pkg/reconciler/certificate/certificate.go +++ b/pkg/reconciler/certificate/certificate.go @@ -18,6 +18,7 @@ package certificate import ( "context" + "errors" "fmt" "hash/adler32" "strconv" @@ -105,7 +106,7 @@ func (c *Reconciler) reconcile(ctx context.Context, knCert *v1alpha1.Certificate cmCert, errCondition := resources.MakeCertManagerCertificate(cmConfig, knCert) if errCondition != nil { knCert.Status.MarkFailed(errCondition.Reason, errCondition.Message) - return fmt.Errorf(errCondition.Message) + return errors.New(errCondition.Message) } cmCert, err := c.reconcileCMCertificate(ctx, knCert, cmCert) diff --git a/pkg/reconciler/certificate/certificate_test.go b/pkg/reconciler/certificate/certificate_test.go index f43b5ff01480..99b0d686e02d 100644 --- a/pkg/reconciler/certificate/certificate_test.go +++ b/pkg/reconciler/certificate/certificate_test.go @@ -19,8 +19,8 @@ package certificate import ( "context" "errors" - "fmt" "hash/adler32" + "strconv" "testing" "time" @@ -898,7 +898,7 @@ func cmSolverService(hostname, namespace string) *corev1.Service { Name: "cm-solver-" + hostname, Namespace: namespace, Labels: map[string]string{ - httpDomainLabel: fmt.Sprintf("%d", adler32.Checksum([]byte(hostname))), + httpDomainLabel: strconv.FormatUint(uint64(adler32.Checksum([]byte(hostname))), 10), }, }, Spec: corev1.ServiceSpec{ diff --git a/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go b/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go index cbb1765353d2..7bf0c4086a80 100644 --- a/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go +++ b/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go @@ -17,6 +17,7 @@ limitations under the License. package resources import ( + "errors" "fmt" "strings" "testing" @@ -315,7 +316,7 @@ func TestMakeCertManagerCertificateLongCommonName(t *testing.T) { } func TestMakeCertManagerCertificateDomainMappingIsTooLong(t *testing.T) { - wantError := fmt.Errorf("error creating cert-manager certificate: CommonName (this.is.aaaaaaaaaaaaaaa.reallyreallyreallyreallyreallylong.domainmapping) longer than 63 characters") + wantError := errors.New("error creating cert-manager certificate: CommonName (this.is.aaaaaaaaaaaaaaa.reallyreallyreallyreallyreallylong.domainmapping) longer than 63 characters") cert, gotError := MakeCertManagerCertificate(cmConfig, &v1alpha1.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cert-from-domain-mapping", @@ -346,7 +347,7 @@ func TestMakeCertManagerCertificateDomainMappingIsTooLong(t *testing.T) { } func TestMakeCertManagerCertificateDomainIsTooLong(t *testing.T) { - wantError := fmt.Errorf("error creating cert-manager certificate: CommonName (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com)(length: 64) too long, prepending short prefix of (k.)(length: 2) will be longer than 64 bytes") + wantError := errors.New("error creating cert-manager certificate: CommonName (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com)(length: 64) too long, prepending short prefix of (k.)(length: 2) will be longer than 64 bytes") cert, gotError := MakeCertManagerCertificate(cmConfig, certWithLongDomain) if cert != nil { @@ -359,7 +360,7 @@ func TestMakeCertManagerCertificateDomainIsTooLong(t *testing.T) { } func TestMakeCertManagerCertificateIssuerNotSet(t *testing.T) { - wantError := fmt.Errorf("error creating cert-manager certificate: issuerRef was not set in config-certmanager") + wantError := errors.New("error creating cert-manager certificate: issuerRef was not set in config-certmanager") cmConfigNoIssuer := cmConfig.DeepCopy() cmConfigNoIssuer.IssuerRef = nil @@ -376,7 +377,7 @@ func TestMakeCertManagerCertificateIssuerNotSet(t *testing.T) { } func TestMakeCertManagerCertificateLocalIssuerNotSet(t *testing.T) { - wantError := fmt.Errorf("error creating cert-manager certificate: clusterLocalIssuerRef was not set in config-certmanager") + wantError := errors.New("error creating cert-manager certificate: clusterLocalIssuerRef was not set in config-certmanager") cmConfigNoIssuer := cmConfig.DeepCopy() cmConfigNoIssuer.ClusterLocalIssuerRef = nil @@ -393,7 +394,7 @@ func TestMakeCertManagerCertificateLocalIssuerNotSet(t *testing.T) { } func TestMakeCertManagerCertificateSystemInternalIssuerNotSet(t *testing.T) { - wantError := fmt.Errorf("error creating cert-manager certificate: systemInternalIssuerRef was not set in config-certmanager") + wantError := errors.New("error creating cert-manager certificate: systemInternalIssuerRef was not set in config-certmanager") cmConfigNoIssuer := cmConfig.DeepCopy() cmConfigNoIssuer.SystemInternalIssuerRef = nil diff --git a/pkg/reconciler/configuration/resources/revision.go b/pkg/reconciler/configuration/resources/revision.go index 62ee9ff36351..8783e75d0e35 100644 --- a/pkg/reconciler/configuration/resources/revision.go +++ b/pkg/reconciler/configuration/resources/revision.go @@ -19,6 +19,7 @@ package resources import ( "context" "fmt" + "strconv" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -104,7 +105,7 @@ func RevisionLabelValueForKey(key string, config metav1.Object) string { case serving.ServiceLabelKey: return config.GetLabels()[serving.ServiceLabelKey] case serving.ConfigurationGenerationLabelKey: - return fmt.Sprint(config.GetGeneration()) + return strconv.FormatInt(config.GetGeneration(), 10) case serving.ConfigurationUIDLabelKey: return string(config.GetUID()) case serving.ServiceUIDLabelKey: diff --git a/pkg/reconciler/revision/resolve_test.go b/pkg/reconciler/revision/resolve_test.go index 61ca53680c50..bef5fac63c58 100644 --- a/pkg/reconciler/revision/resolve_test.go +++ b/pkg/reconciler/revision/resolve_test.go @@ -30,6 +30,7 @@ import ( "net/url" "os" "path/filepath" + "strconv" "strings" "testing" "time" @@ -92,7 +93,7 @@ func fakeRegistry(t *testing.T, repo, username, password, ua string, img v1.Imag t.Error("Digest() =", err) } w.Header().Set("Content-Type", string(mt)) - w.Header().Set("Content-Length", fmt.Sprint(sz)) + w.Header().Set("Content-Length", strconv.FormatInt(sz, 10)) w.Header().Set("Docker-Content-Digest", digest.String()) default: t.Error("Unexpected path:", r.URL.Path) diff --git a/pkg/reconciler/revision/revision_test.go b/pkg/reconciler/revision/revision_test.go index 3b8827e56a4c..d6572093b219 100644 --- a/pkg/reconciler/revision/revision_test.go +++ b/pkg/reconciler/revision/revision_test.go @@ -19,8 +19,8 @@ package revision import ( "context" "errors" - "fmt" "math/rand" + "strconv" "testing" "time" @@ -543,7 +543,7 @@ func TestGlobalResyncOnDefaultCMChange(t *testing.T) { Name: config.DefaultsConfigName, }, Data: map[string]string{ - "container-concurrency": fmt.Sprint(pos), + "container-concurrency": strconv.FormatInt(pos, 10), }, }) diff --git a/test/conformance/api/v1/revision_timeout_test.go b/test/conformance/api/v1/revision_timeout_test.go index 6c8097559515..e3c3de96764f 100644 --- a/test/conformance/api/v1/revision_timeout_test.go +++ b/test/conformance/api/v1/revision_timeout_test.go @@ -24,6 +24,7 @@ import ( "fmt" "net/http" "net/url" + "strconv" "testing" "time" @@ -50,8 +51,8 @@ func sendRequest(t *testing.T, clients *test.Clients, endpoint *url.URL, }() u, _ := url.Parse(endpoint.String()) q := u.Query() - q.Set("initialTimeout", fmt.Sprint(initialSleep.Milliseconds())) - q.Set("timeout", fmt.Sprint(sleep.Milliseconds())) + q.Set("initialTimeout", strconv.FormatInt(initialSleep.Milliseconds(), 10)) + q.Set("timeout", strconv.FormatInt(sleep.Milliseconds(), 10)) u.RawQuery = q.Encode() req, err := http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { diff --git a/test/conformance/runtime/cgroup_test.go b/test/conformance/runtime/cgroup_test.go index 5e79debb146b..ff41d34acb07 100644 --- a/test/conformance/runtime/cgroup_test.go +++ b/test/conformance/runtime/cgroup_test.go @@ -20,6 +20,7 @@ limitations under the License. package runtime import ( + "errors" "fmt" "strconv" "strings" @@ -49,7 +50,7 @@ func isCgroupsV2(mounts []*types.Mount) (bool, error) { return mount.Type == "cgroup2", nil } } - return false, fmt.Errorf("Failed to find cgroup mount on /sys/fs/cgroup") + return false, errors.New("Failed to find cgroup mount on /sys/fs/cgroup") } // TestMustHaveCgroupConfigured verifies that the Linux cgroups are configured based on the specified @@ -72,14 +73,14 @@ func TestMustHaveCgroupConfigured(t *testing.T) { // size (4k, 8k, 16k, 64k) as some environments apply rounding to the closest page // size multiple, see https://github.com/kubernetes/kubernetes/issues/82230. var expectedCgroupsV1 = map[string]string{ - "/sys/fs/cgroup/memory/memory.limit_in_bytes": fmt.Sprintf("%d", resources.Limits.Memory().Value()&^4095), // floor() to 4K pages - "/sys/fs/cgroup/cpu/cpu.shares": fmt.Sprintf("%d", resources.Requests.Cpu().MilliValue()*1024/1000)} + "/sys/fs/cgroup/memory/memory.limit_in_bytes": strconv.FormatInt(resources.Limits.Memory().Value()&^4095, 10), // floor() to 4K pages + "/sys/fs/cgroup/cpu/cpu.shares": strconv.FormatInt(resources.Requests.Cpu().MilliValue()*1024/1000, 10)} var expectedCgroupsV2 = map[string]string{ - "/sys/fs/cgroup/memory.max": fmt.Sprintf("%d", resources.Limits.Memory().Value()&^4095), // floor() to 4K pages + "/sys/fs/cgroup/memory.max": strconv.FormatInt(resources.Limits.Memory().Value()&^4095, 10), // floor() to 4K pages // Convert cgroup v1 cpu.shares value to cgroup v2 cpu.weight // https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2254-cgroup-v2#phase-1-convert-from-cgroups-v1-settings-to-v2 - "/sys/fs/cgroup/cpu.weight": fmt.Sprintf("%d", ((((resources.Requests.Cpu().MilliValue()*1024/1000)-2)*9999)/262142)+1), + "/sys/fs/cgroup/cpu.weight": strconv.FormatInt(((((resources.Requests.Cpu().MilliValue()*1024/1000)-2)*9999)/262142)+1, 10), } cgroups := ri.Host.Cgroups diff --git a/test/e2e/autoscale_hpa_test.go b/test/e2e/autoscale_hpa_test.go index 4a380eb5d2c3..d3dc3e0116bf 100644 --- a/test/e2e/autoscale_hpa_test.go +++ b/test/e2e/autoscale_hpa_test.go @@ -21,7 +21,6 @@ package e2e import ( "context" - "fmt" "strconv" "strings" "testing" @@ -93,7 +92,7 @@ func setupHPASvc(t *testing.T, metric string, target int) *TestContext { autoscaling.ClassAnnotationKey: autoscaling.HPA, autoscaling.MetricAnnotationKey: metric, autoscaling.TargetAnnotationKey: strconv.Itoa(target), - autoscaling.MaxScaleAnnotationKey: fmt.Sprintf("%d", int(maxPods)), + autoscaling.MaxScaleAnnotationKey: strconv.Itoa(int(maxPods)), autoscaling.WindowAnnotationKey: "20s", }), rtesting.WithResourceRequirements(corev1.ResourceRequirements{ Requests: corev1.ResourceList{ diff --git a/test/e2e/destroypod_test.go b/test/e2e/destroypod_test.go index 2434649a2813..789be67a7911 100644 --- a/test/e2e/destroypod_test.go +++ b/test/e2e/destroypod_test.go @@ -24,6 +24,7 @@ import ( "fmt" "net/http" "net/url" + "strconv" "testing" "time" @@ -114,7 +115,7 @@ func TestDestroyPodInflight(t *testing.T) { // The timeout app sleeps for the time passed via the timeout query parameter in milliseconds u, _ := url.Parse(routeURL.String()) q := u.Query() - q.Set("timeout", fmt.Sprint(timeoutRequestDuration.Milliseconds())) + q.Set("timeout", strconv.FormatInt(timeoutRequestDuration.Milliseconds(), 10)) u.RawQuery = q.Encode() req, err := http.NewRequestWithContext(egCtx, http.MethodGet, u.String(), nil) if err != nil { diff --git a/test/e2e/externaldomaintls/util_test.go b/test/e2e/externaldomaintls/util_test.go index b9f1e907c1d9..f80cb18229e9 100644 --- a/test/e2e/externaldomaintls/util_test.go +++ b/test/e2e/externaldomaintls/util_test.go @@ -28,6 +28,7 @@ import ( "net" "net/http" "net/http/httputil" + "strconv" "strings" "testing" "time" @@ -192,7 +193,7 @@ func CreateDialContext(ctx context.Context, t *testing.T, ing *v1alpha1.Ingress, return nil, err } for _, sp := range svc.Spec.Ports { - if fmt.Sprint(sp.Port) == port { + if strconv.Itoa(int(sp.Port)) == port { return dial(ctx, "tcp", fmt.Sprintf("%s:%d", pkgTest.Flags.IngressEndpoint, sp.NodePort)) } } diff --git a/test/e2e/systeminternaltls/system_internal_tls_test.go b/test/e2e/systeminternaltls/system_internal_tls_test.go index 61931497c370..bfc12d5ac24c 100644 --- a/test/e2e/systeminternaltls/system_internal_tls_test.go +++ b/test/e2e/systeminternaltls/system_internal_tls_test.go @@ -21,7 +21,6 @@ package systeminternaltls import ( "context" - "fmt" "net/url" "os" "strings" @@ -96,7 +95,7 @@ func TestSystemInternalTLS(t *testing.T) { t.Log("Checking Queue-Proxy logs") pods, err = clients.KubeClient.CoreV1().Pods("serving-tests").List(context.TODO(), v1.ListOptions{ - LabelSelector: fmt.Sprintf("serving.knative.dev/configuration=%s", names.Config), + LabelSelector: "serving.knative.dev/configuration=" + names.Config, }) if err != nil { t.Fatalf("Failed to get pods: %v", err) @@ -198,7 +197,7 @@ func TestTLSCertificateRotation(t *testing.T) { t.Log("Checking queue-proxy logs") pods, err := clients.KubeClient.CoreV1().Pods(test.ServingFlags.TestNamespace).List(context.TODO(), v1.ListOptions{ - LabelSelector: fmt.Sprintf("serving.knative.dev/configuration=%s", names.Config), + LabelSelector: "serving.knative.dev/configuration=" + names.Config, }) if err != nil { t.Fatal(err) diff --git a/test/e2e/timeout_test.go b/test/e2e/timeout_test.go index 0a1df1c0c086..6ccf469859ce 100644 --- a/test/e2e/timeout_test.go +++ b/test/e2e/timeout_test.go @@ -24,6 +24,7 @@ import ( "fmt" "net/http" "net/url" + "strconv" "testing" "time" @@ -50,8 +51,8 @@ func sendRequestWithTimeout(t *testing.T, clients *test.Clients, endpoint *url.U }() u, _ := url.Parse(endpoint.String()) q := u.Query() - q.Set("initialTimeout", fmt.Sprint(initialSleep.Milliseconds())) - q.Set("timeout", fmt.Sprint(sleep.Milliseconds())) + q.Set("initialTimeout", strconv.FormatInt(initialSleep.Milliseconds(), 10)) + q.Set("timeout", strconv.FormatInt(sleep.Milliseconds(), 10)) u.RawQuery = q.Encode() req, err := http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { diff --git a/test/e2e/websocket.go b/test/e2e/websocket.go index 47055798b034..a509ce4b010e 100644 --- a/test/e2e/websocket.go +++ b/test/e2e/websocket.go @@ -59,7 +59,7 @@ func connect(t *testing.T, clients *test.Clients, domain, timeout string) (*webs } } - rawQuery := fmt.Sprintf("delay=%s", timeout) + rawQuery := "delay=" + timeout u := url.URL{Scheme: "ws", Host: net.JoinHostPort(address, mapper("80")), Path: "/", RawQuery: rawQuery} if test.ServingFlags.HTTPS { u = url.URL{Scheme: "wss", Host: net.JoinHostPort(address, mapper("443")), Path: "/", RawQuery: rawQuery} From c7166605a3ddc6604bd426244dac4695f1050e2f Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 00:13:45 -0500 Subject: [PATCH 10/35] fix nosprintfhostport --- pkg/autoscaler/statforwarder/leases.go | 4 +++- pkg/reconciler/autoscaling/kpa/scaler.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/pkg/autoscaler/statforwarder/leases.go b/pkg/autoscaler/statforwarder/leases.go index 7c27a0ca9974..a3c390d96924 100644 --- a/pkg/autoscaler/statforwarder/leases.go +++ b/pkg/autoscaler/statforwarder/leases.go @@ -19,6 +19,8 @@ package statforwarder import ( "context" "fmt" + "net" + "strconv" "go.uber.org/zap" coordinationv1 "k8s.io/api/coordination/v1" @@ -173,7 +175,7 @@ func (f *leaseTracker) leaseUpdated(obj interface{}) { if ip != f.selfIP { f.fwd.setProcessor(n, newForwardProcessor(f.logger.With(zap.String("bucket", n)), n, holder, - fmt.Sprintf("ws://%s:%d", ip, autoscalerPort), + fmt.Sprintf("ws://%s", net.JoinHostPort(ip, strconv.Itoa(autoscalerPort))), fmt.Sprintf("ws://%s.%s.%s", n, ns, svcURLSuffix))) // Skip creating/updating Service and Endpoints if not the leader. diff --git a/pkg/reconciler/autoscaling/kpa/scaler.go b/pkg/reconciler/autoscaling/kpa/scaler.go index e59b82fd60a0..80fd7a5d7786 100644 --- a/pkg/reconciler/autoscaling/kpa/scaler.go +++ b/pkg/reconciler/autoscaling/kpa/scaler.go @@ -19,7 +19,9 @@ package kpa import ( "context" "fmt" + "net" "net/http" + "strconv" "time" "knative.dev/pkg/apis/duck" @@ -126,7 +128,7 @@ func paToProbeTarget(pa *autoscalingv1alpha1.PodAutoscaler) string { svc := pkgnet.GetServiceHostname(pa.Status.ServiceName, pa.Namespace) port := netapis.ServicePort(pa.Spec.ProtocolType) - return fmt.Sprintf("http://%s:%d/%s", svc, port, nethttp.HealthCheckPath) + return fmt.Sprintf("http://%s/%s", net.JoinHostPort(svc, strconv.Itoa(port)), nethttp.HealthCheckPath) } // activatorProbe returns true if via probe it determines that the From 9afcee815657607e78f2a259abb9f97d9ee708ce Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 00:19:07 -0500 Subject: [PATCH 11/35] f perfsprint --- pkg/autoscaler/statforwarder/leases.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/autoscaler/statforwarder/leases.go b/pkg/autoscaler/statforwarder/leases.go index a3c390d96924..5c0e15e692fa 100644 --- a/pkg/autoscaler/statforwarder/leases.go +++ b/pkg/autoscaler/statforwarder/leases.go @@ -175,7 +175,7 @@ func (f *leaseTracker) leaseUpdated(obj interface{}) { if ip != f.selfIP { f.fwd.setProcessor(n, newForwardProcessor(f.logger.With(zap.String("bucket", n)), n, holder, - fmt.Sprintf("ws://%s", net.JoinHostPort(ip, strconv.Itoa(autoscalerPort))), + "ws://"+net.JoinHostPort(ip, strconv.Itoa(autoscalerPort)), fmt.Sprintf("ws://%s.%s.%s", n, ns, svcURLSuffix))) // Skip creating/updating Service and Endpoints if not the leader. From 8d648ec0fa0cce9f199ce6879d1f4507b399a76a Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 00:33:19 -0500 Subject: [PATCH 12/35] fix nolintlint - remove nolint directives that had no effect --- pkg/activator/net/lb_policy.go | 2 -- pkg/apis/autoscaling/register.go | 2 -- pkg/apis/serving/v1/configuration_conversion.go | 5 +---- pkg/apis/serving/v1/revision_conversion.go | 5 +---- pkg/apis/serving/v1/route_conversion.go | 5 +---- pkg/apis/serving/v1/service_conversion.go | 5 +---- pkg/http/handler/timeout_test.go | 2 +- pkg/queue/health/probe.go | 1 - pkg/reconciler/revision/resources/deploy.go | 2 -- test/performance/performance/influx.go | 1 - 10 files changed, 5 insertions(+), 25 deletions(-) diff --git a/pkg/activator/net/lb_policy.go b/pkg/activator/net/lb_policy.go index 0e2fc3b0d685..8d757fe39d3f 100644 --- a/pkg/activator/net/lb_policy.go +++ b/pkg/activator/net/lb_policy.go @@ -33,8 +33,6 @@ type lbPolicy func(ctx context.Context, targets []*podTracker) (func(), *podTrac // randomLBPolicy is a load balancer policy that picks a random target. // This approximates the LB policy done by K8s Service (IPTables based). -// -// nolint // This is currently unused but kept here for posterity. func randomLBPolicy(_ context.Context, targets []*podTracker) (func(), *podTracker) { return noop, targets[rand.Intn(len(targets))] } diff --git a/pkg/apis/autoscaling/register.go b/pkg/apis/autoscaling/register.go index 3d488f105695..8ed7042c31d3 100644 --- a/pkg/apis/autoscaling/register.go +++ b/pkg/apis/autoscaling/register.go @@ -138,8 +138,6 @@ const ( // points will be missed entirely by the panic window which is // smaller than the stable window. Anything less than 6 seconds // isn't going to work well. - // - // nolint:revive // False positive, Min means minimum, not minutes. WindowMin = 6 * time.Second // WindowMax is the maximum permitted stable autoscaling window. // This keeps the event horizon to a reasonable enough limit. diff --git a/pkg/apis/serving/v1/configuration_conversion.go b/pkg/apis/serving/v1/configuration_conversion.go index 647e4fb18d7c..985317ec0217 100644 --- a/pkg/apis/serving/v1/configuration_conversion.go +++ b/pkg/apis/serving/v1/configuration_conversion.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:stylecheck // ignore complaints about receiver having different names package v1 import ( @@ -24,15 +25,11 @@ import ( ) // ConvertTo implements apis.Convertible -// -//nolint:stylecheck func (source *Configuration) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible -// -//nolint:stylecheck func (sink *Configuration) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/revision_conversion.go b/pkg/apis/serving/v1/revision_conversion.go index 0cd88b03359a..278ef1e5151a 100644 --- a/pkg/apis/serving/v1/revision_conversion.go +++ b/pkg/apis/serving/v1/revision_conversion.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:stylecheck // ignore complaints about receiver having different names package v1 import ( @@ -24,15 +25,11 @@ import ( ) // ConvertTo implements apis.Convertible -// -//nolint:stylecheck func (source *Revision) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible -// -//nolint:stylecheck func (sink *Revision) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/route_conversion.go b/pkg/apis/serving/v1/route_conversion.go index b2dcab8b7a76..1c3275553321 100644 --- a/pkg/apis/serving/v1/route_conversion.go +++ b/pkg/apis/serving/v1/route_conversion.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:stylecheck // ignore complaints about receiver having different names package v1 import ( @@ -24,15 +25,11 @@ import ( ) // ConvertTo implements apis.Convertible -// -//nolint:stylecheck func (source *Route) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible -// -//nolint:stylecheck func (sink *Route) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/apis/serving/v1/service_conversion.go b/pkg/apis/serving/v1/service_conversion.go index a77e294c23f9..3b4853f1a31d 100644 --- a/pkg/apis/serving/v1/service_conversion.go +++ b/pkg/apis/serving/v1/service_conversion.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:stylecheck // ignore complaints about receiver having different names package v1 import ( @@ -24,15 +25,11 @@ import ( ) // ConvertTo implements apis.Convertible -// -//nolint:stylecheck func (source *Service) ConvertTo(_ context.Context, sink apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", sink) } // ConvertFrom implements apis.Convertible -// -//nolint:stylecheck func (sink *Service) ConvertFrom(_ context.Context, source apis.Convertible) error { return fmt.Errorf("v1 is the highest known version, got: %T", source) } diff --git a/pkg/http/handler/timeout_test.go b/pkg/http/handler/timeout_test.go index 55109ab900b0..ea9158840867 100644 --- a/pkg/http/handler/timeout_test.go +++ b/pkg/http/handler/timeout_test.go @@ -113,7 +113,7 @@ func testTimeoutScenario(t *testing.T, scenarios []timeoutHandlerTestScenario) { defer func() { if scenario.wantPanic { - if recovered := recover(); recovered != http.ErrAbortHandler { //nolint // False positive for errors.Is check + if recovered := recover(); recovered != http.ErrAbortHandler { t.Errorf("Recover = %v, want: %v", recovered, http.ErrAbortHandler) } } diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 569154e1d012..5c7dd58b1bd5 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -106,7 +106,6 @@ func autoDowngradingTransport(opt HTTPProbeConfigOptions) http.RoundTripper { var transport = func() *http.Transport { t := http.DefaultTransport.(*http.Transport).Clone() - //nolint:gosec // We explicitly don't need to check certs here. t.TLSClientConfig.InsecureSkipVerify = true return t }() diff --git a/pkg/reconciler/revision/resources/deploy.go b/pkg/reconciler/revision/resources/deploy.go index f62c5514f2d3..aba5c877bbcd 100644 --- a/pkg/reconciler/revision/resources/deploy.go +++ b/pkg/reconciler/revision/resources/deploy.go @@ -58,7 +58,6 @@ var ( SubPathExpr: "$(K_INTERNAL_POD_NAMESPACE)_$(K_INTERNAL_POD_NAME)_", } - //nolint:gosec // Volume, not hardcoded credentials varTokenVolume = corev1.Volume{ Name: "knative-token-volume", VolumeSource: corev1.VolumeSource{ @@ -74,7 +73,6 @@ var ( ReadOnly: true, } - //nolint:gosec // VolumeMount, not hardcoded credentials varTokenVolumeMount = corev1.VolumeMount{ Name: varTokenVolume.Name, MountPath: queue.TokenDirectory, diff --git a/test/performance/performance/influx.go b/test/performance/performance/influx.go index 971fc3130eff..d33103b663ae 100644 --- a/test/performance/performance/influx.go +++ b/test/performance/performance/influx.go @@ -60,7 +60,6 @@ func NewInfluxReporter(tags map[string]string) (*InfluxReporter, error) { client := influxdb2.NewClientWithOptions(url, token, influxdb2.DefaultOptions(). SetUseGZip(true). - //nolint:gosec // We explicitly don't need to check certs here since this is test code. SetTLSConfig(&tls.Config{InsecureSkipVerify: true})) writeAPI := client.WriteAPI(org, bucket) From ca7f5e387fede970d19f7d227d47532e72534aeb Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 00:34:05 -0500 Subject: [PATCH 13/35] fix noctx linter --- pkg/queue/health/probe.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 5c7dd58b1bd5..26b416007458 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -126,6 +126,7 @@ func http2UpgradeProbe(config HTTPProbeConfigOptions) (int, error) { if err != nil { return 0, fmt.Errorf("error constructing probe url %w", err) } + //nolint:noctx // timeout is specified on the http.Client above req, err := http.NewRequest(http.MethodOptions, url.String(), nil) if err != nil { return 0, fmt.Errorf("error constructing probe request %w", err) @@ -183,6 +184,7 @@ func HTTPProbe(config HTTPProbeConfigOptions) error { if err != nil { return fmt.Errorf("error constructing probe url %w", err) } + //nolint:noctx // timeout is specified on the http.Client above req, err := http.NewRequest(http.MethodGet, url.String(), nil) if err != nil { return fmt.Errorf("error constructing probe request %w", err) From 153a53bb33b8fb18b732a74b62d096e0faa9f319 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 11:39:14 -0500 Subject: [PATCH 14/35] fix gomodguard linter - drop uber atomic package --- go.mod | 2 - go.sum | 3 - pkg/activator/config/store.go | 2 +- pkg/activator/handler/concurrency_reporter.go | 10 +- pkg/activator/handler/handler_test.go | 2 +- pkg/activator/net/revision_backends.go | 2 +- pkg/activator/net/throttler.go | 9 +- pkg/activator/testing/roundtripper.go | 5 +- pkg/autoscaler/metrics/stats_scraper.go | 7 +- pkg/http/request_log.go | 2 +- pkg/http/response_recorder.go | 3 +- pkg/queue/breaker.go | 15 +- pkg/queue/handler_test.go | 6 +- pkg/queue/health/probe_test.go | 6 +- pkg/queue/protobuf_stats_reporter.go | 3 +- pkg/queue/readiness/probe_test.go | 12 +- pkg/reconciler/autoscaling/kpa/kpa_test.go | 20 +- .../certificate/config/cert_manager.go | 3 +- pkg/reconciler/metric/metric_test.go | 6 +- test/prober.go | 9 +- test/test_images/singlethreaded/main.go | 6 +- vendor/github.com/ghodss/yaml/.gitignore | 20 - vendor/github.com/ghodss/yaml/.travis.yml | 7 - vendor/github.com/ghodss/yaml/LICENSE | 50 -- vendor/github.com/ghodss/yaml/README.md | 121 ----- vendor/github.com/ghodss/yaml/fields.go | 501 ------------------ vendor/github.com/ghodss/yaml/yaml.go | 277 ---------- vendor/go.uber.org/atomic/.codecov.yml | 19 - vendor/go.uber.org/atomic/.gitignore | 15 - vendor/go.uber.org/atomic/CHANGELOG.md | 117 ---- vendor/go.uber.org/atomic/LICENSE.txt | 19 - vendor/go.uber.org/atomic/Makefile | 79 --- vendor/go.uber.org/atomic/README.md | 63 --- vendor/go.uber.org/atomic/bool.go | 88 --- vendor/go.uber.org/atomic/bool_ext.go | 53 -- vendor/go.uber.org/atomic/doc.go | 23 - vendor/go.uber.org/atomic/duration.go | 89 ---- vendor/go.uber.org/atomic/duration_ext.go | 40 -- vendor/go.uber.org/atomic/error.go | 62 --- vendor/go.uber.org/atomic/error_ext.go | 39 -- vendor/go.uber.org/atomic/float32.go | 77 --- vendor/go.uber.org/atomic/float32_ext.go | 76 --- vendor/go.uber.org/atomic/float64.go | 77 --- vendor/go.uber.org/atomic/float64_ext.go | 76 --- vendor/go.uber.org/atomic/gen.go | 27 - vendor/go.uber.org/atomic/int32.go | 109 ---- vendor/go.uber.org/atomic/int64.go | 109 ---- vendor/go.uber.org/atomic/nocmp.go | 35 -- vendor/go.uber.org/atomic/pointer_go118.go | 60 --- vendor/go.uber.org/atomic/pointer_go119.go | 61 --- vendor/go.uber.org/atomic/string.go | 65 --- vendor/go.uber.org/atomic/string_ext.go | 43 -- vendor/go.uber.org/atomic/time.go | 55 -- vendor/go.uber.org/atomic/time_ext.go | 36 -- vendor/go.uber.org/atomic/uint32.go | 109 ---- vendor/go.uber.org/atomic/uint64.go | 109 ---- vendor/go.uber.org/atomic/uintptr.go | 109 ---- vendor/go.uber.org/atomic/unsafe_pointer.go | 65 --- vendor/go.uber.org/atomic/value.go | 31 -- vendor/modules.txt | 6 - 60 files changed, 61 insertions(+), 3089 deletions(-) delete mode 100644 vendor/github.com/ghodss/yaml/.gitignore delete mode 100644 vendor/github.com/ghodss/yaml/.travis.yml delete mode 100644 vendor/github.com/ghodss/yaml/LICENSE delete mode 100644 vendor/github.com/ghodss/yaml/README.md delete mode 100644 vendor/github.com/ghodss/yaml/fields.go delete mode 100644 vendor/github.com/ghodss/yaml/yaml.go delete mode 100644 vendor/go.uber.org/atomic/.codecov.yml delete mode 100644 vendor/go.uber.org/atomic/.gitignore delete mode 100644 vendor/go.uber.org/atomic/CHANGELOG.md delete mode 100644 vendor/go.uber.org/atomic/LICENSE.txt delete mode 100644 vendor/go.uber.org/atomic/Makefile delete mode 100644 vendor/go.uber.org/atomic/README.md delete mode 100644 vendor/go.uber.org/atomic/bool.go delete mode 100644 vendor/go.uber.org/atomic/bool_ext.go delete mode 100644 vendor/go.uber.org/atomic/doc.go delete mode 100644 vendor/go.uber.org/atomic/duration.go delete mode 100644 vendor/go.uber.org/atomic/duration_ext.go delete mode 100644 vendor/go.uber.org/atomic/error.go delete mode 100644 vendor/go.uber.org/atomic/error_ext.go delete mode 100644 vendor/go.uber.org/atomic/float32.go delete mode 100644 vendor/go.uber.org/atomic/float32_ext.go delete mode 100644 vendor/go.uber.org/atomic/float64.go delete mode 100644 vendor/go.uber.org/atomic/float64_ext.go delete mode 100644 vendor/go.uber.org/atomic/gen.go delete mode 100644 vendor/go.uber.org/atomic/int32.go delete mode 100644 vendor/go.uber.org/atomic/int64.go delete mode 100644 vendor/go.uber.org/atomic/nocmp.go delete mode 100644 vendor/go.uber.org/atomic/pointer_go118.go delete mode 100644 vendor/go.uber.org/atomic/pointer_go119.go delete mode 100644 vendor/go.uber.org/atomic/string.go delete mode 100644 vendor/go.uber.org/atomic/string_ext.go delete mode 100644 vendor/go.uber.org/atomic/time.go delete mode 100644 vendor/go.uber.org/atomic/time_ext.go delete mode 100644 vendor/go.uber.org/atomic/uint32.go delete mode 100644 vendor/go.uber.org/atomic/uint64.go delete mode 100644 vendor/go.uber.org/atomic/uintptr.go delete mode 100644 vendor/go.uber.org/atomic/unsafe_pointer.go delete mode 100644 vendor/go.uber.org/atomic/value.go diff --git a/go.mod b/go.mod index 6ac4eaeb0332..26b3fa9572f9 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,6 @@ require ( github.com/ahmetb/gen-crd-api-reference-docs v0.3.1-0.20210609063737-0067dc6dcea2 github.com/cert-manager/cert-manager v1.13.3 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc - github.com/ghodss/yaml v1.0.0 github.com/gogo/protobuf v1.3.2 github.com/google/go-cmp v0.6.0 github.com/google/go-containerregistry v0.13.0 @@ -18,7 +17,6 @@ require ( github.com/kelseyhightower/envconfig v1.4.0 github.com/tsenart/vegeta/v12 v12.12.0 go.opencensus.io v0.24.0 - go.uber.org/atomic v1.10.0 go.uber.org/automaxprocs v1.6.0 go.uber.org/zap v1.27.0 golang.org/x/net v0.34.0 diff --git a/go.sum b/go.sum index 95e1d99821e0..09827cff5202 100644 --- a/go.sum +++ b/go.sum @@ -185,7 +185,6 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/getkin/kin-openapi v0.61.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-chi/chi/v5 v5.0.0/go.mod h1:BBug9lr0cqtdAhsu6R4AAdvufI0/XBzAQSsUqJpoZOs= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= @@ -544,8 +543,6 @@ go.opentelemetry.io/otel/sdk/metric v1.31.0/go.mod h1:CRInTMVvNhUKgSAMbKyTMxqOBC go.opentelemetry.io/otel/trace v1.31.0 h1:ffjsj1aRouKewfr85U2aGagJ46+MvodynlQ1HYdmJys= go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06FJAsO1tJg480A= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/pkg/activator/config/store.go b/pkg/activator/config/store.go index d0a6056960e0..8b7040cb7691 100644 --- a/pkg/activator/config/store.go +++ b/pkg/activator/config/store.go @@ -18,8 +18,8 @@ package config import ( "context" + "sync/atomic" - "go.uber.org/atomic" netcfg "knative.dev/networking/pkg/config" "knative.dev/pkg/configmap" tracingconfig "knative.dev/pkg/tracing/config" diff --git a/pkg/activator/handler/concurrency_reporter.go b/pkg/activator/handler/concurrency_reporter.go index 09b2cf1b975f..fcf8a0fcfbff 100644 --- a/pkg/activator/handler/concurrency_reporter.go +++ b/pkg/activator/handler/concurrency_reporter.go @@ -21,9 +21,9 @@ import ( "math" "net/http" "sync" + "sync/atomic" "time" - "go.uber.org/atomic" "go.uber.org/zap" "k8s.io/apimachinery/pkg/types" netstats "knative.dev/networking/pkg/http/stats" @@ -94,7 +94,7 @@ func (cr *ConcurrencyReporter) handleRequestIn(event netstats.ReqEvent) *revisio // the handleRequestIn call. func (cr *ConcurrencyReporter) handleRequestOut(stat *revisionStats, event netstats.ReqEvent) { stat.stats.HandleEvent(event) - stat.refs.Dec() + stat.refs.Add(-1) } // getOrCreateStat gets a stat from the state if present. @@ -106,7 +106,7 @@ func (cr *ConcurrencyReporter) getOrCreateStat(event netstats.ReqEvent) (*revisi if stat != nil { // Since this is incremented under the lock, it's guaranteed to be observed by // the deletion routine. - stat.refs.Inc() + stat.refs.Add(1) cr.mux.RUnlock() return stat, nil } @@ -120,7 +120,7 @@ func (cr *ConcurrencyReporter) getOrCreateStat(event netstats.ReqEvent) (*revisi if stat != nil { // Since this is incremented under the lock, it's guaranteed to be observed by // the deletion routine. - stat.refs.Inc() + stat.refs.Add(1) return stat, nil } @@ -128,7 +128,7 @@ func (cr *ConcurrencyReporter) getOrCreateStat(event netstats.ReqEvent) (*revisi stats: netstats.NewRequestStats(event.Time), firstRequest: 1, } - stat.refs.Inc() + stat.refs.Add(1) cr.stats[event.Key] = stat return stat, &asmetrics.StatMessage{ diff --git a/pkg/activator/handler/handler_test.go b/pkg/activator/handler/handler_test.go index c206b46304dc..9877517712d1 100644 --- a/pkg/activator/handler/handler_test.go +++ b/pkg/activator/handler/handler_test.go @@ -25,10 +25,10 @@ import ( "math/rand" "net/http" "net/http/httptest" + "sync/atomic" "testing" "time" - "go.uber.org/atomic" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" netheader "knative.dev/networking/pkg/http/header" diff --git a/pkg/activator/net/revision_backends.go b/pkg/activator/net/revision_backends.go index 83f60b1328aa..ac1436c94520 100644 --- a/pkg/activator/net/revision_backends.go +++ b/pkg/activator/net/revision_backends.go @@ -25,9 +25,9 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" - "go.uber.org/atomic" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/sync/errgroup" diff --git a/pkg/activator/net/throttler.go b/pkg/activator/net/throttler.go index 291292df4c53..484e66234d68 100644 --- a/pkg/activator/net/throttler.go +++ b/pkg/activator/net/throttler.go @@ -21,8 +21,8 @@ import ( "net/http" "sort" "sync" + "sync/atomic" - "go.uber.org/atomic" "go.uber.org/zap" "k8s.io/apimachinery/pkg/util/sets" @@ -190,15 +190,18 @@ func newRevisionThrottler(revID types.NamespacedName, revBreaker = queue.NewBreaker(breakerParams) lbp = newRoundRobinPolicy() } - return &revisionThrottler{ + t := &revisionThrottler{ revID: revID, containerConcurrency: containerConcurrency, breaker: revBreaker, logger: logger, protocol: proto, - activatorIndex: *atomic.NewInt32(-1), // Start with unknown. lbPolicy: lbp, } + + // Start with unknown + t.activatorIndex.Store(-1) + return t } func noop() {} diff --git a/pkg/activator/testing/roundtripper.go b/pkg/activator/testing/roundtripper.go index 8a4c05a8005d..3a2f2d0ab188 100644 --- a/pkg/activator/testing/roundtripper.go +++ b/pkg/activator/testing/roundtripper.go @@ -21,10 +21,9 @@ import ( "net/http" "net/http/httptest" "sync" + "sync/atomic" "time" - "go.uber.org/atomic" - netheader "knative.dev/networking/pkg/http/header" "knative.dev/serving/pkg/queue" ) @@ -130,7 +129,7 @@ func (rt *FakeRoundTripper) RT(req *http.Request) (*http.Response, error) { } if req.Header.Get(netheader.ProbeKey) != "" { - rt.NumProbes.Inc() + rt.NumProbes.Add(1) resp := rt.popResponse(req.URL.Host) err := delayResponse(resp) diff --git a/pkg/autoscaler/metrics/stats_scraper.go b/pkg/autoscaler/metrics/stats_scraper.go index e3ba25ab68e9..8f34cababb78 100644 --- a/pkg/autoscaler/metrics/stats_scraper.go +++ b/pkg/autoscaler/metrics/stats_scraper.go @@ -24,11 +24,11 @@ import ( "net/http" "strconv" "sync" + "sync/atomic" "time" "go.opencensus.io/stats" "go.opencensus.io/stats/view" - "go.uber.org/atomic" "go.uber.org/zap" "golang.org/x/sync/errgroup" @@ -276,7 +276,8 @@ func (s *serviceScraper) scrapePods(window time.Duration) (Stat, error) { pods = append(pods, youngPods...) grp, egCtx := errgroup.WithContext(context.Background()) - idx := atomic.NewInt32(-1) + var idx atomic.Int32 + idx.Store(-1) var sawNonMeshError atomic.Bool // Start |sampleSize| threads to scan in parallel. for i := 0; i < sampleSize; i++ { @@ -285,7 +286,7 @@ func (s *serviceScraper) scrapePods(window time.Duration) (Stat, error) { // scanning pods down the line. for { // Acquire next pod. - myIdx := int(idx.Inc()) + myIdx := int(idx.Add(1)) // All out? if myIdx >= len(pods) { return errPodsExhausted diff --git a/pkg/http/request_log.go b/pkg/http/request_log.go index 8bb86373aa31..1a7bc362fff7 100644 --- a/pkg/http/request_log.go +++ b/pkg/http/request_log.go @@ -23,10 +23,10 @@ import ( "net/http" "strings" "sync" + "sync/atomic" "text/template" "time" - "go.uber.org/atomic" netheader "knative.dev/networking/pkg/http/header" ) diff --git a/pkg/http/response_recorder.go b/pkg/http/response_recorder.go index 079f50be2dd9..01dbe008a3ad 100644 --- a/pkg/http/response_recorder.go +++ b/pkg/http/response_recorder.go @@ -20,8 +20,7 @@ import ( "bufio" "net" "net/http" - - "go.uber.org/atomic" + "sync/atomic" "knative.dev/pkg/websocket" ) diff --git a/pkg/queue/breaker.go b/pkg/queue/breaker.go index 79b78a37cd62..543dd3dd82db 100644 --- a/pkg/queue/breaker.go +++ b/pkg/queue/breaker.go @@ -21,8 +21,7 @@ import ( "errors" "fmt" "math" - - "go.uber.org/atomic" + "sync/atomic" ) var ( @@ -103,7 +102,7 @@ func (b *Breaker) tryAcquirePending() bool { if cur == b.totalSlots { return false } - if b.inFlight.CAS(cur, cur+1) { + if b.inFlight.CompareAndSwap(cur, cur+1) { return true } } @@ -111,7 +110,7 @@ func (b *Breaker) tryAcquirePending() bool { // releasePending releases a slot on the pending "queue". func (b *Breaker) releasePending() { - b.inFlight.Dec() + b.inFlight.Add(-1) } // Reserve reserves an execution slot in the breaker, to permit @@ -204,7 +203,7 @@ func (s *semaphore) tryAcquire() bool { return false } in++ - if s.state.CAS(old, pack(capacity, in)) { + if s.state.CompareAndSwap(old, pack(capacity, in)) { return true } } @@ -227,7 +226,7 @@ func (s *semaphore) acquire(ctx context.Context) error { } in++ - if s.state.CAS(old, pack(capacity, in)) { + if s.state.CompareAndSwap(old, pack(capacity, in)) { return nil } } @@ -246,7 +245,7 @@ func (s *semaphore) release() { } in-- - if s.state.CAS(old, pack(capacity, in)) { + if s.state.CompareAndSwap(old, pack(capacity, in)) { if in < capacity { select { case s.queue <- struct{}{}: @@ -275,7 +274,7 @@ func (s *semaphore) updateCapacity(size int) { return } - if s.state.CAS(old, pack(s64, in)) { + if s.state.CompareAndSwap(old, pack(s64, in)) { if s64 > capacity { for i := uint64(0); i < s64-capacity; i++ { select { diff --git a/pkg/queue/handler_test.go b/pkg/queue/handler_test.go index c37cc2a22a54..adc7d803f1e8 100644 --- a/pkg/queue/handler_test.go +++ b/pkg/queue/handler_test.go @@ -24,10 +24,10 @@ import ( "net/http/httputil" "net/url" "strings" + "sync/atomic" "testing" "time" - "go.uber.org/atomic" netheader "knative.dev/networking/pkg/http/header" netstats "knative.dev/networking/pkg/http/stats" "knative.dev/serving/pkg/activator" @@ -175,7 +175,7 @@ func TestHandlerReqEvent(t *testing.T) { func TestIgnoreProbe(t *testing.T) { // Verifies that probes don't queue. resp := make(chan struct{}) - c := atomic.NewInt32(0) + var c atomic.Int32 // Ensure we can receive 3 requests with CC=1. go func() { to := time.After(3 * time.Second) @@ -197,7 +197,7 @@ func TestIgnoreProbe(t *testing.T) { }() var httpHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { - c.Inc() + c.Add(1) <-resp if !netheader.IsKubeletProbe(r) { t.Error("Request was not a probe") diff --git a/pkg/queue/health/probe_test.go b/pkg/queue/health/probe_test.go index 3afbbc73eb04..9f36bcdf8788 100644 --- a/pkg/queue/health/probe_test.go +++ b/pkg/queue/health/probe_test.go @@ -23,11 +23,11 @@ import ( "net/http/httptest" "net/url" "strings" + "sync/atomic" "testing" "time" "github.com/google/go-cmp/cmp" - "go.uber.org/atomic" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "google.golang.org/grpc" @@ -125,7 +125,7 @@ func TestHTTPProbeNoAutoHTTP2IfDisabled(t *testing.T) { var callCount atomic.Int32 server := newH2cTestServer(t, func(w http.ResponseWriter, r *http.Request) { - count := callCount.Inc() + count := callCount.Add(1) if count == 1 { // This is the h2c handshake, we won't do anything. for key, value := range h2cHeaders { @@ -165,7 +165,7 @@ func TestHTTPProbeAutoHTTP2(t *testing.T) { var callCount atomic.Int32 server := newH2cTestServer(t, func(w http.ResponseWriter, r *http.Request) { - count := callCount.Inc() + count := callCount.Add(1) if count == 1 { // This is the h2c handshake, we won't do anything. for key, value := range h2cHeaders { diff --git a/pkg/queue/protobuf_stats_reporter.go b/pkg/queue/protobuf_stats_reporter.go index 3117b1b3ac2c..5326894b7cdd 100644 --- a/pkg/queue/protobuf_stats_reporter.go +++ b/pkg/queue/protobuf_stats_reporter.go @@ -18,10 +18,9 @@ package queue import ( "net/http" + "sync/atomic" "time" - "go.uber.org/atomic" - "github.com/gogo/protobuf/proto" netheader "knative.dev/networking/pkg/http/header" diff --git a/pkg/queue/readiness/probe_test.go b/pkg/queue/readiness/probe_test.go index 1d5c385fe9f0..67307e881392 100644 --- a/pkg/queue/readiness/probe_test.go +++ b/pkg/queue/readiness/probe_test.go @@ -26,11 +26,11 @@ import ( "net/http/httptest" "net/url" "strings" + "sync/atomic" "testing" "time" "github.com/google/go-cmp/cmp" - "go.uber.org/atomic" "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.org/grpc/health/grpc_health_v1" @@ -115,7 +115,7 @@ func TestAggressiveFailureNotLoggedOnSuccess(t *testing.T) { tsURL := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { // Fail a few times before succeeding to ensure no failures are // misleadingly logged as long as we eventually succeed. - if polled.Inc() > 3 { + if polled.Add(1) > 3 { w.WriteHeader(http.StatusOK) return } @@ -271,7 +271,7 @@ func TestHTTPSuccess(t *testing.T) { func TestHTTPManyParallel(t *testing.T) { var count atomic.Int32 tsURL := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { - if count.Inc() == 1 { + if count.Add(1) == 1 { // Add a small amount of work to allow the requests below to collapse into one. time.Sleep(200 * time.Millisecond) } @@ -488,7 +488,7 @@ func TestKnHTTPSuccessWithRetry(t *testing.T) { var count atomic.Int32 tsURL := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { // Fail the very first request. - if count.Inc() == 1 { + if count.Add(1) == 1 { w.WriteHeader(http.StatusBadRequest) return } @@ -519,7 +519,7 @@ func TestKnHTTPSuccessWithThreshold(t *testing.T) { var count atomic.Int32 tsURL := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { - count.Inc() + count.Add(1) w.WriteHeader(http.StatusOK) }) @@ -552,7 +552,7 @@ func TestKnHTTPSuccessWithThresholdAndFailure(t *testing.T) { var count atomic.Int32 tsURL := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { - if count.Inc() == requestFailure { + if count.Add(1) == requestFailure { w.WriteHeader(http.StatusBadRequest) return } diff --git a/pkg/reconciler/autoscaling/kpa/kpa_test.go b/pkg/reconciler/autoscaling/kpa/kpa_test.go index e4df8601e893..a523e2e3cdaf 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa_test.go +++ b/pkg/reconciler/autoscaling/kpa/kpa_test.go @@ -23,6 +23,7 @@ import ( "net/http" "strconv" "sync" + "sync/atomic" "testing" "time" @@ -58,7 +59,6 @@ import ( "github.com/google/go-cmp/cmp" "go.opencensus.io/resource" - "go.uber.org/atomic" "golang.org/x/sync/errgroup" nv1a1 "knative.dev/networking/pkg/apis/networking/v1alpha1" @@ -1677,27 +1677,23 @@ func pollDeciders(deciders *testDeciders, namespace, name string, cond func(*sca func newTestDeciders() *testDeciders { return &testDeciders{ - createCallCount: atomic.NewUint32(0), - createCall: make(chan struct{}, 1), - deleteCallCount: atomic.NewUint32(0), - deleteCall: make(chan struct{}, 5), - updateCallCount: atomic.NewUint32(0), - updateCall: make(chan struct{}, 1), - deleteBeforeCreate: atomic.NewBool(false), + createCall: make(chan struct{}, 1), + deleteCall: make(chan struct{}, 5), + updateCall: make(chan struct{}, 1), } } type testDeciders struct { - createCallCount *atomic.Uint32 + createCallCount atomic.Uint32 createCall chan struct{} - deleteCallCount *atomic.Uint32 + deleteCallCount atomic.Uint32 deleteCall chan struct{} - updateCallCount *atomic.Uint32 + updateCallCount atomic.Uint32 updateCall chan struct{} - deleteBeforeCreate *atomic.Bool + deleteBeforeCreate atomic.Bool decider *scaling.Decider mutex sync.Mutex } diff --git a/pkg/reconciler/certificate/config/cert_manager.go b/pkg/reconciler/certificate/config/cert_manager.go index 158f4b51e347..4e4b1eedafa2 100644 --- a/pkg/reconciler/certificate/config/cert_manager.go +++ b/pkg/reconciler/certificate/config/cert_manager.go @@ -17,10 +17,9 @@ limitations under the License. package config import ( - "github.com/ghodss/yaml" - cmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1" corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/yaml" ) const ( diff --git a/pkg/reconciler/metric/metric_test.go b/pkg/reconciler/metric/metric_test.go index 9f920931728a..e052aaaa7fd5 100644 --- a/pkg/reconciler/metric/metric_test.go +++ b/pkg/reconciler/metric/metric_test.go @@ -19,10 +19,10 @@ package metric import ( "context" "errors" + "sync/atomic" "testing" "time" - "go.uber.org/atomic" "golang.org/x/sync/errgroup" corev1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" @@ -270,12 +270,12 @@ type testCollector struct { } func (c *testCollector) CreateOrUpdate(metric *autoscalingv1alpha1.Metric) error { - c.createOrUpdateCalls.Inc() + c.createOrUpdateCalls.Add(1) return c.createOrUpdateError } func (c *testCollector) Delete(namespace, name string) { - c.deleteCalls.Inc() + c.deleteCalls.Add(1) } func (c *testCollector) Watch(func(types.NamespacedName)) {} diff --git a/test/prober.go b/test/prober.go index b70e77ce2b59..d1d254fa9400 100644 --- a/test/prober.go +++ b/test/prober.go @@ -24,10 +24,9 @@ import ( "net/http" "net/url" "sync" + "sync/atomic" "testing" - "go.uber.org/atomic" - "golang.org/x/sync/errgroup" pkgTest "knative.dev/pkg/test" "knative.dev/pkg/test/logging" @@ -162,16 +161,16 @@ func (m *manager) Spawn(url *url.URL) Prober { return nil default: res, err := client.Do(req) - if p.requests.Inc() == p.minimumProbes { + if p.requests.Add(1) == p.minimumProbes { close(p.minDoneCh) } if err != nil { p.logf("%q error: %v", p.url, err) - p.failures.Inc() + p.failures.Add(1) } else if res.StatusCode != http.StatusOK { p.logf("%q status = %d, want: %d", p.url, res.StatusCode, http.StatusOK) p.logf("response: %s", res) - p.failures.Inc() + p.failures.Add(1) } } } diff --git a/test/test_images/singlethreaded/main.go b/test/test_images/singlethreaded/main.go index 2ed3b258a559..4f08720e63b6 100644 --- a/test/test_images/singlethreaded/main.go +++ b/test/test_images/singlethreaded/main.go @@ -20,14 +20,13 @@ package main import ( "fmt" "net/http" + "sync/atomic" "time" - "go.uber.org/atomic" - "knative.dev/serving/test" ) -var isLocked = atomic.NewBool(false) +var isLocked atomic.Bool func handler(w http.ResponseWriter, r *http.Request) { if isLocked.CompareAndSwap(false /*was unlocked*/, true /*lock*/) { @@ -41,5 +40,6 @@ func handler(w http.ResponseWriter, r *http.Request) { } func main() { + isLocked.Store(false) test.ListenAndServeGracefully(":8080", handler) } diff --git a/vendor/github.com/ghodss/yaml/.gitignore b/vendor/github.com/ghodss/yaml/.gitignore deleted file mode 100644 index e256a31e00a5..000000000000 --- a/vendor/github.com/ghodss/yaml/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# OSX leaves these everywhere on SMB shares -._* - -# Eclipse files -.classpath -.project -.settings/** - -# Emacs save files -*~ - -# Vim-related files -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist - -# Go test binaries -*.test diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml deleted file mode 100644 index 0e9d6edc010a..000000000000 --- a/vendor/github.com/ghodss/yaml/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.3 - - 1.4 -script: - - go test - - go build diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE deleted file mode 100644 index 7805d36de730..000000000000 --- a/vendor/github.com/ghodss/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b4d12..000000000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go deleted file mode 100644 index 58600740266c..000000000000 --- a/vendor/github.com/ghodss/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go deleted file mode 100644 index 4fb4054a8b74..000000000000 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ /dev/null @@ -1,277 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - - "gopkg.in/yaml.v2" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// Converts YAML to JSON then uses JSON to unmarshal into an object. -func Unmarshal(y []byte, o interface{}) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = json.Unmarshal(j, o) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through -// this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yaml.Unmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/go.uber.org/atomic/.codecov.yml b/vendor/go.uber.org/atomic/.codecov.yml deleted file mode 100644 index 571116cc39c6..000000000000 --- a/vendor/go.uber.org/atomic/.codecov.yml +++ /dev/null @@ -1,19 +0,0 @@ -coverage: - range: 80..100 - round: down - precision: 2 - - status: - project: # measuring the overall project coverage - default: # context, you can create multiple ones with custom titles - enabled: yes # must be yes|true to enable this status - target: 100 # specify the target coverage for each commit status - # option: "auto" (must increase from parent commit or pull request base) - # option: "X%" a static target percentage to hit - if_not_found: success # if parent is not found report status as success, error, or failure - if_ci_failed: error # if ci fails report status as success, error, or failure - -# Also update COVER_IGNORE_PKGS in the Makefile. -ignore: - - /internal/gen-atomicint/ - - /internal/gen-valuewrapper/ diff --git a/vendor/go.uber.org/atomic/.gitignore b/vendor/go.uber.org/atomic/.gitignore deleted file mode 100644 index 2e337a0ed529..000000000000 --- a/vendor/go.uber.org/atomic/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -/bin -.DS_Store -/vendor -cover.html -cover.out -lint.log - -# Binaries -*.test - -# Profiling output -*.prof - -# Output of fossa analyzer -/fossa diff --git a/vendor/go.uber.org/atomic/CHANGELOG.md b/vendor/go.uber.org/atomic/CHANGELOG.md deleted file mode 100644 index 5fe03f21bd3d..000000000000 --- a/vendor/go.uber.org/atomic/CHANGELOG.md +++ /dev/null @@ -1,117 +0,0 @@ -# Changelog -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [1.10.0] - 2022-08-11 -### Added -- Add `atomic.Float32` type for atomic operations on `float32`. -- Add `CompareAndSwap` and `Swap` methods to `atomic.String`, `atomic.Error`, - and `atomic.Value`. -- Add generic `atomic.Pointer[T]` type for atomic operations on pointers of any - type. This is present only for Go 1.18 or higher, and is a drop-in for - replacement for the standard library's `sync/atomic.Pointer` type. - -### Changed -- Deprecate `CAS` methods on all types in favor of corresponding - `CompareAndSwap` methods. - -Thanks to @eNV25 and @icpd for their contributions to this release. - -[1.10.0]: https://github.com/uber-go/atomic/compare/v1.9.0...v1.10.0 - -## [1.9.0] - 2021-07-15 -### Added -- Add `Float64.Swap` to match int atomic operations. -- Add `atomic.Time` type for atomic operations on `time.Time` values. - -[1.9.0]: https://github.com/uber-go/atomic/compare/v1.8.0...v1.9.0 - -## [1.8.0] - 2021-06-09 -### Added -- Add `atomic.Uintptr` type for atomic operations on `uintptr` values. -- Add `atomic.UnsafePointer` type for atomic operations on `unsafe.Pointer` values. - -[1.8.0]: https://github.com/uber-go/atomic/compare/v1.7.0...v1.8.0 - -## [1.7.0] - 2020-09-14 -### Added -- Support JSON serialization and deserialization of primitive atomic types. -- Support Text marshalling and unmarshalling for string atomics. - -### Changed -- Disallow incorrect comparison of atomic values in a non-atomic way. - -### Removed -- Remove dependency on `golang.org/x/{lint, tools}`. - -[1.7.0]: https://github.com/uber-go/atomic/compare/v1.6.0...v1.7.0 - -## [1.6.0] - 2020-02-24 -### Changed -- Drop library dependency on `golang.org/x/{lint, tools}`. - -[1.6.0]: https://github.com/uber-go/atomic/compare/v1.5.1...v1.6.0 - -## [1.5.1] - 2019-11-19 -- Fix bug where `Bool.CAS` and `Bool.Toggle` do work correctly together - causing `CAS` to fail even though the old value matches. - -[1.5.1]: https://github.com/uber-go/atomic/compare/v1.5.0...v1.5.1 - -## [1.5.0] - 2019-10-29 -### Changed -- With Go modules, only the `go.uber.org/atomic` import path is supported now. - If you need to use the old import path, please add a `replace` directive to - your `go.mod`. - -[1.5.0]: https://github.com/uber-go/atomic/compare/v1.4.0...v1.5.0 - -## [1.4.0] - 2019-05-01 -### Added - - Add `atomic.Error` type for atomic operations on `error` values. - -[1.4.0]: https://github.com/uber-go/atomic/compare/v1.3.2...v1.4.0 - -## [1.3.2] - 2018-05-02 -### Added -- Add `atomic.Duration` type for atomic operations on `time.Duration` values. - -[1.3.2]: https://github.com/uber-go/atomic/compare/v1.3.1...v1.3.2 - -## [1.3.1] - 2017-11-14 -### Fixed -- Revert optimization for `atomic.String.Store("")` which caused data races. - -[1.3.1]: https://github.com/uber-go/atomic/compare/v1.3.0...v1.3.1 - -## [1.3.0] - 2017-11-13 -### Added -- Add `atomic.Bool.CAS` for compare-and-swap semantics on bools. - -### Changed -- Optimize `atomic.String.Store("")` by avoiding an allocation. - -[1.3.0]: https://github.com/uber-go/atomic/compare/v1.2.0...v1.3.0 - -## [1.2.0] - 2017-04-12 -### Added -- Shadow `atomic.Value` from `sync/atomic`. - -[1.2.0]: https://github.com/uber-go/atomic/compare/v1.1.0...v1.2.0 - -## [1.1.0] - 2017-03-10 -### Added -- Add atomic `Float64` type. - -### Changed -- Support new `go.uber.org/atomic` import path. - -[1.1.0]: https://github.com/uber-go/atomic/compare/v1.0.0...v1.1.0 - -## [1.0.0] - 2016-07-18 - -- Initial release. - -[1.0.0]: https://github.com/uber-go/atomic/releases/tag/v1.0.0 diff --git a/vendor/go.uber.org/atomic/LICENSE.txt b/vendor/go.uber.org/atomic/LICENSE.txt deleted file mode 100644 index 8765c9fbc619..000000000000 --- a/vendor/go.uber.org/atomic/LICENSE.txt +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2016 Uber Technologies, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/go.uber.org/atomic/Makefile b/vendor/go.uber.org/atomic/Makefile deleted file mode 100644 index 46c945b32beb..000000000000 --- a/vendor/go.uber.org/atomic/Makefile +++ /dev/null @@ -1,79 +0,0 @@ -# Directory to place `go install`ed binaries into. -export GOBIN ?= $(shell pwd)/bin - -GOLINT = $(GOBIN)/golint -GEN_ATOMICINT = $(GOBIN)/gen-atomicint -GEN_ATOMICWRAPPER = $(GOBIN)/gen-atomicwrapper -STATICCHECK = $(GOBIN)/staticcheck - -GO_FILES ?= $(shell find . '(' -path .git -o -path vendor ')' -prune -o -name '*.go' -print) - -# Also update ignore section in .codecov.yml. -COVER_IGNORE_PKGS = \ - go.uber.org/atomic/internal/gen-atomicint \ - go.uber.org/atomic/internal/gen-atomicwrapper - -.PHONY: build -build: - go build ./... - -.PHONY: test -test: - go test -race ./... - -.PHONY: gofmt -gofmt: - $(eval FMT_LOG := $(shell mktemp -t gofmt.XXXXX)) - gofmt -e -s -l $(GO_FILES) > $(FMT_LOG) || true - @[ ! -s "$(FMT_LOG)" ] || (echo "gofmt failed:" && cat $(FMT_LOG) && false) - -$(GOLINT): - cd tools && go install golang.org/x/lint/golint - -$(STATICCHECK): - cd tools && go install honnef.co/go/tools/cmd/staticcheck - -$(GEN_ATOMICWRAPPER): $(wildcard ./internal/gen-atomicwrapper/*) - go build -o $@ ./internal/gen-atomicwrapper - -$(GEN_ATOMICINT): $(wildcard ./internal/gen-atomicint/*) - go build -o $@ ./internal/gen-atomicint - -.PHONY: golint -golint: $(GOLINT) - $(GOLINT) ./... - -.PHONY: staticcheck -staticcheck: $(STATICCHECK) - $(STATICCHECK) ./... - -.PHONY: lint -lint: gofmt golint staticcheck generatenodirty - -# comma separated list of packages to consider for code coverage. -COVER_PKG = $(shell \ - go list -find ./... | \ - grep -v $(foreach pkg,$(COVER_IGNORE_PKGS),-e "^$(pkg)$$") | \ - paste -sd, -) - -.PHONY: cover -cover: - go test -coverprofile=cover.out -coverpkg $(COVER_PKG) -v ./... - go tool cover -html=cover.out -o cover.html - -.PHONY: generate -generate: $(GEN_ATOMICINT) $(GEN_ATOMICWRAPPER) - go generate ./... - -.PHONY: generatenodirty -generatenodirty: - @[ -z "$$(git status --porcelain)" ] || ( \ - echo "Working tree is dirty. Commit your changes first."; \ - git status; \ - exit 1 ) - @make generate - @status=$$(git status --porcelain); \ - [ -z "$$status" ] || ( \ - echo "Working tree is dirty after `make generate`:"; \ - echo "$$status"; \ - echo "Please ensure that the generated code is up-to-date." ) diff --git a/vendor/go.uber.org/atomic/README.md b/vendor/go.uber.org/atomic/README.md deleted file mode 100644 index 96b47a1f12d3..000000000000 --- a/vendor/go.uber.org/atomic/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# atomic [![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] [![Go Report Card][reportcard-img]][reportcard] - -Simple wrappers for primitive types to enforce atomic access. - -## Installation - -```shell -$ go get -u go.uber.org/atomic@v1 -``` - -### Legacy Import Path - -As of v1.5.0, the import path `go.uber.org/atomic` is the only supported way -of using this package. If you are using Go modules, this package will fail to -compile with the legacy import path path `github.com/uber-go/atomic`. - -We recommend migrating your code to the new import path but if you're unable -to do so, or if your dependencies are still using the old import path, you -will have to add a `replace` directive to your `go.mod` file downgrading the -legacy import path to an older version. - -``` -replace github.com/uber-go/atomic => github.com/uber-go/atomic v1.4.0 -``` - -You can do so automatically by running the following command. - -```shell -$ go mod edit -replace github.com/uber-go/atomic=github.com/uber-go/atomic@v1.4.0 -``` - -## Usage - -The standard library's `sync/atomic` is powerful, but it's easy to forget which -variables must be accessed atomically. `go.uber.org/atomic` preserves all the -functionality of the standard library, but wraps the primitive types to -provide a safer, more convenient API. - -```go -var atom atomic.Uint32 -atom.Store(42) -atom.Sub(2) -atom.CAS(40, 11) -``` - -See the [documentation][doc] for a complete API specification. - -## Development Status - -Stable. - ---- - -Released under the [MIT License](LICENSE.txt). - -[doc-img]: https://godoc.org/github.com/uber-go/atomic?status.svg -[doc]: https://godoc.org/go.uber.org/atomic -[ci-img]: https://github.com/uber-go/atomic/actions/workflows/go.yml/badge.svg -[ci]: https://github.com/uber-go/atomic/actions/workflows/go.yml -[cov-img]: https://codecov.io/gh/uber-go/atomic/branch/master/graph/badge.svg -[cov]: https://codecov.io/gh/uber-go/atomic -[reportcard-img]: https://goreportcard.com/badge/go.uber.org/atomic -[reportcard]: https://goreportcard.com/report/go.uber.org/atomic diff --git a/vendor/go.uber.org/atomic/bool.go b/vendor/go.uber.org/atomic/bool.go deleted file mode 100644 index dfa2085f491d..000000000000 --- a/vendor/go.uber.org/atomic/bool.go +++ /dev/null @@ -1,88 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" -) - -// Bool is an atomic type-safe wrapper for bool values. -type Bool struct { - _ nocmp // disallow non-atomic comparison - - v Uint32 -} - -var _zeroBool bool - -// NewBool creates a new Bool. -func NewBool(val bool) *Bool { - x := &Bool{} - if val != _zeroBool { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped bool. -func (x *Bool) Load() bool { - return truthy(x.v.Load()) -} - -// Store atomically stores the passed bool. -func (x *Bool) Store(val bool) { - x.v.Store(boolToInt(val)) -} - -// CAS is an atomic compare-and-swap for bool values. -// -// Deprecated: Use CompareAndSwap. -func (x *Bool) CAS(old, new bool) (swapped bool) { - return x.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap for bool values. -func (x *Bool) CompareAndSwap(old, new bool) (swapped bool) { - return x.v.CompareAndSwap(boolToInt(old), boolToInt(new)) -} - -// Swap atomically stores the given bool and returns the old -// value. -func (x *Bool) Swap(val bool) (old bool) { - return truthy(x.v.Swap(boolToInt(val))) -} - -// MarshalJSON encodes the wrapped bool into JSON. -func (x *Bool) MarshalJSON() ([]byte, error) { - return json.Marshal(x.Load()) -} - -// UnmarshalJSON decodes a bool from JSON. -func (x *Bool) UnmarshalJSON(b []byte) error { - var v bool - if err := json.Unmarshal(b, &v); err != nil { - return err - } - x.Store(v) - return nil -} diff --git a/vendor/go.uber.org/atomic/bool_ext.go b/vendor/go.uber.org/atomic/bool_ext.go deleted file mode 100644 index a2e60e987390..000000000000 --- a/vendor/go.uber.org/atomic/bool_ext.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "strconv" -) - -//go:generate bin/gen-atomicwrapper -name=Bool -type=bool -wrapped=Uint32 -pack=boolToInt -unpack=truthy -cas -swap -json -file=bool.go - -func truthy(n uint32) bool { - return n == 1 -} - -func boolToInt(b bool) uint32 { - if b { - return 1 - } - return 0 -} - -// Toggle atomically negates the Boolean and returns the previous value. -func (b *Bool) Toggle() (old bool) { - for { - old := b.Load() - if b.CAS(old, !old) { - return old - } - } -} - -// String encodes the wrapped value as a string. -func (b *Bool) String() string { - return strconv.FormatBool(b.Load()) -} diff --git a/vendor/go.uber.org/atomic/doc.go b/vendor/go.uber.org/atomic/doc.go deleted file mode 100644 index ae7390ee6887..000000000000 --- a/vendor/go.uber.org/atomic/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// Package atomic provides simple wrappers around numerics to enforce atomic -// access. -package atomic diff --git a/vendor/go.uber.org/atomic/duration.go b/vendor/go.uber.org/atomic/duration.go deleted file mode 100644 index 6f4157445cfb..000000000000 --- a/vendor/go.uber.org/atomic/duration.go +++ /dev/null @@ -1,89 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "time" -) - -// Duration is an atomic type-safe wrapper for time.Duration values. -type Duration struct { - _ nocmp // disallow non-atomic comparison - - v Int64 -} - -var _zeroDuration time.Duration - -// NewDuration creates a new Duration. -func NewDuration(val time.Duration) *Duration { - x := &Duration{} - if val != _zeroDuration { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped time.Duration. -func (x *Duration) Load() time.Duration { - return time.Duration(x.v.Load()) -} - -// Store atomically stores the passed time.Duration. -func (x *Duration) Store(val time.Duration) { - x.v.Store(int64(val)) -} - -// CAS is an atomic compare-and-swap for time.Duration values. -// -// Deprecated: Use CompareAndSwap. -func (x *Duration) CAS(old, new time.Duration) (swapped bool) { - return x.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap for time.Duration values. -func (x *Duration) CompareAndSwap(old, new time.Duration) (swapped bool) { - return x.v.CompareAndSwap(int64(old), int64(new)) -} - -// Swap atomically stores the given time.Duration and returns the old -// value. -func (x *Duration) Swap(val time.Duration) (old time.Duration) { - return time.Duration(x.v.Swap(int64(val))) -} - -// MarshalJSON encodes the wrapped time.Duration into JSON. -func (x *Duration) MarshalJSON() ([]byte, error) { - return json.Marshal(x.Load()) -} - -// UnmarshalJSON decodes a time.Duration from JSON. -func (x *Duration) UnmarshalJSON(b []byte) error { - var v time.Duration - if err := json.Unmarshal(b, &v); err != nil { - return err - } - x.Store(v) - return nil -} diff --git a/vendor/go.uber.org/atomic/duration_ext.go b/vendor/go.uber.org/atomic/duration_ext.go deleted file mode 100644 index 4c18b0a9ed42..000000000000 --- a/vendor/go.uber.org/atomic/duration_ext.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import "time" - -//go:generate bin/gen-atomicwrapper -name=Duration -type=time.Duration -wrapped=Int64 -pack=int64 -unpack=time.Duration -cas -swap -json -imports time -file=duration.go - -// Add atomically adds to the wrapped time.Duration and returns the new value. -func (d *Duration) Add(delta time.Duration) time.Duration { - return time.Duration(d.v.Add(int64(delta))) -} - -// Sub atomically subtracts from the wrapped time.Duration and returns the new value. -func (d *Duration) Sub(delta time.Duration) time.Duration { - return time.Duration(d.v.Sub(int64(delta))) -} - -// String encodes the wrapped value as a string. -func (d *Duration) String() string { - return d.Load().String() -} diff --git a/vendor/go.uber.org/atomic/error.go b/vendor/go.uber.org/atomic/error.go deleted file mode 100644 index 27b23ea16282..000000000000 --- a/vendor/go.uber.org/atomic/error.go +++ /dev/null @@ -1,62 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -// Error is an atomic type-safe wrapper for error values. -type Error struct { - _ nocmp // disallow non-atomic comparison - - v Value -} - -var _zeroError error - -// NewError creates a new Error. -func NewError(val error) *Error { - x := &Error{} - if val != _zeroError { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped error. -func (x *Error) Load() error { - return unpackError(x.v.Load()) -} - -// Store atomically stores the passed error. -func (x *Error) Store(val error) { - x.v.Store(packError(val)) -} - -// CompareAndSwap is an atomic compare-and-swap for error values. -func (x *Error) CompareAndSwap(old, new error) (swapped bool) { - return x.v.CompareAndSwap(packError(old), packError(new)) -} - -// Swap atomically stores the given error and returns the old -// value. -func (x *Error) Swap(val error) (old error) { - return unpackError(x.v.Swap(packError(val))) -} diff --git a/vendor/go.uber.org/atomic/error_ext.go b/vendor/go.uber.org/atomic/error_ext.go deleted file mode 100644 index d31fb633bb63..000000000000 --- a/vendor/go.uber.org/atomic/error_ext.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -// atomic.Value panics on nil inputs, or if the underlying type changes. -// Stabilize by always storing a custom struct that we control. - -//go:generate bin/gen-atomicwrapper -name=Error -type=error -wrapped=Value -pack=packError -unpack=unpackError -compareandswap -swap -file=error.go - -type packedError struct{ Value error } - -func packError(v error) interface{} { - return packedError{v} -} - -func unpackError(v interface{}) error { - if err, ok := v.(packedError); ok { - return err.Value - } - return nil -} diff --git a/vendor/go.uber.org/atomic/float32.go b/vendor/go.uber.org/atomic/float32.go deleted file mode 100644 index 5d535a6d2acf..000000000000 --- a/vendor/go.uber.org/atomic/float32.go +++ /dev/null @@ -1,77 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "math" -) - -// Float32 is an atomic type-safe wrapper for float32 values. -type Float32 struct { - _ nocmp // disallow non-atomic comparison - - v Uint32 -} - -var _zeroFloat32 float32 - -// NewFloat32 creates a new Float32. -func NewFloat32(val float32) *Float32 { - x := &Float32{} - if val != _zeroFloat32 { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped float32. -func (x *Float32) Load() float32 { - return math.Float32frombits(x.v.Load()) -} - -// Store atomically stores the passed float32. -func (x *Float32) Store(val float32) { - x.v.Store(math.Float32bits(val)) -} - -// Swap atomically stores the given float32 and returns the old -// value. -func (x *Float32) Swap(val float32) (old float32) { - return math.Float32frombits(x.v.Swap(math.Float32bits(val))) -} - -// MarshalJSON encodes the wrapped float32 into JSON. -func (x *Float32) MarshalJSON() ([]byte, error) { - return json.Marshal(x.Load()) -} - -// UnmarshalJSON decodes a float32 from JSON. -func (x *Float32) UnmarshalJSON(b []byte) error { - var v float32 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - x.Store(v) - return nil -} diff --git a/vendor/go.uber.org/atomic/float32_ext.go b/vendor/go.uber.org/atomic/float32_ext.go deleted file mode 100644 index b0cd8d9c820a..000000000000 --- a/vendor/go.uber.org/atomic/float32_ext.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "math" - "strconv" -) - -//go:generate bin/gen-atomicwrapper -name=Float32 -type=float32 -wrapped=Uint32 -pack=math.Float32bits -unpack=math.Float32frombits -swap -json -imports math -file=float32.go - -// Add atomically adds to the wrapped float32 and returns the new value. -func (f *Float32) Add(delta float32) float32 { - for { - old := f.Load() - new := old + delta - if f.CAS(old, new) { - return new - } - } -} - -// Sub atomically subtracts from the wrapped float32 and returns the new value. -func (f *Float32) Sub(delta float32) float32 { - return f.Add(-delta) -} - -// CAS is an atomic compare-and-swap for float32 values. -// -// Deprecated: Use CompareAndSwap -func (f *Float32) CAS(old, new float32) (swapped bool) { - return f.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap for float32 values. -// -// Note: CompareAndSwap handles NaN incorrectly. NaN != NaN using Go's inbuilt operators -// but CompareAndSwap allows a stored NaN to compare equal to a passed in NaN. -// This avoids typical CompareAndSwap loops from blocking forever, e.g., -// -// for { -// old := atom.Load() -// new = f(old) -// if atom.CompareAndSwap(old, new) { -// break -// } -// } -// -// If CompareAndSwap did not match NaN to match, then the above would loop forever. -func (f *Float32) CompareAndSwap(old, new float32) (swapped bool) { - return f.v.CompareAndSwap(math.Float32bits(old), math.Float32bits(new)) -} - -// String encodes the wrapped value as a string. -func (f *Float32) String() string { - // 'g' is the behavior for floats with %v. - return strconv.FormatFloat(float64(f.Load()), 'g', -1, 32) -} diff --git a/vendor/go.uber.org/atomic/float64.go b/vendor/go.uber.org/atomic/float64.go deleted file mode 100644 index 11d5189a5f29..000000000000 --- a/vendor/go.uber.org/atomic/float64.go +++ /dev/null @@ -1,77 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "math" -) - -// Float64 is an atomic type-safe wrapper for float64 values. -type Float64 struct { - _ nocmp // disallow non-atomic comparison - - v Uint64 -} - -var _zeroFloat64 float64 - -// NewFloat64 creates a new Float64. -func NewFloat64(val float64) *Float64 { - x := &Float64{} - if val != _zeroFloat64 { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped float64. -func (x *Float64) Load() float64 { - return math.Float64frombits(x.v.Load()) -} - -// Store atomically stores the passed float64. -func (x *Float64) Store(val float64) { - x.v.Store(math.Float64bits(val)) -} - -// Swap atomically stores the given float64 and returns the old -// value. -func (x *Float64) Swap(val float64) (old float64) { - return math.Float64frombits(x.v.Swap(math.Float64bits(val))) -} - -// MarshalJSON encodes the wrapped float64 into JSON. -func (x *Float64) MarshalJSON() ([]byte, error) { - return json.Marshal(x.Load()) -} - -// UnmarshalJSON decodes a float64 from JSON. -func (x *Float64) UnmarshalJSON(b []byte) error { - var v float64 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - x.Store(v) - return nil -} diff --git a/vendor/go.uber.org/atomic/float64_ext.go b/vendor/go.uber.org/atomic/float64_ext.go deleted file mode 100644 index 48c52b0abf66..000000000000 --- a/vendor/go.uber.org/atomic/float64_ext.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "math" - "strconv" -) - -//go:generate bin/gen-atomicwrapper -name=Float64 -type=float64 -wrapped=Uint64 -pack=math.Float64bits -unpack=math.Float64frombits -swap -json -imports math -file=float64.go - -// Add atomically adds to the wrapped float64 and returns the new value. -func (f *Float64) Add(delta float64) float64 { - for { - old := f.Load() - new := old + delta - if f.CAS(old, new) { - return new - } - } -} - -// Sub atomically subtracts from the wrapped float64 and returns the new value. -func (f *Float64) Sub(delta float64) float64 { - return f.Add(-delta) -} - -// CAS is an atomic compare-and-swap for float64 values. -// -// Deprecated: Use CompareAndSwap -func (f *Float64) CAS(old, new float64) (swapped bool) { - return f.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap for float64 values. -// -// Note: CompareAndSwap handles NaN incorrectly. NaN != NaN using Go's inbuilt operators -// but CompareAndSwap allows a stored NaN to compare equal to a passed in NaN. -// This avoids typical CompareAndSwap loops from blocking forever, e.g., -// -// for { -// old := atom.Load() -// new = f(old) -// if atom.CompareAndSwap(old, new) { -// break -// } -// } -// -// If CompareAndSwap did not match NaN to match, then the above would loop forever. -func (f *Float64) CompareAndSwap(old, new float64) (swapped bool) { - return f.v.CompareAndSwap(math.Float64bits(old), math.Float64bits(new)) -} - -// String encodes the wrapped value as a string. -func (f *Float64) String() string { - // 'g' is the behavior for floats with %v. - return strconv.FormatFloat(f.Load(), 'g', -1, 64) -} diff --git a/vendor/go.uber.org/atomic/gen.go b/vendor/go.uber.org/atomic/gen.go deleted file mode 100644 index 1e9ef4f879c3..000000000000 --- a/vendor/go.uber.org/atomic/gen.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -//go:generate bin/gen-atomicint -name=Int32 -wrapped=int32 -file=int32.go -//go:generate bin/gen-atomicint -name=Int64 -wrapped=int64 -file=int64.go -//go:generate bin/gen-atomicint -name=Uint32 -wrapped=uint32 -unsigned -file=uint32.go -//go:generate bin/gen-atomicint -name=Uint64 -wrapped=uint64 -unsigned -file=uint64.go -//go:generate bin/gen-atomicint -name=Uintptr -wrapped=uintptr -unsigned -file=uintptr.go diff --git a/vendor/go.uber.org/atomic/int32.go b/vendor/go.uber.org/atomic/int32.go deleted file mode 100644 index b9a68f42ca84..000000000000 --- a/vendor/go.uber.org/atomic/int32.go +++ /dev/null @@ -1,109 +0,0 @@ -// @generated Code generated by gen-atomicint. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "strconv" - "sync/atomic" -) - -// Int32 is an atomic wrapper around int32. -type Int32 struct { - _ nocmp // disallow non-atomic comparison - - v int32 -} - -// NewInt32 creates a new Int32. -func NewInt32(val int32) *Int32 { - return &Int32{v: val} -} - -// Load atomically loads the wrapped value. -func (i *Int32) Load() int32 { - return atomic.LoadInt32(&i.v) -} - -// Add atomically adds to the wrapped int32 and returns the new value. -func (i *Int32) Add(delta int32) int32 { - return atomic.AddInt32(&i.v, delta) -} - -// Sub atomically subtracts from the wrapped int32 and returns the new value. -func (i *Int32) Sub(delta int32) int32 { - return atomic.AddInt32(&i.v, -delta) -} - -// Inc atomically increments the wrapped int32 and returns the new value. -func (i *Int32) Inc() int32 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped int32 and returns the new value. -func (i *Int32) Dec() int32 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap. -func (i *Int32) CAS(old, new int32) (swapped bool) { - return i.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (i *Int32) CompareAndSwap(old, new int32) (swapped bool) { - return atomic.CompareAndSwapInt32(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Int32) Store(val int32) { - atomic.StoreInt32(&i.v, val) -} - -// Swap atomically swaps the wrapped int32 and returns the old value. -func (i *Int32) Swap(val int32) (old int32) { - return atomic.SwapInt32(&i.v, val) -} - -// MarshalJSON encodes the wrapped int32 into JSON. -func (i *Int32) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Load()) -} - -// UnmarshalJSON decodes JSON into the wrapped int32. -func (i *Int32) UnmarshalJSON(b []byte) error { - var v int32 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - i.Store(v) - return nil -} - -// String encodes the wrapped value as a string. -func (i *Int32) String() string { - v := i.Load() - return strconv.FormatInt(int64(v), 10) -} diff --git a/vendor/go.uber.org/atomic/int64.go b/vendor/go.uber.org/atomic/int64.go deleted file mode 100644 index 78d260976fcf..000000000000 --- a/vendor/go.uber.org/atomic/int64.go +++ /dev/null @@ -1,109 +0,0 @@ -// @generated Code generated by gen-atomicint. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "strconv" - "sync/atomic" -) - -// Int64 is an atomic wrapper around int64. -type Int64 struct { - _ nocmp // disallow non-atomic comparison - - v int64 -} - -// NewInt64 creates a new Int64. -func NewInt64(val int64) *Int64 { - return &Int64{v: val} -} - -// Load atomically loads the wrapped value. -func (i *Int64) Load() int64 { - return atomic.LoadInt64(&i.v) -} - -// Add atomically adds to the wrapped int64 and returns the new value. -func (i *Int64) Add(delta int64) int64 { - return atomic.AddInt64(&i.v, delta) -} - -// Sub atomically subtracts from the wrapped int64 and returns the new value. -func (i *Int64) Sub(delta int64) int64 { - return atomic.AddInt64(&i.v, -delta) -} - -// Inc atomically increments the wrapped int64 and returns the new value. -func (i *Int64) Inc() int64 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped int64 and returns the new value. -func (i *Int64) Dec() int64 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap. -func (i *Int64) CAS(old, new int64) (swapped bool) { - return i.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (i *Int64) CompareAndSwap(old, new int64) (swapped bool) { - return atomic.CompareAndSwapInt64(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Int64) Store(val int64) { - atomic.StoreInt64(&i.v, val) -} - -// Swap atomically swaps the wrapped int64 and returns the old value. -func (i *Int64) Swap(val int64) (old int64) { - return atomic.SwapInt64(&i.v, val) -} - -// MarshalJSON encodes the wrapped int64 into JSON. -func (i *Int64) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Load()) -} - -// UnmarshalJSON decodes JSON into the wrapped int64. -func (i *Int64) UnmarshalJSON(b []byte) error { - var v int64 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - i.Store(v) - return nil -} - -// String encodes the wrapped value as a string. -func (i *Int64) String() string { - v := i.Load() - return strconv.FormatInt(int64(v), 10) -} diff --git a/vendor/go.uber.org/atomic/nocmp.go b/vendor/go.uber.org/atomic/nocmp.go deleted file mode 100644 index 54b74174abdf..000000000000 --- a/vendor/go.uber.org/atomic/nocmp.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -// nocmp is an uncomparable struct. Embed this inside another struct to make -// it uncomparable. -// -// type Foo struct { -// nocmp -// // ... -// } -// -// This DOES NOT: -// -// - Disallow shallow copies of structs -// - Disallow comparison of pointers to uncomparable structs -type nocmp [0]func() diff --git a/vendor/go.uber.org/atomic/pointer_go118.go b/vendor/go.uber.org/atomic/pointer_go118.go deleted file mode 100644 index e0f47dba4686..000000000000 --- a/vendor/go.uber.org/atomic/pointer_go118.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -//go:build go1.18 && !go1.19 -// +build go1.18,!go1.19 - -package atomic - -import "unsafe" - -type Pointer[T any] struct { - _ nocmp // disallow non-atomic comparison - p UnsafePointer -} - -// NewPointer creates a new Pointer. -func NewPointer[T any](v *T) *Pointer[T] { - var p Pointer[T] - if v != nil { - p.p.Store(unsafe.Pointer(v)) - } - return &p -} - -// Load atomically loads the wrapped value. -func (p *Pointer[T]) Load() *T { - return (*T)(p.p.Load()) -} - -// Store atomically stores the passed value. -func (p *Pointer[T]) Store(val *T) { - p.p.Store(unsafe.Pointer(val)) -} - -// Swap atomically swaps the wrapped pointer and returns the old value. -func (p *Pointer[T]) Swap(val *T) (old *T) { - return (*T)(p.p.Swap(unsafe.Pointer(val))) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) { - return p.p.CompareAndSwap(unsafe.Pointer(old), unsafe.Pointer(new)) -} diff --git a/vendor/go.uber.org/atomic/pointer_go119.go b/vendor/go.uber.org/atomic/pointer_go119.go deleted file mode 100644 index 6726f17ad64f..000000000000 --- a/vendor/go.uber.org/atomic/pointer_go119.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -//go:build go1.19 -// +build go1.19 - -package atomic - -import "sync/atomic" - -// Pointer is an atomic pointer of type *T. -type Pointer[T any] struct { - _ nocmp // disallow non-atomic comparison - p atomic.Pointer[T] -} - -// NewPointer creates a new Pointer. -func NewPointer[T any](v *T) *Pointer[T] { - var p Pointer[T] - if v != nil { - p.p.Store(v) - } - return &p -} - -// Load atomically loads the wrapped value. -func (p *Pointer[T]) Load() *T { - return p.p.Load() -} - -// Store atomically stores the passed value. -func (p *Pointer[T]) Store(val *T) { - p.p.Store(val) -} - -// Swap atomically swaps the wrapped pointer and returns the old value. -func (p *Pointer[T]) Swap(val *T) (old *T) { - return p.p.Swap(val) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) { - return p.p.CompareAndSwap(old, new) -} diff --git a/vendor/go.uber.org/atomic/string.go b/vendor/go.uber.org/atomic/string.go deleted file mode 100644 index c4bea70f4ddf..000000000000 --- a/vendor/go.uber.org/atomic/string.go +++ /dev/null @@ -1,65 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -// String is an atomic type-safe wrapper for string values. -type String struct { - _ nocmp // disallow non-atomic comparison - - v Value -} - -var _zeroString string - -// NewString creates a new String. -func NewString(val string) *String { - x := &String{} - if val != _zeroString { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped string. -func (x *String) Load() string { - if v := x.v.Load(); v != nil { - return v.(string) - } - return _zeroString -} - -// Store atomically stores the passed string. -func (x *String) Store(val string) { - x.v.Store(val) -} - -// CompareAndSwap is an atomic compare-and-swap for string values. -func (x *String) CompareAndSwap(old, new string) (swapped bool) { - return x.v.CompareAndSwap(old, new) -} - -// Swap atomically stores the given string and returns the old -// value. -func (x *String) Swap(val string) (old string) { - return x.v.Swap(val).(string) -} diff --git a/vendor/go.uber.org/atomic/string_ext.go b/vendor/go.uber.org/atomic/string_ext.go deleted file mode 100644 index 1f63dfd5b978..000000000000 --- a/vendor/go.uber.org/atomic/string_ext.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -compareandswap -swap -file=string.go - -// String returns the wrapped value. -func (s *String) String() string { - return s.Load() -} - -// MarshalText encodes the wrapped string into a textual form. -// -// This makes it encodable as JSON, YAML, XML, and more. -func (s *String) MarshalText() ([]byte, error) { - return []byte(s.Load()), nil -} - -// UnmarshalText decodes text and replaces the wrapped string with it. -// -// This makes it decodable from JSON, YAML, XML, and more. -func (s *String) UnmarshalText(b []byte) error { - s.Store(string(b)) - return nil -} diff --git a/vendor/go.uber.org/atomic/time.go b/vendor/go.uber.org/atomic/time.go deleted file mode 100644 index 1660feb14268..000000000000 --- a/vendor/go.uber.org/atomic/time.go +++ /dev/null @@ -1,55 +0,0 @@ -// @generated Code generated by gen-atomicwrapper. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "time" -) - -// Time is an atomic type-safe wrapper for time.Time values. -type Time struct { - _ nocmp // disallow non-atomic comparison - - v Value -} - -var _zeroTime time.Time - -// NewTime creates a new Time. -func NewTime(val time.Time) *Time { - x := &Time{} - if val != _zeroTime { - x.Store(val) - } - return x -} - -// Load atomically loads the wrapped time.Time. -func (x *Time) Load() time.Time { - return unpackTime(x.v.Load()) -} - -// Store atomically stores the passed time.Time. -func (x *Time) Store(val time.Time) { - x.v.Store(packTime(val)) -} diff --git a/vendor/go.uber.org/atomic/time_ext.go b/vendor/go.uber.org/atomic/time_ext.go deleted file mode 100644 index 1e3dc978aa55..000000000000 --- a/vendor/go.uber.org/atomic/time_ext.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2021 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import "time" - -//go:generate bin/gen-atomicwrapper -name=Time -type=time.Time -wrapped=Value -pack=packTime -unpack=unpackTime -imports time -file=time.go - -func packTime(t time.Time) interface{} { - return t -} - -func unpackTime(v interface{}) time.Time { - if t, ok := v.(time.Time); ok { - return t - } - return time.Time{} -} diff --git a/vendor/go.uber.org/atomic/uint32.go b/vendor/go.uber.org/atomic/uint32.go deleted file mode 100644 index d6f04a96dc38..000000000000 --- a/vendor/go.uber.org/atomic/uint32.go +++ /dev/null @@ -1,109 +0,0 @@ -// @generated Code generated by gen-atomicint. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "strconv" - "sync/atomic" -) - -// Uint32 is an atomic wrapper around uint32. -type Uint32 struct { - _ nocmp // disallow non-atomic comparison - - v uint32 -} - -// NewUint32 creates a new Uint32. -func NewUint32(val uint32) *Uint32 { - return &Uint32{v: val} -} - -// Load atomically loads the wrapped value. -func (i *Uint32) Load() uint32 { - return atomic.LoadUint32(&i.v) -} - -// Add atomically adds to the wrapped uint32 and returns the new value. -func (i *Uint32) Add(delta uint32) uint32 { - return atomic.AddUint32(&i.v, delta) -} - -// Sub atomically subtracts from the wrapped uint32 and returns the new value. -func (i *Uint32) Sub(delta uint32) uint32 { - return atomic.AddUint32(&i.v, ^(delta - 1)) -} - -// Inc atomically increments the wrapped uint32 and returns the new value. -func (i *Uint32) Inc() uint32 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped uint32 and returns the new value. -func (i *Uint32) Dec() uint32 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap. -func (i *Uint32) CAS(old, new uint32) (swapped bool) { - return i.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (i *Uint32) CompareAndSwap(old, new uint32) (swapped bool) { - return atomic.CompareAndSwapUint32(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Uint32) Store(val uint32) { - atomic.StoreUint32(&i.v, val) -} - -// Swap atomically swaps the wrapped uint32 and returns the old value. -func (i *Uint32) Swap(val uint32) (old uint32) { - return atomic.SwapUint32(&i.v, val) -} - -// MarshalJSON encodes the wrapped uint32 into JSON. -func (i *Uint32) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Load()) -} - -// UnmarshalJSON decodes JSON into the wrapped uint32. -func (i *Uint32) UnmarshalJSON(b []byte) error { - var v uint32 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - i.Store(v) - return nil -} - -// String encodes the wrapped value as a string. -func (i *Uint32) String() string { - v := i.Load() - return strconv.FormatUint(uint64(v), 10) -} diff --git a/vendor/go.uber.org/atomic/uint64.go b/vendor/go.uber.org/atomic/uint64.go deleted file mode 100644 index 2574bdd5ec4a..000000000000 --- a/vendor/go.uber.org/atomic/uint64.go +++ /dev/null @@ -1,109 +0,0 @@ -// @generated Code generated by gen-atomicint. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "strconv" - "sync/atomic" -) - -// Uint64 is an atomic wrapper around uint64. -type Uint64 struct { - _ nocmp // disallow non-atomic comparison - - v uint64 -} - -// NewUint64 creates a new Uint64. -func NewUint64(val uint64) *Uint64 { - return &Uint64{v: val} -} - -// Load atomically loads the wrapped value. -func (i *Uint64) Load() uint64 { - return atomic.LoadUint64(&i.v) -} - -// Add atomically adds to the wrapped uint64 and returns the new value. -func (i *Uint64) Add(delta uint64) uint64 { - return atomic.AddUint64(&i.v, delta) -} - -// Sub atomically subtracts from the wrapped uint64 and returns the new value. -func (i *Uint64) Sub(delta uint64) uint64 { - return atomic.AddUint64(&i.v, ^(delta - 1)) -} - -// Inc atomically increments the wrapped uint64 and returns the new value. -func (i *Uint64) Inc() uint64 { - return i.Add(1) -} - -// Dec atomically decrements the wrapped uint64 and returns the new value. -func (i *Uint64) Dec() uint64 { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap. -func (i *Uint64) CAS(old, new uint64) (swapped bool) { - return i.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (i *Uint64) CompareAndSwap(old, new uint64) (swapped bool) { - return atomic.CompareAndSwapUint64(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Uint64) Store(val uint64) { - atomic.StoreUint64(&i.v, val) -} - -// Swap atomically swaps the wrapped uint64 and returns the old value. -func (i *Uint64) Swap(val uint64) (old uint64) { - return atomic.SwapUint64(&i.v, val) -} - -// MarshalJSON encodes the wrapped uint64 into JSON. -func (i *Uint64) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Load()) -} - -// UnmarshalJSON decodes JSON into the wrapped uint64. -func (i *Uint64) UnmarshalJSON(b []byte) error { - var v uint64 - if err := json.Unmarshal(b, &v); err != nil { - return err - } - i.Store(v) - return nil -} - -// String encodes the wrapped value as a string. -func (i *Uint64) String() string { - v := i.Load() - return strconv.FormatUint(uint64(v), 10) -} diff --git a/vendor/go.uber.org/atomic/uintptr.go b/vendor/go.uber.org/atomic/uintptr.go deleted file mode 100644 index 81b275a7ad5d..000000000000 --- a/vendor/go.uber.org/atomic/uintptr.go +++ /dev/null @@ -1,109 +0,0 @@ -// @generated Code generated by gen-atomicint. - -// Copyright (c) 2020-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "encoding/json" - "strconv" - "sync/atomic" -) - -// Uintptr is an atomic wrapper around uintptr. -type Uintptr struct { - _ nocmp // disallow non-atomic comparison - - v uintptr -} - -// NewUintptr creates a new Uintptr. -func NewUintptr(val uintptr) *Uintptr { - return &Uintptr{v: val} -} - -// Load atomically loads the wrapped value. -func (i *Uintptr) Load() uintptr { - return atomic.LoadUintptr(&i.v) -} - -// Add atomically adds to the wrapped uintptr and returns the new value. -func (i *Uintptr) Add(delta uintptr) uintptr { - return atomic.AddUintptr(&i.v, delta) -} - -// Sub atomically subtracts from the wrapped uintptr and returns the new value. -func (i *Uintptr) Sub(delta uintptr) uintptr { - return atomic.AddUintptr(&i.v, ^(delta - 1)) -} - -// Inc atomically increments the wrapped uintptr and returns the new value. -func (i *Uintptr) Inc() uintptr { - return i.Add(1) -} - -// Dec atomically decrements the wrapped uintptr and returns the new value. -func (i *Uintptr) Dec() uintptr { - return i.Sub(1) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap. -func (i *Uintptr) CAS(old, new uintptr) (swapped bool) { - return i.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (i *Uintptr) CompareAndSwap(old, new uintptr) (swapped bool) { - return atomic.CompareAndSwapUintptr(&i.v, old, new) -} - -// Store atomically stores the passed value. -func (i *Uintptr) Store(val uintptr) { - atomic.StoreUintptr(&i.v, val) -} - -// Swap atomically swaps the wrapped uintptr and returns the old value. -func (i *Uintptr) Swap(val uintptr) (old uintptr) { - return atomic.SwapUintptr(&i.v, val) -} - -// MarshalJSON encodes the wrapped uintptr into JSON. -func (i *Uintptr) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Load()) -} - -// UnmarshalJSON decodes JSON into the wrapped uintptr. -func (i *Uintptr) UnmarshalJSON(b []byte) error { - var v uintptr - if err := json.Unmarshal(b, &v); err != nil { - return err - } - i.Store(v) - return nil -} - -// String encodes the wrapped value as a string. -func (i *Uintptr) String() string { - v := i.Load() - return strconv.FormatUint(uint64(v), 10) -} diff --git a/vendor/go.uber.org/atomic/unsafe_pointer.go b/vendor/go.uber.org/atomic/unsafe_pointer.go deleted file mode 100644 index 34868baf6a85..000000000000 --- a/vendor/go.uber.org/atomic/unsafe_pointer.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2021-2022 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import ( - "sync/atomic" - "unsafe" -) - -// UnsafePointer is an atomic wrapper around unsafe.Pointer. -type UnsafePointer struct { - _ nocmp // disallow non-atomic comparison - - v unsafe.Pointer -} - -// NewUnsafePointer creates a new UnsafePointer. -func NewUnsafePointer(val unsafe.Pointer) *UnsafePointer { - return &UnsafePointer{v: val} -} - -// Load atomically loads the wrapped value. -func (p *UnsafePointer) Load() unsafe.Pointer { - return atomic.LoadPointer(&p.v) -} - -// Store atomically stores the passed value. -func (p *UnsafePointer) Store(val unsafe.Pointer) { - atomic.StorePointer(&p.v, val) -} - -// Swap atomically swaps the wrapped unsafe.Pointer and returns the old value. -func (p *UnsafePointer) Swap(val unsafe.Pointer) (old unsafe.Pointer) { - return atomic.SwapPointer(&p.v, val) -} - -// CAS is an atomic compare-and-swap. -// -// Deprecated: Use CompareAndSwap -func (p *UnsafePointer) CAS(old, new unsafe.Pointer) (swapped bool) { - return p.CompareAndSwap(old, new) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (p *UnsafePointer) CompareAndSwap(old, new unsafe.Pointer) (swapped bool) { - return atomic.CompareAndSwapPointer(&p.v, old, new) -} diff --git a/vendor/go.uber.org/atomic/value.go b/vendor/go.uber.org/atomic/value.go deleted file mode 100644 index 52caedb9a58f..000000000000 --- a/vendor/go.uber.org/atomic/value.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2020 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package atomic - -import "sync/atomic" - -// Value shadows the type of the same name from sync/atomic -// https://godoc.org/sync/atomic#Value -type Value struct { - _ nocmp // disallow non-atomic comparison - - atomic.Value -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 5a0690a835c7..02b96e7c4f32 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -241,9 +241,6 @@ github.com/felixge/httpsnoop # github.com/fxamacker/cbor/v2 v2.7.0 ## explicit; go 1.17 github.com/fxamacker/cbor/v2 -# github.com/ghodss/yaml v1.0.0 -## explicit -github.com/ghodss/yaml # github.com/go-kit/log v0.2.1 ## explicit; go 1.17 github.com/go-kit/log @@ -568,9 +565,6 @@ go.opentelemetry.io/otel/metric/embedded ## explicit; go 1.22 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded -# go.uber.org/atomic v1.10.0 -## explicit; go 1.18 -go.uber.org/atomic # go.uber.org/automaxprocs v1.6.0 ## explicit; go 1.20 go.uber.org/automaxprocs/internal/cgroups From 0d7e57881c40c34897ac4d4bc484e64646ad362c Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 11:56:30 -0500 Subject: [PATCH 15/35] fix nilerr linter --- pkg/autoscaler/statforwarder/forwarder_test.go | 4 ++-- pkg/autoscaler/statforwarder/leases.go | 4 ++-- pkg/queue/readiness/probe.go | 2 +- pkg/reconciler/autoscaling/kpa/kpa_test.go | 2 +- test/e2e/destroypod_test.go | 2 +- test/e2e/e2e.go | 6 +++--- test/e2e/minscale_readiness_test.go | 4 ++-- .../multicontainerprobing/multicontainer_readiness_test.go | 2 +- test/e2e/subroutes_test.go | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/pkg/autoscaler/statforwarder/forwarder_test.go b/pkg/autoscaler/statforwarder/forwarder_test.go index 6defcd279ce6..65f985afecc4 100644 --- a/pkg/autoscaler/statforwarder/forwarder_test.go +++ b/pkg/autoscaler/statforwarder/forwarder_test.go @@ -141,7 +141,7 @@ func TestForwarderReconcile(t *testing.T) { got, err := el.Get(bucket1) if err != nil { lastErr = err - return false, nil + return false, nil //nolint:nilerr } if !cmp.Equal(wantSubsets, got.Subsets) { @@ -166,7 +166,7 @@ func TestForwarderReconcile(t *testing.T) { got, err := el.Get(bucket1) if err != nil { lastErr = err - return false, nil + return false, nil //nolint:nilerr } if !cmp.Equal(wantSubsets, got.Subsets) { diff --git a/pkg/autoscaler/statforwarder/leases.go b/pkg/autoscaler/statforwarder/leases.go index 5c0e15e692fa..81bab06782c5 100644 --- a/pkg/autoscaler/statforwarder/leases.go +++ b/pkg/autoscaler/statforwarder/leases.go @@ -259,7 +259,7 @@ func (f *leaseTracker) createOrUpdateEndpoints(ctx context.Context, ns, n string if err != nil { lastErr = err // Do not return the error to cause a retry. - return false, nil + return false, nil //nolint:nilerr } if equality.Semantic.DeepEqual(wantSubsets, e.Subsets) { @@ -270,7 +270,7 @@ func (f *leaseTracker) createOrUpdateEndpoints(ctx context.Context, ns, n string want.Subsets = wantSubsets if _, lastErr = f.kc.CoreV1().Endpoints(ns).Update(ctx, want, metav1.UpdateOptions{}); lastErr != nil { // Do not return the error to cause a retry. - return false, nil + return false, nil //nolint:nilerr } f.logger.Infof("Bucket Endpoints %s updated with IP %s", n, f.selfIP) diff --git a/pkg/queue/readiness/probe.go b/pkg/queue/readiness/probe.go index 5d4566caba35..b0cca8d998a5 100644 --- a/pkg/queue/readiness/probe.go +++ b/pkg/queue/readiness/probe.go @@ -197,7 +197,7 @@ func (p *wrappedProbe) doProbe(probe func(time.Duration) error) error { // We'll log the lastProbeErr if we don't eventually succeed. lastProbeErr = err failCount++ - return false, nil + return false, nil //nolint:nilerr } p.count++ diff --git a/pkg/reconciler/autoscaling/kpa/kpa_test.go b/pkg/reconciler/autoscaling/kpa/kpa_test.go index a523e2e3cdaf..9a2ade731bfb 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa_test.go +++ b/pkg/reconciler/autoscaling/kpa/kpa_test.go @@ -1668,7 +1668,7 @@ func pollDeciders(deciders *testDeciders, namespace, name string, cond func(*sca wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 3*time.Second, true, func(context.Context) (bool, error) { decider, err = deciders.Get(context.Background(), namespace, name) if err != nil { - return false, nil + return false, nil //nolint:nilerr } return cond == nil || cond(decider), nil }) diff --git a/test/e2e/destroypod_test.go b/test/e2e/destroypod_test.go index 789be67a7911..a6d2fd6eafe0 100644 --- a/test/e2e/destroypod_test.go +++ b/test/e2e/destroypod_test.go @@ -209,7 +209,7 @@ func TestDestroyPodTimely(t *testing.T) { // The podToDelete must be deleted. return true, nil } else if err != nil { - return false, nil + return false, nil //nolint:nilerr } latestPodState = pod diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 63c2105e3613..8cb35d78630d 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -112,11 +112,11 @@ func waitForActivatorEndpoints(ctx *TestContext) error { actEps, err := ctx.clients.KubeClient.CoreV1().Endpoints( system.Namespace()).Get(context.Background(), networking.ActivatorServiceName, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } sks, err := ctx.clients.NetworkingClient.ServerlessServices.Get(context.Background(), ctx.resources.Revision.Name, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } svcEps, err := ctx.clients.KubeClient.CoreV1().Endpoints(test.ServingFlags.TestNamespace).Get( @@ -219,7 +219,7 @@ func PrivateServiceName(t *testing.T, clients *test.Clients, revision string) st if err := wait.PollUntilContextTimeout(context.Background(), time.Second, 1*time.Minute, true, func(context.Context) (bool, error) { sks, err := clients.NetworkingClient.ServerlessServices.Get(context.Background(), revision, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } privateServiceName = sks.Status.PrivateServiceName return privateServiceName != "", nil diff --git a/test/e2e/minscale_readiness_test.go b/test/e2e/minscale_readiness_test.go index d931b81a853f..95d6fb5c0e3a 100644 --- a/test/e2e/minscale_readiness_test.go +++ b/test/e2e/minscale_readiness_test.go @@ -217,7 +217,7 @@ func waitForDesiredScale(clients *test.Clients, serviceName string, cond func(in return latestReady, wait.PollUntilContextTimeout(context.Background(), 250*time.Millisecond, 3*time.Minute, true, func(context.Context) (bool, error) { endpoint, err := endpoints.Get(context.Background(), serviceName, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } latestReady = resources.ReadyAddressCount(endpoint) return cond(latestReady), nil @@ -230,7 +230,7 @@ func ensureDesiredScale(clients *test.Clients, t *testing.T, serviceName string, err := wait.PollUntilContextTimeout(context.Background(), 250*time.Millisecond, 10*time.Second, true, func(context.Context) (bool, error) { endpoint, err := endpoints.Get(context.Background(), serviceName, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } if latestReady = resources.ReadyAddressCount(endpoint); !cond(latestReady) { diff --git a/test/e2e/multicontainerprobing/multicontainer_readiness_test.go b/test/e2e/multicontainerprobing/multicontainer_readiness_test.go index 9d497105b5fd..a9d5cc2b55f2 100644 --- a/test/e2e/multicontainerprobing/multicontainer_readiness_test.go +++ b/test/e2e/multicontainerprobing/multicontainer_readiness_test.go @@ -387,7 +387,7 @@ func TestMultiContainerProbeStartFailingAfterReady(t *testing.T) { if err := wait.PollUntilContextTimeout(context.Background(), time.Second, 60*time.Second, true, func(context.Context) (bool, error) { endpoint, err := endpoints.Get(context.Background(), privateSvcName, metav1.GetOptions{}) if err != nil { - return false, nil + return false, nil //nolint:nilerr } latestReady = resources.ReadyAddressCount(endpoint) return latestReady == 0, nil diff --git a/test/e2e/subroutes_test.go b/test/e2e/subroutes_test.go index a66a42ee361d..01554d99a476 100644 --- a/test/e2e/subroutes_test.go +++ b/test/e2e/subroutes_test.go @@ -174,7 +174,7 @@ func TestSubrouteVisibilityPublicToPrivate(t *testing.T) { } // Check subroute2 is cluster local if isClusterLocal, err := isTrafficClusterLocal(r.Status.Traffic, subrouteTag2); err != nil { - return false, nil + return false, nil //nolint:nilerr } else if isClusterLocal { return false, nil } From b26986f97396d0c982175c650b5555c62f71de24 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 11:58:24 -0500 Subject: [PATCH 16/35] fix mirror linter --- pkg/reconciler/autoscaling/kpa/scaler_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/reconciler/autoscaling/kpa/scaler_test.go b/pkg/reconciler/autoscaling/kpa/scaler_test.go index 10c8503ee3b8..55045c5bac19 100644 --- a/pkg/reconciler/autoscaling/kpa/scaler_test.go +++ b/pkg/reconciler/autoscaling/kpa/scaler_test.go @@ -803,7 +803,7 @@ func TestActivatorProbe(t *testing.T) { name: "ok", rt: func(r *http.Request) (*http.Response, error) { rsp := httptest.NewRecorder() - rsp.Write([]byte(activator.Name)) + rsp.WriteString(activator.Name) return rsp.Result(), nil }, wantRes: true, @@ -812,7 +812,7 @@ func TestActivatorProbe(t *testing.T) { rt: func(r *http.Request) (*http.Response, error) { rsp := httptest.NewRecorder() rsp.Code = http.StatusBadRequest - rsp.Write([]byte("wrong header, I guess?")) + rsp.WriteString("wrong header, I guess?") return rsp.Result(), nil }, wantErr: true, @@ -820,7 +820,7 @@ func TestActivatorProbe(t *testing.T) { name: "wrong body", rt: func(r *http.Request) (*http.Response, error) { rsp := httptest.NewRecorder() - rsp.Write([]byte("haxoorprober")) + rsp.WriteString("haxoorprober") return rsp.Result(), nil }, wantErr: true, From a22fa3b9b997b31a44998a3907029d2b65ead274 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 12:03:55 -0500 Subject: [PATCH 17/35] fix loggercheck linter --- cmd/default-domain/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/default-domain/main.go b/cmd/default-domain/main.go index ec2f6f6cdd15..950005b1c833 100644 --- a/cmd/default-domain/main.go +++ b/cmd/default-domain/main.go @@ -218,7 +218,7 @@ func main() { } ipAddr, err := net.ResolveIPAddr("ip", address.Hostname) if err != nil { - logger.Fatalw("Error resolving the IP address of %q", address.Hostname, zap.Error(err)) + logger.Fatalw(fmt.Sprintf("Error resolving the IP address of %q", address.Hostname), zap.Error(err)) } ip = ipAddr.String() } From 7cdf82a0b2a91932a24be2573c9c6a18871ff656 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 12:10:36 -0500 Subject: [PATCH 18/35] fix govet linter --- pkg/activator/net/throttler_test.go | 2 +- test/e2e/autoscale.go | 4 ++-- test/e2e/subroutes_test.go | 18 +++++++++--------- .../benchmarks/dataplane-probe/main.go | 2 +- test/performance/benchmarks/load-test/main.go | 2 +- .../benchmarks/rollout-probe/main.go | 4 ++-- .../benchmarks/scale-from-zero/main.go | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index e95a8b68da06..97e4774e24dd 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -568,7 +568,7 @@ func TestThrottlerSuccesses(t *testing.T) { }); err != nil { t.Fatal("Timed out waiting for the capacity to be updated") } - t.Log("This activator idx =", rt.activatorIndex) + t.Log("This activator idx =", rt.activatorIndex.Load()) tryContext, cancel2 := context.WithTimeout(context.Background(), 1*time.Second) defer cancel2() diff --git a/test/e2e/autoscale.go b/test/e2e/autoscale.go index 668d3677033f..930d75be905c 100644 --- a/test/e2e/autoscale.go +++ b/test/e2e/autoscale.go @@ -342,7 +342,7 @@ func checkPodScale(ctx *TestContext, targetPods, minPods, maxPods float64, done } mes := fmt.Sprintf("revision %q #replicas: %v, want at least: %v", ctx.resources.Revision.Name, got, minPods) - ctx.t.Logf(mes) + ctx.t.Log(mes) // verify that the number of pods doesn't go down while we are scaling up. if got < minPods { return fmt.Errorf("interim scale didn't fulfill constraints: %s\ndeployment state: %s", mes, spew.Sdump(d)) @@ -374,7 +374,7 @@ func checkPodScale(ctx *TestContext, targetPods, minPods, maxPods float64, done } mes := fmt.Sprintf("revision %q #replicas: %v, want between [%v, %v]", ctx.resources.Revision.Name, got, targetPods-1, maxPods) - ctx.t.Logf(mes) + ctx.t.Log(mes) if got < targetPods-1 || got > maxPods { return fmt.Errorf("final scale didn't fulfill constraints: %s\ndeployment state: %s", mes, spew.Sdump(d)) } diff --git a/test/e2e/subroutes_test.go b/test/e2e/subroutes_test.go index 01554d99a476..7c5fbd2a3843 100644 --- a/test/e2e/subroutes_test.go +++ b/test/e2e/subroutes_test.go @@ -125,7 +125,7 @@ func TestSubrouteVisibilityPublicToPrivate(t *testing.T) { } if isClusterLocal, err := isTrafficClusterLocal(resources.Route.Status.Traffic, subrouteTag1); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } else if isClusterLocal { t.Fatalf("Expected subroutes with tag %s to be not cluster local", subrouteTag1) } @@ -198,12 +198,12 @@ func TestSubrouteVisibilityPublicToPrivate(t *testing.T) { clusterLocalRoute, err := clients.ServingClient.Routes.Get(context.Background(), resources.Route.Name, metav1.GetOptions{}) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } for _, tag := range []string{subrouteTag1, subrouteTag2} { if isClusterLocal, err := isTrafficClusterLocal(clusterLocalRoute.Status.Traffic, tag); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } else if !isClusterLocal { t.Fatalf("Expected subroute with tag %s to be cluster local", tag) } @@ -266,7 +266,7 @@ func TestSubrouteVisibilityPrivateToPublic(t *testing.T) { svcpatchBytes, err := duck.CreateBytePatch(svc, svcCopy) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } if _, err = clients.KubeClient.CoreV1().Services(test.ServingFlags.TestNamespace).Patch(context.Background(), serviceName, types.JSONPatchType, svcpatchBytes, metav1.PatchOptions{}); err != nil { @@ -316,19 +316,19 @@ func TestSubrouteVisibilityPrivateToPublic(t *testing.T) { publicRoute, err := clients.ServingClient.Routes.Get(context.Background(), resources.Route.Name, metav1.GetOptions{}) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } // Check subroute 2 is public. if isClusterLocal, err := isTrafficClusterLocal(publicRoute.Status.Traffic, subrouteTag2); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } else if isClusterLocal { t.Fatalf("Expected subroute with tag %s to be not cluster local", subrouteTag2) } // Check subroute1 is private. This check is expected to fail on v0.8.1 and earlier as subroute1 becomes public) if isClusterLocal, err := isTrafficClusterLocal(publicRoute.Status.Traffic, subrouteTag1); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } else if !isClusterLocal { t.Fatalf("Expected subroute with tag %s to be cluster local", subrouteTag1) } @@ -345,7 +345,7 @@ func TestSubrouteVisibilityPrivateToPublic(t *testing.T) { svc1patchBytes, err := duck.CreateBytePatch(svc1, svc1Copy) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } if _, err = clients.KubeClient.CoreV1().Services(test.ServingFlags.TestNamespace).Patch(context.Background(), serviceName1, types.JSONPatchType, svc1patchBytes, metav1.PatchOptions{}); err != nil { @@ -357,7 +357,7 @@ func TestSubrouteVisibilityPrivateToPublic(t *testing.T) { } if isClusterLocal, err := isTrafficClusterLocal(publicRoute.Status.Traffic, subrouteTag1); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } else if !isClusterLocal { t.Fatalf("Expected subroute with tag %s to be cluster local", subrouteTag1) } diff --git a/test/performance/benchmarks/dataplane-probe/main.go b/test/performance/benchmarks/dataplane-probe/main.go index 58693daa337d..2825e9ac32e2 100644 --- a/test/performance/benchmarks/dataplane-probe/main.go +++ b/test/performance/benchmarks/dataplane-probe/main.go @@ -162,7 +162,7 @@ LOOP: if err := checkSLA(metricResults, t.slaMin, t.slaMax, rate, *duration); err != nil { // make sure to still write the stats influxReporter.FlushAndShutdown() - log.Fatalf(err.Error()) + log.Fatal(err) } log.Println("Dataplane probe test finished") diff --git a/test/performance/benchmarks/load-test/main.go b/test/performance/benchmarks/load-test/main.go index 4e55b942dcee..82829d82d12f 100644 --- a/test/performance/benchmarks/load-test/main.go +++ b/test/performance/benchmarks/load-test/main.go @@ -107,7 +107,7 @@ func main() { if err := checkSLA(metricResults, pacers, durations); err != nil { // make sure to still write the stats influxReporter.FlushAndShutdown() - log.Fatalf(err.Error()) + log.Fatal(err) } log.Println("Load test finished") diff --git a/test/performance/benchmarks/rollout-probe/main.go b/test/performance/benchmarks/rollout-probe/main.go index 2881251386b7..960ee6c8a09d 100644 --- a/test/performance/benchmarks/rollout-probe/main.go +++ b/test/performance/benchmarks/rollout-probe/main.go @@ -82,7 +82,7 @@ func main() { startInformers() if *target == "" { - log.Fatalf("-target is a required flag.") + log.Fatal("-target is a required flag.") } // We cron quite often, so make sure that we don't severely overrun to @@ -214,7 +214,7 @@ LOOP: if err := checkSLA(metricResults, rate); err != nil { // make sure to still write the stats influxReporter.FlushAndShutdown() - log.Fatalf(err.Error()) + log.Fatal(err) } log.Println("Load test finished") diff --git a/test/performance/benchmarks/scale-from-zero/main.go b/test/performance/benchmarks/scale-from-zero/main.go index 2c527c74bc41..36f0bb31991e 100644 --- a/test/performance/benchmarks/scale-from-zero/main.go +++ b/test/performance/benchmarks/scale-from-zero/main.go @@ -167,7 +167,7 @@ func main() { if err := checkSLA(metricResults, sla.p95min, sla.p95max, sla.latencyMax, *parallelCount); err != nil { // make sure to still write the stats influxReporter.FlushAndShutdown() - log.Fatalf(err.Error()) + log.Fatal(err) } log.Println("Scale from zero test completed") From 74d8600f497dfd63a336252e862debe55b264ac5 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sat, 11 Jan 2025 12:11:45 -0500 Subject: [PATCH 19/35] fix gosimple linter --- pkg/activator/handler/metric_handler_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/activator/handler/metric_handler_test.go b/pkg/activator/handler/metric_handler_test.go index a7ab19204d29..d7a385c65d54 100644 --- a/pkg/activator/handler/metric_handler_test.go +++ b/pkg/activator/handler/metric_handler_test.go @@ -70,7 +70,7 @@ func TestRequestMetricHandler(t *testing.T) { resp := httptest.NewRecorder() req := httptest.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("")) - if test.newHeader != nil && len(test.newHeader) != 0 { + if len(test.newHeader) != 0 { for k, v := range test.newHeader { req.Header.Add(k, v) } From a06abbce0188db2f54d94e67bd2f1f57279ff2ec Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 13:54:59 -0500 Subject: [PATCH 20/35] fix gosec linter --- pkg/activator/net/lb_policy.go | 2 +- pkg/activator/net/throttler.go | 1 + pkg/autoscaler/scaling/autoscaler.go | 2 +- pkg/gc/config.go | 4 ++++ pkg/gc/config_test.go | 8 ++++++++ pkg/queue/breaker.go | 4 ++-- pkg/reconciler/autoscaling/hpa/hpa.go | 6 +++--- pkg/reconciler/autoscaling/kpa/kpa.go | 2 ++ pkg/reconciler/revision/resolve.go | 1 + pkg/reconciler/serverlessservice/resources/services.go | 5 +++-- 10 files changed, 26 insertions(+), 9 deletions(-) diff --git a/pkg/activator/net/lb_policy.go b/pkg/activator/net/lb_policy.go index 8d757fe39d3f..b114a1f6b7f5 100644 --- a/pkg/activator/net/lb_policy.go +++ b/pkg/activator/net/lb_policy.go @@ -34,7 +34,7 @@ type lbPolicy func(ctx context.Context, targets []*podTracker) (func(), *podTrac // randomLBPolicy is a load balancer policy that picks a random target. // This approximates the LB policy done by K8s Service (IPTables based). func randomLBPolicy(_ context.Context, targets []*podTracker) (func(), *podTracker) { - return noop, targets[rand.Intn(len(targets))] + return noop, targets[rand.Intn(len(targets))] //nolint:gosec } // randomChoice2Policy implements the Power of 2 choices LB algorithm diff --git a/pkg/activator/net/throttler.go b/pkg/activator/net/throttler.go index 484e66234d68..54d466afbc5e 100644 --- a/pkg/activator/net/throttler.go +++ b/pkg/activator/net/throttler.go @@ -631,6 +631,7 @@ func (rt *revisionThrottler) handlePubEpsUpdate(eps *corev1.Endpoints, selfIP st // We are using List to have the IP addresses sorted for consistent results. epsL := sets.List(epSet) + //nolint:gosec // number of k8s replicas is bounded by int32 newNA, newAI := int32(len(epsL)), int32(inferIndex(epsL, selfIP)) if newAI == -1 { // No need to do anything, this activator is not in path. diff --git a/pkg/autoscaler/scaling/autoscaler.go b/pkg/autoscaler/scaling/autoscaler.go index 1ecaa4c15cc1..fb0bd66ec949 100644 --- a/pkg/autoscaler/scaling/autoscaler.go +++ b/pkg/autoscaler/scaling/autoscaler.go @@ -118,7 +118,7 @@ func newAutoscaler( delayWindow: delayWindow, panicTime: pt, - maxPanicPods: int32(curC), + maxPanicPods: int32(curC), //nolint:gosec // k8s replica count is bounded by int32 } } diff --git a/pkg/gc/config.go b/pkg/gc/config.go index dc4c3b849633..3378d44206a0 100644 --- a/pkg/gc/config.go +++ b/pkg/gc/config.go @@ -20,6 +20,7 @@ import ( "context" "errors" "fmt" + "math" "strconv" "strings" "time" @@ -112,6 +113,9 @@ func parseDisabledOrInt64(val string, toSet *int64) error { if err != nil { return err } + if parsed > math.MaxInt64 { + return fmt.Errorf("value should be lower than %v", math.MaxInt64) + } *toSet = int64(parsed) } return nil diff --git a/pkg/gc/config_test.go b/pkg/gc/config_test.go index ce14eb68074f..23ec1d0bd0dc 100644 --- a/pkg/gc/config_test.go +++ b/pkg/gc/config_test.go @@ -17,6 +17,8 @@ limitations under the License. package gc import ( + "fmt" + "math" "testing" "time" @@ -70,6 +72,12 @@ func TestOurConfig(t *testing.T) { data: map[string]string{ "max-non-active-revisions": "-2", }, + }, { + name: "invalid integer value > maxint64", + fail: true, + data: map[string]string{ + "max-non-active-revisions": fmt.Sprintf("%v", uint64(math.MaxUint64)), + }, }, { name: "invalid max less than min", fail: true, diff --git a/pkg/queue/breaker.go b/pkg/queue/breaker.go index 543dd3dd82db..2968c77465bf 100644 --- a/pkg/queue/breaker.go +++ b/pkg/queue/breaker.go @@ -264,7 +264,7 @@ func (s *semaphore) release() { // updateCapacity updates the capacity of the semaphore to the desired size. func (s *semaphore) updateCapacity(size int) { - s64 := uint64(size) + s64 := uint64(size) //nolint:gosec // TODO(dprotaso) capacity should be uint for { old := s.state.Load() capacity, in := unpack(old) @@ -292,7 +292,7 @@ func (s *semaphore) updateCapacity(size int) { // Capacity is the capacity of the semaphore. func (s *semaphore) Capacity() int { capacity, _ := unpack(s.state.Load()) - return int(capacity) + return int(capacity) //nolint:gosec // TODO(dprotaso) - capacity should be uint64 } // unpack takes an uint64 and returns two uint32 (as uint64) comprised of the leftmost diff --git a/pkg/reconciler/autoscaling/hpa/hpa.go b/pkg/reconciler/autoscaling/hpa/hpa.go index 8e96ee59fd7e..86bb82f8579d 100644 --- a/pkg/reconciler/autoscaling/hpa/hpa.go +++ b/pkg/reconciler/autoscaling/hpa/hpa.go @@ -113,14 +113,14 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, pa *autoscalingv1alpha1. } // activeThreshold returns the scale required for the pa to be marked Active -func activeThreshold(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler) int { +func activeThreshold(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler) int32 { asConfig := config.FromContext(ctx).Autoscaler min, _ := pa.ScaleBounds(asConfig) if !pa.Status.IsScaleTargetInitialized() { initialScale := getInitialScale(asConfig, pa) - return int(intMax(min, initialScale)) + return intMax(min, initialScale) } - return int(intMax(min, 1)) + return intMax(min, 1) } // getInitialScale returns the calculated initial scale based on the autoscaler diff --git a/pkg/reconciler/autoscaling/kpa/kpa.go b/pkg/reconciler/autoscaling/kpa/kpa.go index a7dd17851544..3849b4427729 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa.go +++ b/pkg/reconciler/autoscaling/kpa/kpa.go @@ -219,6 +219,7 @@ func (c *Reconciler) reconcileDecider(ctx context.Context, pa *autoscalingv1alph } func computeStatus(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, pc podCounts, logger *zap.SugaredLogger) { + //nolint:gosec // bound by 0 < x < max(int32) pa.Status.ActualScale = ptr.Int32(int32(pc.ready)) // When the autoscaler just restarted, it does not yet have metrics and would change the desiredScale to -1 and moments @@ -226,6 +227,7 @@ func computeStatus(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, p if pc.want == -1 && pa.Status.DesiredScale != nil && *pa.Status.DesiredScale >= 0 { logger.Debugf("Ignoring change of desiredScale from %d to %d", *pa.Status.DesiredScale, pc.want) } else { + //nolint:gosec // bound by 0 < x < max(int32) pa.Status.DesiredScale = ptr.Int32(int32(pc.want)) } diff --git a/pkg/reconciler/revision/resolve.go b/pkg/reconciler/revision/resolve.go index 16aeeae8663e..458e3c8398de 100644 --- a/pkg/reconciler/revision/resolve.go +++ b/pkg/reconciler/revision/resolve.go @@ -65,6 +65,7 @@ func newResolverTransport(path string, maxIdleConns, maxIdleConnsPerHost int) (* transport := http.DefaultTransport.(*http.Transport).Clone() transport.MaxIdleConns = maxIdleConns transport.MaxIdleConnsPerHost = maxIdleConnsPerHost + //nolint:gosec // quay.io still required 1.2 - bump if they've moved up transport.TLSClientConfig = &tls.Config{ MinVersion: tlsMinVersionFromEnv(tls.VersionTLS12), RootCAs: pool, diff --git a/pkg/reconciler/serverlessservice/resources/services.go b/pkg/reconciler/serverlessservice/resources/services.go index 5672fc12e3df..3292a9b889af 100644 --- a/pkg/reconciler/serverlessservice/resources/services.go +++ b/pkg/reconciler/serverlessservice/resources/services.go @@ -63,8 +63,9 @@ func makePublicServicePorts(sks *v1alpha1.ServerlessService) []corev1.ServicePor Name: pkgnet.ServicePortName(sks.Spec.ProtocolType), Protocol: corev1.ProtocolTCP, AppProtocol: pkgnet.AppProtocol(sks.Spec.ProtocolType), - Port: int32(pkgnet.ServicePort(sks.Spec.ProtocolType)), - TargetPort: targetPort(sks), + //nolint:gosec //ignore integer overflow since pkgnet is bounded + Port: int32(pkgnet.ServicePort(sks.Spec.ProtocolType)), + TargetPort: targetPort(sks), }, { // The HTTPS port is used when activator-ca is enabled. // Although it is not used by default, we put it here as it should be harmless From a72a657139094eae7184145b0e86717dd7b30e4f Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 13:57:45 -0500 Subject: [PATCH 21/35] fix unconvert linter --- pkg/reconciler/autoscaling/hpa/hpa.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/reconciler/autoscaling/hpa/hpa.go b/pkg/reconciler/autoscaling/hpa/hpa.go index 86bb82f8579d..ba8cea900577 100644 --- a/pkg/reconciler/autoscaling/hpa/hpa.go +++ b/pkg/reconciler/autoscaling/hpa/hpa.go @@ -98,7 +98,7 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, pa *autoscalingv1alpha1. // as initialized until the current replicas are >= the min-scale value. if !pa.Status.IsScaleTargetInitialized() { ms := activeThreshold(ctx, pa) - if hpa.Status.CurrentReplicas >= int32(ms) { + if hpa.Status.CurrentReplicas >= ms { pa.Status.MarkScaleTargetInitialized() } } From d2f37edf46ab04719a5af6ce6b5b3236e7e2676f Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 13:59:26 -0500 Subject: [PATCH 22/35] fix perfsprint linter --- pkg/gc/config_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/gc/config_test.go b/pkg/gc/config_test.go index 23ec1d0bd0dc..5f5671bc25bf 100644 --- a/pkg/gc/config_test.go +++ b/pkg/gc/config_test.go @@ -17,8 +17,8 @@ limitations under the License. package gc import ( - "fmt" "math" + "strconv" "testing" "time" @@ -76,7 +76,7 @@ func TestOurConfig(t *testing.T) { name: "invalid integer value > maxint64", fail: true, data: map[string]string{ - "max-non-active-revisions": fmt.Sprintf("%v", uint64(math.MaxUint64)), + "max-non-active-revisions": strconv.FormatUint(math.MaxUint64, 10), }, }, { name: "invalid max less than min", From ff89cc0a9429402f1a5078accd8e7338874869b5 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:04:17 -0500 Subject: [PATCH 23/35] fix errname linter --- pkg/reconciler/route/domains/domains.go | 8 ++++---- pkg/reconciler/route/route.go | 2 +- pkg/reconciler/route/table_test.go | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/reconciler/route/domains/domains.go b/pkg/reconciler/route/domains/domains.go index 843f2f538109..0a3c63412a9b 100644 --- a/pkg/reconciler/route/domains/domains.go +++ b/pkg/reconciler/route/domains/domains.go @@ -44,7 +44,7 @@ import ( const HTTPScheme string = "http" var ( - ErrorDomainName = errors.New("domain name error") + ErrDomainName = errors.New("domain name error") ) // GetAllDomainsAndTags returns all of the domains and tags(including subdomains) associated with a Route @@ -124,12 +124,12 @@ func DomainNameFromTemplate(ctx context.Context, r metav1.ObjectMeta, name strin } if err := templ.Execute(&buf, data); err != nil { - return "", fmt.Errorf("%w: error executing the DomainTemplate: %w", ErrorDomainName, err) + return "", fmt.Errorf("%w: error executing the DomainTemplate: %w", ErrDomainName, err) } urlErrs := validation.IsFullyQualifiedDomainName(field.NewPath("url"), buf.String()) if urlErrs != nil { - return "", fmt.Errorf("%w: invalid domain name %q: %w", ErrorDomainName, buf.String(), urlErrs.ToAggregate()) + return "", fmt.Errorf("%w: invalid domain name %q: %w", ErrDomainName, buf.String(), urlErrs.ToAggregate()) } return buf.String(), nil @@ -152,7 +152,7 @@ func HostnameFromTemplate(ctx context.Context, name, tag string) (string, error) networkConfig := config.FromContext(ctx).Network buf := bytes.Buffer{} if err := networkConfig.GetTagTemplate().Execute(&buf, data); err != nil { - return "", fmt.Errorf("%w: error executing the TagTemplate: %w", ErrorDomainName, err) + return "", fmt.Errorf("%w: error executing the TagTemplate: %w", ErrDomainName, err) } return buf.String(), nil } diff --git a/pkg/reconciler/route/route.go b/pkg/reconciler/route/route.go index fd391bb8155c..f9db3b585122 100644 --- a/pkg/reconciler/route/route.go +++ b/pkg/reconciler/route/route.go @@ -120,7 +120,7 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, r *v1.Route) pkgreconcil traffic, err := c.configureTraffic(ctx, r) if traffic == nil || err != nil { if err != nil { - if errors.Is(err, domains.ErrorDomainName) { + if errors.Is(err, domains.ErrDomainName) { r.Status.MarkRevisionTargetTrafficError(errorConfigMsg, err.Error()) } else { r.Status.MarkUnknownTrafficError(err.Error()) diff --git a/pkg/reconciler/route/table_test.go b/pkg/reconciler/route/table_test.go index 5db58ef998a6..94562cbcd899 100644 --- a/pkg/reconciler/route/table_test.go +++ b/pkg/reconciler/route/table_test.go @@ -2049,7 +2049,7 @@ func TestReconcile(t *testing.T) { Object: Route("default", "tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long", WithConfigTarget("config"), WithRouteObservedGeneration, WithRouteFinalizer, WithInitRouteConditions, - MarkRevisionTargetTrafficError(errorConfigMsg, domains.ErrorDomainName.Error()+`: invalid domain name "tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long.default.example.com": url: Invalid value: "tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long": must be no more than 63 characters`), + MarkRevisionTargetTrafficError(errorConfigMsg, domains.ErrDomainName.Error()+`: invalid domain name "tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long.default.example.com": url: Invalid value: "tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long": must be no more than 63 characters`), WithHost("tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long.default.svc.cluster.local"), ), }}, From 3900cd39c8f1e83104dbf83ccd59b5b304138910 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:07:22 -0500 Subject: [PATCH 24/35] fix errlint linter --- pkg/http/handler/timeout_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/http/handler/timeout_test.go b/pkg/http/handler/timeout_test.go index ea9158840867..55109ab900b0 100644 --- a/pkg/http/handler/timeout_test.go +++ b/pkg/http/handler/timeout_test.go @@ -113,7 +113,7 @@ func testTimeoutScenario(t *testing.T, scenarios []timeoutHandlerTestScenario) { defer func() { if scenario.wantPanic { - if recovered := recover(); recovered != http.ErrAbortHandler { + if recovered := recover(); recovered != http.ErrAbortHandler { //nolint // False positive for errors.Is check t.Errorf("Recover = %v, want: %v", recovered, http.ErrAbortHandler) } } From 85df3e020f7ec68fc113214963ff539161d7b326 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:09:54 -0500 Subject: [PATCH 25/35] fix bodyclose linter --- pkg/autoscaler/metrics/http_scrape_client_test.go | 2 ++ pkg/autoscaler/statserver/server_test.go | 1 + test/e2e/websocket.go | 1 + .../multicontainer/servingcontainer/servingcontainer.go | 1 + test/test_images/readiness/readiness.go | 4 +++- 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pkg/autoscaler/metrics/http_scrape_client_test.go b/pkg/autoscaler/metrics/http_scrape_client_test.go index de52181906bf..b1a27d06917f 100644 --- a/pkg/autoscaler/metrics/http_scrape_client_test.go +++ b/pkg/autoscaler/metrics/http_scrape_client_test.go @@ -52,6 +52,7 @@ var ( ) func TestHTTPScrapeClientScrapeHappyCaseWithOptionals(t *testing.T) { + //nolint:bodyclose hClient := newTestHTTPClient(makeProtoResponse(http.StatusOK, stat, netheader.ProtobufMIMEType), nil) sClient := newHTTPScrapeClient(hClient) req, err := http.NewRequest(http.MethodGet, testURL, nil) @@ -114,6 +115,7 @@ func TestHTTPScrapeClientScrapeProtoErrorCases(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { + //nolint:bodyclose hClient := newTestHTTPClient(makeProtoResponse(test.responseCode, test.stat, test.responseType), test.responseErr) sClient := newHTTPScrapeClient(hClient) req, err := http.NewRequest(http.MethodGet, testURL, nil) diff --git a/pkg/autoscaler/statserver/server_test.go b/pkg/autoscaler/statserver/server_test.go index ddc136dd8926..86febddd0d9e 100644 --- a/pkg/autoscaler/statserver/server_test.go +++ b/pkg/autoscaler/statserver/server_test.go @@ -268,6 +268,7 @@ func dial(serverURL string) (*websocket.Conn, error) { dialer := &websocket.Dialer{ HandshakeTimeout: time.Second, } + //nolint:bodyclose statSink, _, err := dialer.Dial(u.String(), nil) return statSink, err } diff --git a/test/e2e/websocket.go b/test/e2e/websocket.go index a509ce4b010e..356bc277b2d6 100644 --- a/test/e2e/websocket.go +++ b/test/e2e/websocket.go @@ -77,6 +77,7 @@ func connect(t *testing.T, clients *test.Clients, domain, timeout string) (*webs dialer.TLSClientConfig.ServerName = domain // Set ServerName for pseudo hostname with TLS. } + //nolint:bodyclose c, resp, err := dialer.Dial(u.String(), http.Header{"Host": {domain}}) if err == nil { t.Log("WebSocket connection established.") diff --git a/test/test_images/multicontainer/servingcontainer/servingcontainer.go b/test/test_images/multicontainer/servingcontainer/servingcontainer.go index aceafe36ac13..33b64bad9db4 100644 --- a/test/test_images/multicontainer/servingcontainer/servingcontainer.go +++ b/test/test_images/multicontainer/servingcontainer/servingcontainer.go @@ -37,6 +37,7 @@ func handler(w http.ResponseWriter, _ *http.Request) { if err != nil { log.Fatal(err) } + defer res.Body.Close() resp, err := io.ReadAll(res.Body) if err != nil { log.Fatal(err) diff --git a/test/test_images/readiness/readiness.go b/test/test_images/readiness/readiness.go index 175b76d3928a..a9f9643e6b29 100644 --- a/test/test_images/readiness/readiness.go +++ b/test/test_images/readiness/readiness.go @@ -104,6 +104,7 @@ func execProbeMain() { if err != nil { log.Fatal("Failed to probe: ", err) } + defer resp.Body.Close() if resp.StatusCode > 299 { os.Exit(1) } @@ -119,10 +120,11 @@ func handleStartFailing(w http.ResponseWriter, _ *http.Request) { } func handleStartFailingSidecar(_ http.ResponseWriter, _ *http.Request) { - _, err := http.Get(os.ExpandEnv("http://localhost:$FORWARD_PORT/start-failing")) + resp, err := http.Get(os.ExpandEnv("http://localhost:$FORWARD_PORT/start-failing")) if err != nil { log.Fatalf("GET to /start-failing failed: %v", err) } + defer resp.Body.Close() } func handleReadiness(w http.ResponseWriter, _ *http.Request) { From 129b481fa56c08987d7ca3c5394262b5eb69812a Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:12:29 -0500 Subject: [PATCH 26/35] fix canonicalheader linter --- pkg/queue/stats_handler_test.go | 4 ++-- test/conformance/runtime/header_test.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/queue/stats_handler_test.go b/pkg/queue/stats_handler_test.go index 7e772cc7096f..ffbf8cbd865c 100644 --- a/pkg/queue/stats_handler_test.go +++ b/pkg/queue/stats_handler_test.go @@ -26,7 +26,7 @@ import ( func TestStatsHandler(t *testing.T) { proto := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("served-by", "protobuf") + w.Header().Set("Served-By", "protobuf") }) reporter := NewStatsHandler(proto) @@ -66,7 +66,7 @@ func TestStatsHandler(t *testing.T) { w := httptest.NewRecorder() reporter.ServeHTTP(w, r) - if got, want := w.Header().Get("served-by"), test.expect; got != want { + if got, want := w.Header().Get("Served-By"), test.expect; got != want { t.Errorf("Expected to be served %s but was served %s", want, got) } }) diff --git a/test/conformance/runtime/header_test.go b/test/conformance/runtime/header_test.go index 9e3c679e3f69..ae0b9ce94395 100644 --- a/test/conformance/runtime/header_test.go +++ b/test/conformance/runtime/header_test.go @@ -31,7 +31,7 @@ import ( ) const ( - userHeaderKey = "this-was-user-set" + userHeaderKey = "This-Was-User-Set" userHeaderValue = "a value" ) From 73166ef139ab68792b18bca6f732429452dd4c1e Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:19:14 -0500 Subject: [PATCH 27/35] fix durationcheck linter --- pkg/autoscaler/aggregation/bucketing_test.go | 4 ++-- pkg/autoscaler/aggregation/max/timewindow_test.go | 6 +++--- pkg/autoscaler/metrics/collector_test.go | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/autoscaler/aggregation/bucketing_test.go b/pkg/autoscaler/aggregation/bucketing_test.go index 1b5a6211b3f0..e88642b4c361 100644 --- a/pkg/autoscaler/aggregation/bucketing_test.go +++ b/pkg/autoscaler/aggregation/bucketing_test.go @@ -343,8 +343,8 @@ func TestTimedFloat64BucketsHoles(t *testing.T) { now := time.Now() buckets := NewTimedFloat64Buckets(5*time.Second, granularity) - for i := time.Duration(0); i < 5; i++ { - buckets.Record(now.Add(i*time.Second), float64(i+1)) + for i := range 5 { + buckets.Record(now.Add(time.Duration(i)*time.Second), float64(i+1)) } sum := 0. diff --git a/pkg/autoscaler/aggregation/max/timewindow_test.go b/pkg/autoscaler/aggregation/max/timewindow_test.go index 1d663e0249ef..1dc9edc9cadf 100644 --- a/pkg/autoscaler/aggregation/max/timewindow_test.go +++ b/pkg/autoscaler/aggregation/max/timewindow_test.go @@ -121,9 +121,9 @@ func BenchmarkLargeTimeWindowAscendingRecord(b *testing.B) { } func BenchmarkLargeTimeWindowDescendingRecord(b *testing.B) { - for _, duration := range []time.Duration{5, 15, 30, 45} { - b.Run(fmt.Sprintf("duration-%d-minutes", duration), func(b *testing.B) { - w := NewTimeWindow(duration*time.Minute, 1*time.Second) + for _, d := range []int{5, 15, 30, 45} { + b.Run(fmt.Sprintf("duration-%v-minutes", d), func(b *testing.B) { + w := NewTimeWindow(time.Duration(d)*time.Minute, 1*time.Second) now := time.Now() for i := 0; i < b.N; i++ { diff --git a/pkg/autoscaler/metrics/collector_test.go b/pkg/autoscaler/metrics/collector_test.go index 734db7eccbb4..5b842e19a079 100644 --- a/pkg/autoscaler/metrics/collector_test.go +++ b/pkg/autoscaler/metrics/collector_test.go @@ -620,13 +620,13 @@ func TestMetricCollectorAggregate(t *testing.T) { rpsPanicBuckets: aggregation.NewTimedFloat64Buckets(m.Spec.PanicWindow, config.BucketSize), } now := time.Now() - for i := time.Duration(0); i < 10; i++ { + for i := range 10 { stat := Stat{ PodName: "testPod", AverageConcurrentRequests: float64(i + 5), RequestCount: float64(i + 5), } - c.record(now.Add(i*time.Second), stat) + c.record(now.Add(time.Duration(i)*time.Second), stat) } now = now.Add(9 * time.Second) From f052fbada92d8c0df05629964fb48590329a1e21 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:27:04 -0500 Subject: [PATCH 28/35] fix copyloopvar linter --- pkg/activator/net/revision_backends.go | 1 - pkg/deployment/config_test.go | 1 - pkg/reconciler/revision/resolve_test.go | 1 - pkg/reconciler/route/reconcile_resources.go | 1 - pkg/reconciler/route/route_test.go | 1 - test/conformance/api/v1/revision_timeout_test.go | 2 -- test/conformance/api/v1/util.go | 2 -- test/conformance/runtime/container_test.go | 2 -- test/conformance/runtime/protocol_test.go | 1 - test/conformance/runtime/readiness_probe_test.go | 3 --- test/e2e/autoscale_test.go | 2 -- test/e2e/destroypod_test.go | 1 - test/e2e/grpc_test.go | 1 - test/e2e/route_service_test.go | 1 - test/e2e/scale.go | 2 -- test/e2e/service_to_service_test.go | 2 -- test/e2e/tagheader/tag_header_based_routing_test.go | 1 - test/e2e/timeout_test.go | 2 -- test/e2e/websocket_test.go | 2 -- test/ha/workload_test.go | 1 - 20 files changed, 30 deletions(-) diff --git a/pkg/activator/net/revision_backends.go b/pkg/activator/net/revision_backends.go index ac1436c94520..2a773c0e7ff1 100644 --- a/pkg/activator/net/revision_backends.go +++ b/pkg/activator/net/revision_backends.go @@ -261,7 +261,6 @@ func (rw *revisionWatcher) probePodIPs(ready, notReady sets.Set[string]) (succee continue } - dest := dest // Standard Go concurrency pattern. probeGroup.Go(func() error { ok, notMesh, err := rw.probe(ctx, dest) if ok && (ready.Has(dest) || rw.enableProbeOptimisation) { diff --git a/pkg/deployment/config_test.go b/pkg/deployment/config_test.go index 301dd3782a91..16f3d2ac6f55 100644 --- a/pkg/deployment/config_test.go +++ b/pkg/deployment/config_test.go @@ -594,7 +594,6 @@ func TestPodRuntimeClassName(t *testing.T) { }} for _, tt := range ts { - tt := tt t.Run(tt.name, func(t *testing.T) { if tt.serviceLabels == nil { tt.serviceLabels = map[string]string{} diff --git a/pkg/reconciler/revision/resolve_test.go b/pkg/reconciler/revision/resolve_test.go index bef5fac63c58..0e63e57167aa 100644 --- a/pkg/reconciler/revision/resolve_test.go +++ b/pkg/reconciler/revision/resolve_test.go @@ -479,7 +479,6 @@ func TestNewResolverTransport(t *testing.T) { tmpDir := t.TempDir() for i, tc := range cases { - i, tc := i, tc t.Run(fmt.Sprintf("cases[%d]", i), func(t *testing.T) { // Setup. path, err := writeCertFile(tmpDir, tc.certBundle, tc.certBundleContents) diff --git a/pkg/reconciler/route/reconcile_resources.go b/pkg/reconciler/route/reconcile_resources.go index 0919f2f0f4b2..2fb29b6415cf 100644 --- a/pkg/reconciler/route/reconcile_resources.go +++ b/pkg/reconciler/route/reconcile_resources.go @@ -221,7 +221,6 @@ func (c *Reconciler) updatePlaceholderServices(ctx context.Context, route *v1.Ro eg, egCtx := errgroup.WithContext(ctx) for _, from := range pairs { - from := from eg.Go(func() error { to, err := resources.MakeK8sService(egCtx, route, from.Tag, ingress, resources.IsClusterLocalService(from.Service)) if err != nil { diff --git a/pkg/reconciler/route/route_test.go b/pkg/reconciler/route/route_test.go index 933d1d236888..9a3993669364 100644 --- a/pkg/reconciler/route/route_test.go +++ b/pkg/reconciler/route/route_test.go @@ -1461,7 +1461,6 @@ func TestGlobalResyncOnUpdateDomainConfigMap(t *testing.T) { }} for _, test := range tests { - test := test t.Run(test.expectedDomainSuffix, func(t *testing.T) { ctx, informers, ctrl, watcher, cf := newTestSetup(t) diff --git a/test/conformance/api/v1/revision_timeout_test.go b/test/conformance/api/v1/revision_timeout_test.go index e3c3de96764f..29e1bbf61eb8 100644 --- a/test/conformance/api/v1/revision_timeout_test.go +++ b/test/conformance/api/v1/revision_timeout_test.go @@ -103,8 +103,6 @@ func TestRevisionTimeout(t *testing.T) { }} for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { t.Parallel() diff --git a/test/conformance/api/v1/util.go b/test/conformance/api/v1/util.go index 6e068e1bb543..dfa6c7d6416f 100644 --- a/test/conformance/api/v1/util.go +++ b/test/conformance/api/v1/util.go @@ -91,7 +91,6 @@ func validateDomains(t testing.TB, clients *test.Clients, serviceName string, return checkForExpectedResponses(egCtx, t, clients, baseDomain, baseExpected...) }) for i, s := range subdomains { - i, s := i, s g.Go(func() error { t.Log("Checking updated route tags", s) return checkForExpectedResponses(egCtx, t, clients, s, tagExpectationPairs[i].expectedResponse) @@ -111,7 +110,6 @@ func validateDomains(t testing.TB, clients *test.Clients, serviceName string, return shared.CheckDistribution(egCtx, t, clients, baseDomain, test.ConcurrentRequests, min, baseExpected, test.ServingFlags.ResolvableDomain) }) for i, subdomain := range subdomains { - i, subdomain := i, subdomain g.Go(func() error { min := int(math.Floor(test.ConcurrentRequests * test.MinDirectPercentage)) return shared.CheckDistribution(egCtx, t, clients, subdomain, test.ConcurrentRequests, min, []string{tagExpectationPairs[i].expectedResponse}, test.ServingFlags.ResolvableDomain) diff --git a/test/conformance/runtime/container_test.go b/test/conformance/runtime/container_test.go index e1a01e2e2bab..98b6045b0dca 100644 --- a/test/conformance/runtime/container_test.go +++ b/test/conformance/runtime/container_test.go @@ -59,7 +59,6 @@ func TestMustNotContainerConstraints(t *testing.T) { }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() names := test.ResourceNames{ @@ -177,7 +176,6 @@ func TestShouldNotContainerConstraints(t *testing.T) { }} for _, tc := range testCases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() names := test.ResourceNames{ diff --git a/test/conformance/runtime/protocol_test.go b/test/conformance/runtime/protocol_test.go index 1e1477e9cc4f..a305b284a559 100644 --- a/test/conformance/runtime/protocol_test.go +++ b/test/conformance/runtime/protocol_test.go @@ -61,7 +61,6 @@ func TestProtocols(t *testing.T) { }} for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() diff --git a/test/conformance/runtime/readiness_probe_test.go b/test/conformance/runtime/readiness_probe_test.go index bca4fe3a01d6..18a1558082f0 100644 --- a/test/conformance/runtime/readiness_probe_test.go +++ b/test/conformance/runtime/readiness_probe_test.go @@ -101,9 +101,7 @@ func TestProbeRuntime(t *testing.T) { }} for _, tc := range testCases { - tc := tc for _, period := range []int32{0, 1} { - period := period name := tc.name if period > 0 { // period > 0 opts out of the custom knative startup probing behaviour. @@ -169,7 +167,6 @@ func TestProbeRuntimeAfterStartup(t *testing.T) { } for _, period := range []int32{0, 1} { - period := period t.Run(fmt.Sprintf("periodSeconds=%d", period), func(t *testing.T) { t.Parallel() clients := test.Setup(t) diff --git a/test/e2e/autoscale_test.go b/test/e2e/autoscale_test.go index dc0d81d2cc1d..5df556d3faf9 100644 --- a/test/e2e/autoscale_test.go +++ b/test/e2e/autoscale_test.go @@ -50,7 +50,6 @@ func TestAutoscaleUpDownUp(t *testing.T) { autoscaling.MetricAggregationAlgorithmLinear, autoscaling.MetricAggregationAlgorithmWeightedExponential, } { - algo := algo t.Run("aggregation-"+algo, func(t *testing.T) { t.Parallel() ctx := SetupSvc(t, @@ -122,7 +121,6 @@ func TestAutoscaleSustaining(t *testing.T) { autoscaling.MetricAggregationAlgorithmLinear, autoscaling.MetricAggregationAlgorithmWeightedExponential, } { - algo := algo t.Run("aggregation-"+algo, func(t *testing.T) { // When traffic increases, a knative app should scale up and sustain the scale // as long as the traffic sustains, despite whether it is switching modes between diff --git a/test/e2e/destroypod_test.go b/test/e2e/destroypod_test.go index a6d2fd6eafe0..a60624f51bad 100644 --- a/test/e2e/destroypod_test.go +++ b/test/e2e/destroypod_test.go @@ -297,7 +297,6 @@ func TestDestroyPodWithRequests(t *testing.T) { // Start several requests staggered with 1s delay. for i := 1; i < 7; i++ { - i := i t.Logf("Starting request %d at %v", i, time.Now()) eg.Go(func() error { req, err := http.NewRequestWithContext(egCtx, http.MethodGet, u.String(), nil) diff --git a/test/e2e/grpc_test.go b/test/e2e/grpc_test.go index d25a686c83ce..a23a6833ba0c 100644 --- a/test/e2e/grpc_test.go +++ b/test/e2e/grpc_test.go @@ -198,7 +198,6 @@ func generateGRPCTraffic(ctx *TestContext, concurrentRequests int, host, domain var grp errgroup.Group for i := 0; i < concurrentRequests; i++ { - i := i grp.Go(func() error { for j := 0; ; j++ { select { diff --git a/test/e2e/route_service_test.go b/test/e2e/route_service_test.go index 5d27042b9bee..7eaf7b5ad73e 100644 --- a/test/e2e/route_service_test.go +++ b/test/e2e/route_service_test.go @@ -120,7 +120,6 @@ func TestRouteVisibilityChanges(t *testing.T) { } for _, testCase := range testCases { - testCase := testCase t.Run(testCase.name, func(st *testing.T) { st.Parallel() diff --git a/test/e2e/scale.go b/test/e2e/scale.go index 6df987ba6cac..01e4ac6b5a29 100644 --- a/test/e2e/scale.go +++ b/test/e2e/scale.go @@ -87,8 +87,6 @@ func ScaleToWithin(t *testing.T, scale int, duration time.Duration, latencies La }) for i := 0; i < scale; i++ { - // https://golang.org/doc/faq#closures_and_goroutines - i := i t.Run(fmt.Sprintf("%03d-of-%03d", i, scale), func(t *testing.T) { t.Parallel() diff --git a/test/e2e/service_to_service_test.go b/test/e2e/service_to_service_test.go index a8a58d90854f..3d9a51c46956 100644 --- a/test/e2e/service_to_service_test.go +++ b/test/e2e/service_to_service_test.go @@ -178,7 +178,6 @@ func TestSvcToSvcViaActivator(t *testing.T) { clients := Setup(t) for _, tc := range testInjection { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() if !test.ServingFlags.DisableLogStream { @@ -235,7 +234,6 @@ func TestCallToPublicService(t *testing.T) { } for _, tc := range gatewayTestCases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() if !test.ServingFlags.DisableLogStream { diff --git a/test/e2e/tagheader/tag_header_based_routing_test.go b/test/e2e/tagheader/tag_header_based_routing_test.go index af1824f623a4..3241ad95cc40 100644 --- a/test/e2e/tagheader/tag_header_based_routing_test.go +++ b/test/e2e/tagheader/tag_header_based_routing_test.go @@ -112,7 +112,6 @@ func TestTagHeaderBasedRouting(t *testing.T) { }} for _, tt := range testCases { - tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() diff --git a/test/e2e/timeout_test.go b/test/e2e/timeout_test.go index 6ccf469859ce..e00b254259b0 100644 --- a/test/e2e/timeout_test.go +++ b/test/e2e/timeout_test.go @@ -123,8 +123,6 @@ func TestRevisionTimeout(t *testing.T) { }} for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { t.Parallel() diff --git a/test/e2e/websocket_test.go b/test/e2e/websocket_test.go index 26a9e57f63f3..de458bbd83db 100644 --- a/test/e2e/websocket_test.go +++ b/test/e2e/websocket_test.go @@ -324,8 +324,6 @@ func TestWebSocketWithTimeout(t *testing.T) { expectError: true, }} for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { names := test.ResourceNames{ Service: test.ObjectNameForTest(t), diff --git a/test/ha/workload_test.go b/test/ha/workload_test.go index 636494db2b10..55a6452c17f3 100644 --- a/test/ha/workload_test.go +++ b/test/ha/workload_test.go @@ -59,7 +59,6 @@ func TestWorkloadHA(t *testing.T) { }} for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() clients := e2e.Setup(t) From 663dd2e1dd6d7764a3a075e45f0e86a3535928cf Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:33:18 -0500 Subject: [PATCH 29/35] fix fatcontext linter --- pkg/activator/net/throttler_test.go | 2 +- pkg/apis/serving/metadata_validation_test.go | 3 ++- pkg/client/certmanager/testing/factory.go | 2 +- pkg/reconciler/route/table_test.go | 1 + pkg/reconciler/testing/v1/factory.go | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index 97e4774e24dd..bfee02f0664e 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -954,7 +954,7 @@ func TestInfiniteBreaker(t *testing.T) { // Verify we call the thunk when we have achieved capacity. // Twice. for i := 0; i < 2; i++ { - ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) cancel() res := false if err := b.Maybe(ctx, func() { res = true }); err != nil { diff --git a/pkg/apis/serving/metadata_validation_test.go b/pkg/apis/serving/metadata_validation_test.go index 65c0cbcd2559..b0453456e96c 100644 --- a/pkg/apis/serving/metadata_validation_test.go +++ b/pkg/apis/serving/metadata_validation_test.go @@ -206,6 +206,7 @@ func TestValidateObjectMetadata(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { if c.ctx == nil { + //nolint:fatcontext c.ctx = config.ToContext(context.Background(), &config.Config{Autoscaler: &autoscalerconfig.Config{AllowZeroInitialScale: false}}) } err := ValidateObjectMetadata(c.ctx, c.objectMeta, c.allowAutoscaling) @@ -306,7 +307,7 @@ func TestValidateContainerConcurrency(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { if tc.ctx == nil { - tc.ctx = context.Background() + tc.ctx = context.Background() //nolint:fatcontext } err := ValidateContainerConcurrency(tc.ctx, tc.containerConcurrency) if got, want := err.Error(), tc.expectErr.Error(); got != want { diff --git a/pkg/client/certmanager/testing/factory.go b/pkg/client/certmanager/testing/factory.go index f2da89b17b70..92fef2787459 100644 --- a/pkg/client/certmanager/testing/factory.go +++ b/pkg/client/certmanager/testing/factory.go @@ -77,7 +77,7 @@ func MakeFactory(ctor Ctor) rtesting.Factory { // Set up our Controller from the fakes. c := ctor(ctx, &ls, configmap.NewStaticWatcher()) // Update the context with the stuff we decorated it with. - r.Ctx = ctx + r.Ctx = ctx //nolint:fatcontext // The Reconciler won't do any work until it becomes the leader. if la, ok := c.(reconciler.LeaderAware); ok { diff --git a/pkg/reconciler/route/table_test.go b/pkg/reconciler/route/table_test.go index 94562cbcd899..a250643ebd79 100644 --- a/pkg/reconciler/route/table_test.go +++ b/pkg/reconciler/route/table_test.go @@ -3354,6 +3354,7 @@ func TestReconcileEnableExternalDomainTLS(t *testing.T) { if row.Ctx == nil { row.Ctx = context.Background() } + //nolint:fatcontext table[i].Ctx = context.WithValue(row.Ctx, enableExternalDomainTLSKey, true) } table.Test(t, MakeFactory(NewTestReconciler)) diff --git a/pkg/reconciler/testing/v1/factory.go b/pkg/reconciler/testing/v1/factory.go index f73bb515ae97..ad51cdfdbbad 100644 --- a/pkg/reconciler/testing/v1/factory.go +++ b/pkg/reconciler/testing/v1/factory.go @@ -101,7 +101,7 @@ func MakeFactory(ctor Ctor) rtesting.Factory { // Set up our Controller from the fakes. c := ctor(ctx, &ls, configmap.NewStaticWatcher()) // Update the context with the stuff we decorated it with. - r.Ctx = ctx + r.Ctx = ctx //nolint:fatcontext // The Reconciler won't do any work until it becomes the leader. if la, ok := c.(reconciler.LeaderAware); ok { From c6b9012f866c90930b61bf401c0a3891b17dbd4f Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 14:42:47 -0500 Subject: [PATCH 30/35] fix gocritic-commentFormatting --- pkg/apis/serving/fieldmask.go | 2 +- pkg/reconciler/certificate/certificate.go | 2 +- pkg/reconciler/certificate/certificate_test.go | 2 +- .../certificate/resources/cert_manager_certificate.go | 4 ++-- pkg/reconciler/route/route.go | 10 +++++----- pkg/reconciler/route/table_test.go | 6 +++--- test/e2e/subroutes_test.go | 2 +- test/e2e/systeminternaltls/system_internal_tls_test.go | 2 +- test/upgrade/preupgrade.go | 4 ++-- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pkg/apis/serving/fieldmask.go b/pkg/apis/serving/fieldmask.go index cba7049cce8b..b1761e2387d2 100644 --- a/pkg/apis/serving/fieldmask.go +++ b/pkg/apis/serving/fieldmask.go @@ -472,7 +472,7 @@ func ContainerPortMask(in *corev1.ContainerPort) *corev1.ContainerPort { out.Name = in.Name out.Protocol = in.Protocol - //Disallowed fields + // Disallowed fields // This list is unnecessary, but added here for clarity out.HostIP = "" out.HostPort = 0 diff --git a/pkg/reconciler/certificate/certificate.go b/pkg/reconciler/certificate/certificate.go index 5ae2c34ed2e0..da6263dae7f2 100644 --- a/pkg/reconciler/certificate/certificate.go +++ b/pkg/reconciler/certificate/certificate.go @@ -218,7 +218,7 @@ func (c *Reconciler) setHTTP01Challenges(ctx context.Context, knCert *v1alpha1.C logger.Info("No challenge service found for shortened commonname, could be cached? continuing") continue } - //If the cert is renewing, it could be possible that this isn't an error. Should this change depending on the case? + // If the cert is renewing, it could be possible that this isn't an error. Should this change depending on the case? return fmt.Errorf("no challenge solver service for domain %s; selector=%v", dnsName, selector) } diff --git a/pkg/reconciler/certificate/certificate_test.go b/pkg/reconciler/certificate/certificate_test.go index 99b0d686e02d..4c9cbe057bc3 100644 --- a/pkg/reconciler/certificate/certificate_test.go +++ b/pkg/reconciler/certificate/certificate_test.go @@ -703,7 +703,7 @@ func TestReconcile_HTTP01Challenges(t *testing.T) { }), }}, }, { - //It is possible for a challenge to not be created for a k.{{Domain}} dnsname, since it may have already been created in a previous Kservice + // It is possible for a challenge to not be created for a k.{{Domain}} dnsname, since it may have already been created in a previous Kservice Name: "set Status.HTTP01Challenges on Knative certificate when shortened domain with prefix (k.) is reused", Key: "foo/knCert", Objects: []runtime.Object{ diff --git a/pkg/reconciler/certificate/resources/cert_manager_certificate.go b/pkg/reconciler/certificate/resources/cert_manager_certificate.go index 7431e1c68363..1706b740d8a9 100644 --- a/pkg/reconciler/certificate/resources/cert_manager_certificate.go +++ b/pkg/reconciler/certificate/resources/cert_manager_certificate.go @@ -54,7 +54,7 @@ func MakeCertManagerCertificate(cmConfig *config.CertManagerConfig, knCert *v1al // The KCert controller requests new certs with same domain names, but a different CN if spec.domain is set and the other domain name would be too long // cert-manager Certificates are updated only if the existing domain name kept them from being issued. if len(commonName) > longest { - //if we have a domain field, we can attempt to shorten, or check if we are dealing with a domainMapping + // if we have a domain field, we can attempt to shorten, or check if we are dealing with a domainMapping if knCert.Spec.Domain != "" { // if the domain and commonName pulled from DNSNames are the same, we are dealing with a domainmapping if knCert.Spec.Domain == commonName { @@ -96,7 +96,7 @@ func MakeCertManagerCertificate(cmConfig *config.CertManagerConfig, knCert *v1al commonName = Prefix + knCert.Spec.Domain dnsNames = append(dnsNames, commonName) } else { - //If there was no domain, we can't shorten anything. We must error. + // If there was no domain, we can't shorten anything. We must error. return nil, &apis.Condition{ Type: CreateCertManagerCertificateCondition, Status: corev1.ConditionFalse, diff --git a/pkg/reconciler/route/route.go b/pkg/reconciler/route/route.go index f9db3b585122..ecdd60e06ed2 100644 --- a/pkg/reconciler/route/route.go +++ b/pkg/reconciler/route/route.go @@ -276,11 +276,11 @@ func (c *Reconciler) externalDomainTLS(ctx context.Context, host string, r *v1.R if renewingCondition.Status == corev1.ConditionTrue { logger.Infof("Renewing Condition detected on Cert (%s), will attempt creating new challenges.", cert.Name) if len(cert.Status.HTTP01Challenges) == 0 { - //Not sure log level this should be at. - //It is possible for certs to be renewed without getting - //validated again, for example, LetsEncrypt will cache - //validation results. See - //[here](https://letsencrypt.org/docs/faq/#i-successfully-renewed-a-certificate-but-validation-didn-t-happen-this-time-how-is-that-possible) + // Not sure log level this should be at. + // It is possible for certs to be renewed without getting + // validated again, for example, LetsEncrypt will cache + // validation results. See + // [here](https://letsencrypt.org/docs/faq/#i-successfully-renewed-a-certificate-but-validation-didn-t-happen-this-time-how-is-that-possible) logger.Infof("No HTTP01Challenges found on Cert (%s).", cert.Name) } acmeChallenges = append(acmeChallenges, cert.Status.HTTP01Challenges...) diff --git a/pkg/reconciler/route/table_test.go b/pkg/reconciler/route/table_test.go index a250643ebd79..15dd77ae9f49 100644 --- a/pkg/reconciler/route/table_test.go +++ b/pkg/reconciler/route/table_test.go @@ -633,7 +633,7 @@ func TestReconcile(t *testing.T) { InduceFailure("create", "ingresses"), }, WantCreates: []runtime.Object{ - //This is the Create we see for the ingress, but we induce a failure. + // This is the Create we see for the ingress, but we induce a failure. simpleIngress( Route("default", "ingress-create-failure", WithConfigTarget("config"), WithURL), @@ -2753,7 +2753,7 @@ func TestReconcileEnableExternalDomainTLS(t *testing.T) { }, Spec: netv1alpha1.CertificateSpec{ DNSNames: []string{"becomes-ready.default.example.com"}, - Domain: "example.com", //Need this to pass, otherwise extra event updating the Cert with missing Domain will cause test to fail + Domain: "example.com", // Need this to pass, otherwise extra event updating the Cert with missing Domain will cause test to fail SecretName: "route-12-34", }, Status: netv1alpha1.CertificateStatus{ @@ -2876,7 +2876,7 @@ func TestReconcileEnableExternalDomainTLS(t *testing.T) { }, Spec: netv1alpha1.CertificateSpec{ DNSNames: []string{"becomes-ready.default.example.com"}, - Domain: "example.com", //Need this to pass, otherwise extra event updating the Cert with missing Domain will cause test to fail + Domain: "example.com", // Need this to pass, otherwise extra event updating the Cert with missing Domain will cause test to fail SecretName: "route-12-34", }, Status: netv1alpha1.CertificateStatus{ diff --git a/test/e2e/subroutes_test.go b/test/e2e/subroutes_test.go index 7c5fbd2a3843..d25ff2ebe61f 100644 --- a/test/e2e/subroutes_test.go +++ b/test/e2e/subroutes_test.go @@ -153,7 +153,7 @@ func TestSubrouteVisibilityPublicToPrivate(t *testing.T) { t.Fatal("Failed to patch service:", err) } - //Create subroute2 in kservice. + // Create subroute2 in kservice. ksvcCopy := resources.Service.DeepCopy() ksvcCopyRouteTraffic := append(ksvcCopy.Spec.Traffic, v1.TrafficTarget{ diff --git a/test/e2e/systeminternaltls/system_internal_tls_test.go b/test/e2e/systeminternaltls/system_internal_tls_test.go index bfc12d5ac24c..aeff779be8d2 100644 --- a/test/e2e/systeminternaltls/system_internal_tls_test.go +++ b/test/e2e/systeminternaltls/system_internal_tls_test.go @@ -71,7 +71,7 @@ func TestSystemInternalTLS(t *testing.T) { t.Fatalf("Failed to create initial Service: %v: %v", names.Service, err) } - //The request made here should be enough to trigger some request logs on the Activator and QueueProxy + // The request made here should be enough to trigger some request logs on the Activator and QueueProxy t.Log("Checking Endpoint state") url := resources.Route.Status.URL.URL() checkEndpointState(t, clients, url) diff --git a/test/upgrade/preupgrade.go b/test/upgrade/preupgrade.go index d00f5ef86e87..8fa5efb61d23 100644 --- a/test/upgrade/preupgrade.go +++ b/test/upgrade/preupgrade.go @@ -52,7 +52,7 @@ func servicePreUpgrade(t *testing.T) { resources, err := v1test.CreateServiceReady(t, clients, &upgradeServiceNames, rtesting.WithConfigAnnotations(map[string]string{ - autoscaling.MinScaleAnnotationKey: "1", //make sure we don't scale to zero during the test + autoscaling.MinScaleAnnotationKey: "1", // make sure we don't scale to zero during the test }), ) if err != nil { @@ -76,7 +76,7 @@ func servicePreUpgradeAndScaleToZero(t *testing.T) { resources, err := v1test.CreateServiceReady(t, clients, &scaleToZeroServiceNames, rtesting.WithConfigAnnotations(map[string]string{ - autoscaling.WindowAnnotationKey: autoscaling.WindowMin.String(), //make sure we scale to zero quickly + autoscaling.WindowAnnotationKey: autoscaling.WindowMin.String(), // make sure we scale to zero quickly }), ) if err != nil { From 16d836d57fe90b3b0a4a8d6ff7be90be443718ca Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 19:14:22 -0500 Subject: [PATCH 31/35] fix gocritic linter --- .golangci.yaml | 8 ++++++-- cmd/schema-tweak/main.go | 3 +-- pkg/activator/handler/tracing_handler_test.go | 6 ++---- pkg/activator/net/throttler_test.go | 5 +++-- pkg/apis/serving/v1/revision_validation.go | 6 ++---- pkg/autoscaler/aggregation/bucketing.go | 2 +- pkg/reconciler/revision/table_test.go | 6 +++--- test/performance/benchmarks/load-test/main.go | 2 +- test/test_images/autoscale/autoscale.go | 2 +- .../multicontainer/servingcontainer/servingcontainer.go | 2 +- test/test_images/readiness/readiness.go | 3 ++- 11 files changed, 23 insertions(+), 22 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 71f04e919313..f66ced39b730 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -32,8 +32,12 @@ issues: text: "ifElseChain" linters-settings: - # goimports: - # local-prefixes: knative.dev/pkg + gocritic: + disabled-checks: + # we typically have this pattern during setup + - exitAfterDefer + # a lot cases we have are legit + - appendAssign gomodguard: blocked: modules: diff --git a/cmd/schema-tweak/main.go b/cmd/schema-tweak/main.go index 8839fea41723..a7289e90570d 100644 --- a/cmd/schema-tweak/main.go +++ b/cmd/schema-tweak/main.go @@ -213,8 +213,7 @@ func filterAllowedFields(node *yaml.Node, allowed sets.Set[string], features []f func dropRequiredFields(node *yaml.Node, fields sets.Set[string]) { dataType := dataType(node) - switch dataType { - case "array": + if dataType == "array" { node = items(node) } diff --git a/pkg/activator/handler/tracing_handler_test.go b/pkg/activator/handler/tracing_handler_test.go index 55263066477e..1f8c29fd37ef 100644 --- a/pkg/activator/handler/tracing_handler_test.go +++ b/pkg/activator/handler/tracing_handler_test.go @@ -89,10 +89,8 @@ func TestTracingHandler(t *testing.T) { if got := spans[0].TraceID.String(); got != traceID { t.Errorf("spans[0].TraceID = %s, want %s", got, traceID) } - } else { - if len(spans) != 0 { - t.Errorf("Got %d spans, expected 0: spans = %v", len(spans), spans) - } + } else if len(spans) != 0 { + t.Errorf("Got %d spans, expected 0: spans = %v", len(spans), spans) } }) } diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index bfee02f0664e..bb4f9b47db5d 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -19,6 +19,7 @@ package net import ( "context" "errors" + "slices" "strconv" "sync" "testing" @@ -1177,7 +1178,7 @@ func TestAssignSlice(t *testing.T) { } }) t.Run("idx=1 na=3", func(t *testing.T) { - cp := append(trackers[:0:0], trackers...) + cp := slices.Clone(trackers) got := assignSlice(cp, 1, 3) if !cmp.Equal(got, trackers[1:2], opt) { t.Errorf("Got=%v, want: %v; diff: %s", got, trackers[0:1], @@ -1203,7 +1204,7 @@ func TestAssignSlice(t *testing.T) { dest: "3", b: queue.NewBreaker(testBreakerParams), }} - cp := append(trackers[:0:0], trackers...) + cp := slices.Clone(trackers) got := assignSlice(cp, 1, 2) want := trackers[1:2] if !cmp.Equal(got, want, opt) { diff --git a/pkg/apis/serving/v1/revision_validation.go b/pkg/apis/serving/v1/revision_validation.go index 2508bf8bbc6c..def2570fef70 100644 --- a/pkg/apis/serving/v1/revision_validation.go +++ b/pkg/apis/serving/v1/revision_validation.go @@ -193,10 +193,8 @@ func validateQueueSidecarResourceAnnotations(m map[string]string) *apis.FieldErr value, err := strconv.ParseFloat(v, 64) if err != nil { errs = errs.Also(apis.ErrInvalidValue(v, apis.CurrentField).ViaKey(k)) - } else { - if value < 0.1 || value > 100 { - errs = errs.Also(apis.ErrOutOfBoundsValue(value, 0.1, 100.0, apis.CurrentField).ViaKey(k)) - } + } else if value < 0.1 || value > 100 { + errs = errs.Also(apis.ErrOutOfBoundsValue(value, 0.1, 100.0, apis.CurrentField).ViaKey(k)) } } annoKeys := []kmap.KeyPriority{ diff --git a/pkg/autoscaler/aggregation/bucketing.go b/pkg/autoscaler/aggregation/bucketing.go index 3714b5a2dedb..baf289cea94e 100644 --- a/pkg/autoscaler/aggregation/bucketing.go +++ b/pkg/autoscaler/aggregation/bucketing.go @@ -166,7 +166,7 @@ func (t *WeightedFloat64Buckets) WindowAverage(now time.Time) float64 { if now.After(t.lastWrite) { numZ := now.Sub(t.lastWrite) / t.granularity // Skip to this multiplier directly: m*(1-m)^(nz-1). - multiplier = multiplier * math.Pow(1-t.smoothingCoeff, float64(numZ)) + multiplier *= math.Pow(1-t.smoothingCoeff, float64(numZ)) // Reduce effective number of buckets. numB -= int(numZ) } diff --git a/pkg/reconciler/revision/table_test.go b/pkg/reconciler/revision/table_test.go index c534b56e7ed8..d390938b362e 100644 --- a/pkg/reconciler/revision/table_test.go +++ b/pkg/reconciler/revision/table_test.go @@ -806,11 +806,11 @@ func deployImagePullSecrets(deploy *appsv1.Deployment, secretName string) *appsv return deploy } -func imagePullSecrets(Revision *caching.Image, secretName string) *caching.Image { - Revision.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{ +func imagePullSecrets(img *caching.Image, secretName string) *caching.Image { + img.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{ Name: secretName, }} - return Revision + return img } func changeContainers(deploy *appsv1.Deployment) *appsv1.Deployment { diff --git a/test/performance/benchmarks/load-test/main.go b/test/performance/benchmarks/load-test/main.go index 82829d82d12f..5c03e3ffd6c7 100644 --- a/test/performance/benchmarks/load-test/main.go +++ b/test/performance/benchmarks/load-test/main.go @@ -187,7 +187,7 @@ func checkSLA(results *vegeta.Metrics, pacers []vegeta.Pacer, durations []time.D var expectedSum float64 var expectedRequests uint64 for i := 0; i < len(pacers); i++ { - expectedSum = expectedSum + pacers[i].Rate(time.Second)*durations[i].Seconds() + expectedSum += pacers[i].Rate(time.Second) * durations[i].Seconds() } expectedRequests = uint64(expectedSum) if results.Requests >= expectedRequests-(expectedRequests/1000) { diff --git a/test/test_images/autoscale/autoscale.go b/test/test_images/autoscale/autoscale.go index da0c78e78473..b8266387ff44 100644 --- a/test/test_images/autoscale/autoscale.go +++ b/test/test_images/autoscale/autoscale.go @@ -34,7 +34,7 @@ var mathrand = rand.New(rand.NewSource(time.Now().UnixNano())) // Algorithm from https://stackoverflow.com/a/21854246 // Only primes less than or equal to N will be generated -func primes(N int) []int { +func primes(N int) []int { //nolint var x, y, n int nsqrt := math.Sqrt(float64(N)) diff --git a/test/test_images/multicontainer/servingcontainer/servingcontainer.go b/test/test_images/multicontainer/servingcontainer/servingcontainer.go index 33b64bad9db4..ca56b9b74ca3 100644 --- a/test/test_images/multicontainer/servingcontainer/servingcontainer.go +++ b/test/test_images/multicontainer/servingcontainer/servingcontainer.go @@ -37,8 +37,8 @@ func handler(w http.ResponseWriter, _ *http.Request) { if err != nil { log.Fatal(err) } - defer res.Body.Close() resp, err := io.ReadAll(res.Body) + res.Body.Close() if err != nil { log.Fatal(err) } diff --git a/test/test_images/readiness/readiness.go b/test/test_images/readiness/readiness.go index a9f9643e6b29..f234def0fff8 100644 --- a/test/test_images/readiness/readiness.go +++ b/test/test_images/readiness/readiness.go @@ -104,9 +104,10 @@ func execProbeMain() { if err != nil { log.Fatal("Failed to probe: ", err) } - defer resp.Body.Close() + resp.Body.Close() if resp.StatusCode > 299 { os.Exit(1) + return } os.Exit(0) } From 18ea7bd615c904b803920c1891c2d478a9d62eeb Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 19:30:05 -0500 Subject: [PATCH 32/35] fix intrange linter --- cmd/schema-tweak/overrides.go | 2 +- pkg/activator/config/store_test.go | 2 +- .../handler/concurrency_reporter_test.go | 8 ++++---- pkg/activator/handler/context_handler_test.go | 2 +- pkg/activator/handler/handler_test.go | 4 ++-- pkg/activator/handler/healthz_handler_test.go | 2 +- pkg/activator/handler/main_test.go | 10 +++++----- pkg/activator/handler/metric_handler_test.go | 2 +- pkg/activator/handler/probe_handler_test.go | 2 +- pkg/activator/net/helpers_test.go | 6 +++--- pkg/activator/net/lb_policy.go | 2 +- pkg/activator/net/lb_policy_test.go | 4 ++-- pkg/activator/net/revision_backends_test.go | 4 ++-- pkg/activator/net/throttler_test.go | 8 ++++---- pkg/activator/stat_reporter_test.go | 2 +- pkg/apis/config/features_test.go | 2 +- pkg/autoscaler/aggregation/bucketing.go | 4 ++-- pkg/autoscaler/aggregation/bucketing_test.go | 16 ++++++++-------- .../aggregation/max/timewindow_test.go | 8 ++++---- pkg/autoscaler/bucket/bucket.go | 2 +- pkg/autoscaler/metrics/collector_test.go | 8 ++++---- .../metrics/http_scrape_client_test.go | 2 +- pkg/autoscaler/metrics/stats_scraper.go | 4 ++-- pkg/autoscaler/metrics/stats_scraper_test.go | 6 +++--- pkg/autoscaler/scaling/autoscaler_test.go | 4 ++-- pkg/autoscaler/statserver/server_test.go | 4 ++-- pkg/http/handler/timeout_test.go | 2 +- pkg/http/request_log_test.go | 4 ++-- pkg/metrics/tags_test.go | 2 +- pkg/queue/breaker.go | 2 +- pkg/queue/breaker_test.go | 6 +++--- pkg/queue/forwarded_shim_test.go | 2 +- pkg/queue/handler_test.go | 6 +++--- pkg/queue/readiness/probe_test.go | 2 +- pkg/queue/request_metric_test.go | 6 +++--- pkg/queue/sharedmain/main_test.go | 2 +- pkg/reconciler/autoscaling/kpa/kpa_test.go | 2 +- pkg/reconciler/gc/gc.go | 2 +- pkg/reconciler/revision/background.go | 2 +- pkg/reconciler/revision/background_test.go | 4 ++-- pkg/reconciler/revision/rate_limiter_test.go | 8 ++++---- .../serverlessservice/serverlessservice_test.go | 4 ++-- pkg/resources/endpoints_test.go | 4 ++-- pkg/resources/pods_test.go | 6 +++--- test/conformance/api/shared/util.go | 2 +- test/conformance/api/v1/single_threaded_test.go | 2 +- test/e2e/activator_test.go | 2 +- test/e2e/e2e.go | 4 ++-- test/e2e/grpc_test.go | 6 +++--- test/e2e/scale.go | 2 +- test/e2e/websocket_test.go | 2 +- test/ha/workload_test.go | 2 +- test/performance/benchmarks/load-test/main.go | 2 +- .../benchmarks/real-traffic-test/main.go | 6 +++--- .../benchmarks/scale-from-zero/main.go | 10 +++++----- test/test_images/autoscale/autoscale.go | 2 +- 56 files changed, 114 insertions(+), 114 deletions(-) diff --git a/cmd/schema-tweak/overrides.go b/cmd/schema-tweak/overrides.go index 48b75287bddd..9e4c784de3b7 100644 --- a/cmd/schema-tweak/overrides.go +++ b/cmd/schema-tweak/overrides.go @@ -409,7 +409,7 @@ func revisionSpecFields() []string { revType = reflect.TypeOf(v1.RevisionSpec{}) ) - for i := 0; i < revType.NumField(); i++ { + for i := range revType.NumField() { if revType.Field(i).Name == "PodSpec" { continue } diff --git a/pkg/activator/config/store_test.go b/pkg/activator/config/store_test.go index 2152b7badf34..5947706a6592 100644 --- a/pkg/activator/config/store_test.go +++ b/pkg/activator/config/store_test.go @@ -86,7 +86,7 @@ func BenchmarkStoreToContext(b *testing.B) { store.OnConfigChanged(tracingConfig) b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { store.ToContext(context.Background()) } }) diff --git a/pkg/activator/handler/concurrency_reporter_test.go b/pkg/activator/handler/concurrency_reporter_test.go index 0b80ca5a9fbe..ff5b876dd2a4 100644 --- a/pkg/activator/handler/concurrency_reporter_test.go +++ b/pkg/activator/handler/concurrency_reporter_test.go @@ -638,7 +638,7 @@ func BenchmarkConcurrencyReporterHandler(b *testing.B) { // Spread the load across 100 revisions. reqs := make([]*http.Request, 0, 100) - for i := 0; i < cap(reqs); i++ { + for i := range cap(reqs) { key := types.NamespacedName{ Namespace: testNamespace, Name: testRevName + strconv.Itoa(i), @@ -654,7 +654,7 @@ func BenchmarkConcurrencyReporterHandler(b *testing.B) { resp := httptest.NewRecorder() b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for j := range b.N { req := reqs[j%len(reqs)] handler.ServeHTTP(resp, req) } @@ -687,7 +687,7 @@ func BenchmarkConcurrencyReporterReport(b *testing.B) { fake := fakeservingclient.Get(ctx) revisions := fakerevisioninformer.Get(ctx) - for i := 0; i < revs; i++ { + for i := range revs { key := types.NamespacedName{ Namespace: testNamespace, Name: testRevName + strconv.Itoa(i), @@ -706,7 +706,7 @@ func BenchmarkConcurrencyReporterReport(b *testing.B) { }) } - for j := 0; j < b.N; j++ { + for range b.N { cr.report(time.Now()) } }) diff --git a/pkg/activator/handler/context_handler_test.go b/pkg/activator/handler/context_handler_test.go index 52a73467433f..ebcb0347b619 100644 --- a/pkg/activator/handler/context_handler_test.go +++ b/pkg/activator/handler/context_handler_test.go @@ -137,7 +137,7 @@ func BenchmarkContextHandler(b *testing.B) { req.Header.Set(activator.RevisionHeaderName, test.revisionName) b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/activator/handler/handler_test.go b/pkg/activator/handler/handler_test.go index 9877517712d1..353159b9ef37 100644 --- a/pkg/activator/handler/handler_test.go +++ b/pkg/activator/handler/handler_test.go @@ -103,7 +103,7 @@ func TestActivationHandler(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { probeResponses := make([]activatortest.FakeResponse, len(test.probeResp)) - for i := 0; i < len(test.probeResp); i++ { + for i := range len(test.probeResp) { probeResponses[i] = activatortest.FakeResponse{ Err: test.probeErr, Code: test.probeCode, @@ -369,7 +369,7 @@ func BenchmarkHandler(b *testing.B) { b.Run(fmt.Sprintf("%03dk-resp-len-sequential", bodyLength), func(b *testing.B) { req := request() - for j := 0; j < b.N; j++ { + for range b.N { test(req, b) } }) diff --git a/pkg/activator/handler/healthz_handler_test.go b/pkg/activator/handler/healthz_handler_test.go index b943d5fc4bea..e3382484dda3 100644 --- a/pkg/activator/handler/healthz_handler_test.go +++ b/pkg/activator/handler/healthz_handler_test.go @@ -108,7 +108,7 @@ func BenchmarkHealthHandler(b *testing.B) { req.Header = test.headers b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/activator/handler/main_test.go b/pkg/activator/handler/main_test.go index b21a98ca0480..133e92ab5be7 100644 --- a/pkg/activator/handler/main_test.go +++ b/pkg/activator/handler/main_test.go @@ -106,7 +106,7 @@ func BenchmarkHandlerChain(b *testing.B) { b.Run("sequential", func(b *testing.B) { req := request() - for j := 0; j < b.N; j++ { + for range b.N { test(req, b) } }) @@ -213,18 +213,18 @@ func TestActivatorChainHandlerWithFullDuplex(t *testing.T) { } body := make([]byte, bodySize) - for i := 0; i < cap(body); i++ { + for i := range cap(body) { body[i] = 42 } - for i := 0; i < 10; i++ { + for range 10 { var wg sync.WaitGroup wg.Add(parallelism) - for i := 0; i < parallelism; i++ { + for i := range parallelism { go func(i int) { defer wg.Done() - for i := 0; i < 100; i++ { + for range 100 { if err := send(c, proxyServer.URL, body, "test-host"); err != nil { t.Errorf("error during request: %v", err) } diff --git a/pkg/activator/handler/metric_handler_test.go b/pkg/activator/handler/metric_handler_test.go index d7a385c65d54..e62f69178377 100644 --- a/pkg/activator/handler/metric_handler_test.go +++ b/pkg/activator/handler/metric_handler_test.go @@ -134,7 +134,7 @@ func BenchmarkMetricHandler(b *testing.B) { resp := httptest.NewRecorder() b.Run("sequential", func(b *testing.B) { req := httptest.NewRequest(http.MethodGet, "http://example.com", nil).WithContext(reqCtx) - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/activator/handler/probe_handler_test.go b/pkg/activator/handler/probe_handler_test.go index b1138d1fa982..03ebda1bff03 100644 --- a/pkg/activator/handler/probe_handler_test.go +++ b/pkg/activator/handler/probe_handler_test.go @@ -127,7 +127,7 @@ func BenchmarkProbeHandler(b *testing.B) { req.Header = test.headers b.Run(test.label+"-sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/activator/net/helpers_test.go b/pkg/activator/net/helpers_test.go index 7e0cb0702f16..0c7457391685 100644 --- a/pkg/activator/net/helpers_test.go +++ b/pkg/activator/net/helpers_test.go @@ -201,7 +201,7 @@ func BenchmarkHealthyAddresses(b *testing.B) { for _, n := range []int{1, 10, 100, 1000, 10000} { b.Run(fmt.Sprint("addresses-", n), func(b *testing.B) { ep := eps(10, n) - for i := 0; i < b.N; i++ { + for range b.N { healthyAddresses(ep, networking.ServicePortNameHTTP1) } }) @@ -212,7 +212,7 @@ func BenchmarkEndpointsToDests(b *testing.B) { for _, n := range []int{1, 10, 100, 1000, 10000} { b.Run(fmt.Sprint("addresses-", n), func(b *testing.B) { ep := eps(10, n) - for i := 0; i < b.N; i++ { + for range b.N { endpointsToDests(ep, networking.ServicePortNameHTTP1) } }) @@ -240,7 +240,7 @@ func eps(activators, apps int) *corev1.Endpoints { func addresses(prefix string, n int) []corev1.EndpointAddress { addrs := make([]corev1.EndpointAddress, 0, n) - for i := 0; i < n; i++ { + for i := range n { addrs = append(addrs, corev1.EndpointAddress{ IP: fmt.Sprintf("%s-%d", prefix, i), }) diff --git a/pkg/activator/net/lb_policy.go b/pkg/activator/net/lb_policy.go index b114a1f6b7f5..7e7f689c86c2 100644 --- a/pkg/activator/net/lb_policy.go +++ b/pkg/activator/net/lb_policy.go @@ -102,7 +102,7 @@ func newRoundRobinPolicy() lbPolicy { // Now for |targets| elements and check every next one in // round robin fashion. - for i := 0; i < l; i++ { + for i := range l { p := (idx + i) % l if cb, ok := targets[p].Reserve(ctx); ok { // We want to start with the next index. diff --git a/pkg/activator/net/lb_policy_test.go b/pkg/activator/net/lb_policy_test.go index 2a460965d132..ffdd4fb098d5 100644 --- a/pkg/activator/net/lb_policy_test.go +++ b/pkg/activator/net/lb_policy_test.go @@ -30,7 +30,7 @@ func TestRandomChoice_TwoTrackersDistribution(t *testing.T) { counts := map[string]int{} total := 100 - for i := 0; i < total; i++ { + for range total { cb, pt := randomChoice2Policy(context.Background(), podTrackers) cb() counts[pt.dest]++ @@ -280,7 +280,7 @@ func BenchmarkPolicy(b *testing.B) { for _, n := range []int{1, 2, 3, 10, 100} { b.Run(fmt.Sprintf("%s-%d-trackers-sequential", test.name, n), func(b *testing.B) { targets := makeTrackers(n, 0) - for i := 0; i < b.N; i++ { + for range b.N { cb, _ := test.policy(nil, targets) cb() } diff --git a/pkg/activator/net/revision_backends_test.go b/pkg/activator/net/revision_backends_test.go index 1f9e59b10ae2..9e1f1e2e1d0f 100644 --- a/pkg/activator/net/revision_backends_test.go +++ b/pkg/activator/net/revision_backends_test.go @@ -566,7 +566,7 @@ func TestRevisionWatcher(t *testing.T) { destsCh <- tc.dests updates := []revisionDestsUpdate{} - for i := 0; i < len(tc.expectUpdates); i++ { + for range len(tc.expectUpdates) { select { case update := <-updateCh: updates = append(updates, update) @@ -933,7 +933,7 @@ func TestRevisionBackendManagerAddEndpoint(t *testing.T) { revDests := make(map[types.NamespacedName]revisionDestsUpdate) // Wait for updateCb to be called - for i := 0; i < tc.updateCnt; i++ { + for range tc.updateCnt { select { case update := <-rbm.updates(): revDests[update.Rev] = update diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index bb4f9b47db5d..22f4c1eb8a8b 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -276,7 +276,7 @@ func TestThrottlerCalculateCapacity(t *testing.T) { func makeTrackers(num, cc int) []*podTracker { x := make([]*podTracker, num) - for i := 0; i < num; i++ { + for i := range num { x[i] = newPodTracker(strconv.Itoa(i), nil) if cc > 0 { x[i].b = queue.NewBreaker(queue.BreakerParams{ @@ -584,7 +584,7 @@ func TestThrottlerSuccesses(t *testing.T) { }) gotDests := sets.New[string]() - for i := 0; i < tc.requests; i++ { + for range tc.requests { result := <-resultChan gotDests.Insert(result.dest) } @@ -911,7 +911,7 @@ func (t *Throttler) try(ctx context.Context, requests int, try func(string) erro resultChan := make(chan tryResult) revID := types.NamespacedName{Namespace: testNamespace, Name: testRevision} - for i := 0; i < requests; i++ { + for range requests { go func() { var result tryResult if err := t.Try(ctx, revID, func(dest string) error { @@ -954,7 +954,7 @@ func TestInfiniteBreaker(t *testing.T) { // Verify we call the thunk when we have achieved capacity. // Twice. - for i := 0; i < 2; i++ { + for range 2 { ctx, cancel := context.WithCancel(context.Background()) cancel() res := false diff --git a/pkg/activator/stat_reporter_test.go b/pkg/activator/stat_reporter_test.go index 02fb68c11772..785f28d1fa4b 100644 --- a/pkg/activator/stat_reporter_test.go +++ b/pkg/activator/stat_reporter_test.go @@ -62,7 +62,7 @@ func TestReportStats(t *testing.T) { received := make(chan struct{}) output := make([][]byte, len(inputs)) go func() { - for i := 0; i < len(inputs); i++ { + for i := range inputs { output[i] = <-results } close(received) diff --git a/pkg/apis/config/features_test.go b/pkg/apis/config/features_test.go index 0995c2f56061..b3d1213871c9 100644 --- a/pkg/apis/config/features_test.go +++ b/pkg/apis/config/features_test.go @@ -697,7 +697,7 @@ func defaultWith(p *Features) *Features { f := defaultFeaturesConfig() pType := reflect.ValueOf(p).Elem() fType := reflect.ValueOf(f).Elem() - for i := 0; i < pType.NumField(); i++ { + for i := range pType.NumField() { if pType.Field(i).Interface().(Flag) != "" { fType.Field(i).Set(pType.Field(i)) } diff --git a/pkg/autoscaler/aggregation/bucketing.go b/pkg/autoscaler/aggregation/bucketing.go index baf289cea94e..4e44616898ae 100644 --- a/pkg/autoscaler/aggregation/bucketing.go +++ b/pkg/autoscaler/aggregation/bucketing.go @@ -172,7 +172,7 @@ func (t *WeightedFloat64Buckets) WindowAverage(now time.Time) float64 { } startIdx := t.timeToIndex(t.lastWrite) + totalB // To ensure always positive % operation. ret := 0. - for i := 0; i < numB; i++ { + for i := range numB { effectiveIdx := (startIdx - i) % totalB v := t.buckets[effectiveIdx] * multiplier ret += v @@ -336,7 +336,7 @@ func (t *TimedFloat64Buckets) ResizeWindow(w time.Duration) { // `newBuckets` buckets. oldNumBuckets := len(t.buckets) tIdx := t.timeToIndex(t.lastWrite) - for i := 0; i < min(numBuckets, oldNumBuckets); i++ { + for range min(numBuckets, oldNumBuckets) { oi := tIdx % oldNumBuckets ni := tIdx % numBuckets newBuckets[ni] = t.buckets[oi] diff --git a/pkg/autoscaler/aggregation/bucketing_test.go b/pkg/autoscaler/aggregation/bucketing_test.go index e88642b4c361..504bf59d3a9c 100644 --- a/pkg/autoscaler/aggregation/bucketing_test.go +++ b/pkg/autoscaler/aggregation/bucketing_test.go @@ -132,9 +132,9 @@ func TestTimedFloat64BucketsSimple(t *testing.T) { func TestTimedFloat64BucketsManyReps(t *testing.T) { trunc1 := time.Now().Truncate(granularity) buckets := NewTimedFloat64Buckets(time.Minute, granularity) - for p := 0; p < 5; p++ { + for p := range 5 { trunc1 = trunc1.Add(granularity) - for t := 0; t < 5; t++ { + for t := range 5 { buckets.Record(trunc1, float64(p+t)) } } @@ -168,9 +168,9 @@ func TestTimedFloat64BucketsManyRepsWithNonMonotonicalOrder(t *testing.T) { buckets := NewTimedFloat64Buckets(time.Minute, granularity) d := []int{0, 3, 2, 1, 4} - for p := 0; p < 5; p++ { + for p := range 5 { end = start.Add(time.Duration(d[p]) * granularity) - for t := 0; t < 5; t++ { + for t := range 5 { buckets.Record(end, float64(p+t)) } } @@ -222,7 +222,7 @@ func TestTimedFloat64BucketsWeightedAverage(t *testing.T) { } // Fill the whole window, with [2, 3, 4, 5, 6] - for i := 0; i < 5; i++ { + for i := range 5 { buckets.Record(now.Add(time.Duration(2+i)*time.Second), float64(i+2)) } // Manually compute wanted average. @@ -612,10 +612,10 @@ func BenchmarkWindowAverage(b *testing.B) { buckets := NewTimedFloat64Buckets(time.Duration(wl)*time.Second, time.Second /*granularity*/) // Populate with some random data. - for i := 0; i < wl; i++ { + for i := range wl { buckets.Record(tn.Add(time.Duration(i)*time.Second), rand.Float64()*100) } - for i := 0; i < b.N; i++ { + for range b.N { buckets.WindowAverage(tn.Add(time.Duration(wl) * time.Second)) } }) @@ -650,7 +650,7 @@ func (t *TimedFloat64Buckets) forEachBucket(now time.Time, acc func(time time.Ti numBuckets := len(t.buckets) - int(now.Sub(t.lastWrite)/t.granularity) bucketTime := t.lastWrite // Always aligned with granularity. si := t.timeToIndex(bucketTime) - for i := 0; i < numBuckets; i++ { + for range numBuckets { tIdx := si % len(t.buckets) acc(bucketTime, t.buckets[tIdx]) si-- diff --git a/pkg/autoscaler/aggregation/max/timewindow_test.go b/pkg/autoscaler/aggregation/max/timewindow_test.go index 1dc9edc9cadf..a7c72bbc989c 100644 --- a/pkg/autoscaler/aggregation/max/timewindow_test.go +++ b/pkg/autoscaler/aggregation/max/timewindow_test.go @@ -93,7 +93,7 @@ func TestTimedWindowMax(t *testing.T) { func BenchmarkLargeTimeWindowCreate(b *testing.B) { for _, duration := range []time.Duration{5 * time.Minute, 15 * time.Minute, 30 * time.Minute, 45 * time.Minute} { b.Run(fmt.Sprintf("duration-%v", duration), func(b *testing.B) { - for i := 0; i < b.N; i++ { + for range b.N { _ = NewTimeWindow(duration, 1*time.Second) } }) @@ -104,7 +104,7 @@ func BenchmarkLargeTimeWindowRecord(b *testing.B) { w := NewTimeWindow(45*time.Minute, 1*time.Second) now := time.Now() - for i := 0; i < b.N; i++ { + for range b.N { now = now.Add(1 * time.Second) w.Record(now, rand.Int31()) } @@ -114,7 +114,7 @@ func BenchmarkLargeTimeWindowAscendingRecord(b *testing.B) { w := NewTimeWindow(45*time.Minute, 1*time.Second) now := time.Now() - for i := 0; i < b.N; i++ { + for i := range b.N { now = now.Add(1 * time.Second) w.Record(now, int32(i)) } @@ -126,7 +126,7 @@ func BenchmarkLargeTimeWindowDescendingRecord(b *testing.B) { w := NewTimeWindow(time.Duration(d)*time.Minute, 1*time.Second) now := time.Now() - for i := 0; i < b.N; i++ { + for i := range b.N { now = now.Add(1 * time.Second) w.Record(now, int32(math.MaxInt32-i)) } diff --git a/pkg/autoscaler/bucket/bucket.go b/pkg/autoscaler/bucket/bucket.go index a6eb2fad4710..37fb5f0b58f6 100644 --- a/pkg/autoscaler/bucket/bucket.go +++ b/pkg/autoscaler/bucket/bucket.go @@ -46,7 +46,7 @@ func AutoscalerBucketName(ordinal, total uint32) string { // buckets with the given `total` count. func AutoscalerBucketSet(total uint32) *hash.BucketSet { names := make(sets.Set[string], total) - for i := uint32(0); i < total; i++ { + for i := range total { names.Insert(AutoscalerBucketName(i, total)) } return hash.NewBucketSet(names) diff --git a/pkg/autoscaler/metrics/collector_test.go b/pkg/autoscaler/metrics/collector_test.go index 5b842e19a079..5ff61dd7eccc 100644 --- a/pkg/autoscaler/metrics/collector_test.go +++ b/pkg/autoscaler/metrics/collector_test.go @@ -176,12 +176,12 @@ func TestMetricCollectorScraperMovingTime(t *testing.T) { coll.CreateOrUpdate(&defaultMetric) // Tick three times. Time doesn't matter since we use the time on the Stat. - for i := 0; i < 3; i++ { + for range 3 { mtp.Channel <- now } now = now.Add(time.Second) fc.SetTime(now) - for i := 0; i < 4; i++ { + for range 4 { mtp.Channel <- now } var gotRPS, gotConcurrency, panicRPS, panicConcurrency float64 @@ -252,7 +252,7 @@ func TestMetricCollectorScraper(t *testing.T) { coll.CreateOrUpdate(&defaultMetric) // Tick three times. Time doesn't matter since we use the time on the Stat. - for i := 0; i < 3; i++ { + for range 3 { mtp.Channel <- now } var gotRPS, gotConcurrency, panicRPS, panicConcurrency float64 @@ -341,7 +341,7 @@ func TestMetricCollectorNoScraper(t *testing.T) { noTargetMetric.Spec.ScrapeTarget = "" coll.CreateOrUpdate(&noTargetMetric) // Tick three times. Time doesn't matter since we use the time on the Stat. - for i := 0; i < 3; i++ { + for range 3 { mtp.Channel <- now now = now.Add(time.Second) fc.SetTime(now) diff --git a/pkg/autoscaler/metrics/http_scrape_client_test.go b/pkg/autoscaler/metrics/http_scrape_client_test.go index b1a27d06917f..9d0b99288dee 100644 --- a/pkg/autoscaler/metrics/http_scrape_client_test.go +++ b/pkg/autoscaler/metrics/http_scrape_client_test.go @@ -197,7 +197,7 @@ func BenchmarkUnmarshallingProtoData(b *testing.B) { b.Fatal(err) } b.Run(bm.name, func(b *testing.B) { - for i := 0; i < b.N; i++ { + for range b.N { _, err = statFromProto(bytes.NewReader(bodyBytes)) if err != nil { b.Fatal(err) diff --git a/pkg/autoscaler/metrics/stats_scraper.go b/pkg/autoscaler/metrics/stats_scraper.go index 8f34cababb78..fa97b44b206a 100644 --- a/pkg/autoscaler/metrics/stats_scraper.go +++ b/pkg/autoscaler/metrics/stats_scraper.go @@ -280,7 +280,7 @@ func (s *serviceScraper) scrapePods(window time.Duration) (Stat, error) { idx.Store(-1) var sawNonMeshError atomic.Bool // Start |sampleSize| threads to scan in parallel. - for i := 0; i < sampleSize; i++ { + for range sampleSize { grp.Go(func() error { // If a given pod failed to scrape, we want to continue // scanning pods down the line. @@ -379,7 +379,7 @@ func (s *serviceScraper) scrapeService(window time.Duration) (Stat, error) { grp, egCtx := errgroup.WithContext(context.Background()) youngPodCutOffSecs := window.Seconds() - for i := 0; i < sampleSize; i++ { + for range sampleSize { grp.Go(func() error { for tries := 1; ; tries++ { stat, err := s.tryScrape(egCtx, scrapedPods) diff --git a/pkg/autoscaler/metrics/stats_scraper_test.go b/pkg/autoscaler/metrics/stats_scraper_test.go index 2fffac4ba570..5494a979a47e 100644 --- a/pkg/autoscaler/metrics/stats_scraper_test.go +++ b/pkg/autoscaler/metrics/stats_scraper_test.go @@ -79,7 +79,7 @@ func testStatsWithTime(n int, youngestSecs float64) []Stat { RequestCount: 2, ProxiedRequestCount: 4, } - for i := 0; i < n; i++ { + for i := range n { s := tmpl s.PodName = "pod-" + strconv.Itoa(i) s.AverageConcurrentRequests = float64((i + 1) * 2) @@ -693,7 +693,7 @@ func TestOldPodsFallback(t *testing.T) { client := newTestScrapeClient(testStats, func() []error { r := make([]error, numPods) // This will fail all the old pods. - for i := 0; i < oldPods; i++ { + for i := range oldPods { r[i] = errors.New("bad-hair-day") } // But succeed all the youngs. @@ -850,7 +850,7 @@ func TestURLFromTarget(t *testing.T) { } func makePods(ctx context.Context, prefix string, n int, startTime metav1.Time) { - for i := 0; i < n; i++ { + for i := range n { p := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: prefix + strconv.Itoa(i), diff --git a/pkg/autoscaler/scaling/autoscaler_test.go b/pkg/autoscaler/scaling/autoscaler_test.go index 69fe3bd00fb1..48547ff11663 100644 --- a/pkg/autoscaler/scaling/autoscaler_test.go +++ b/pkg/autoscaler/scaling/autoscaler_test.go @@ -633,7 +633,7 @@ func TestStartInPanicMode(t *testing.T) { } pc := &fakePodCounter{} - for i := 0; i < 2; i++ { + for i := range 2 { pc.readyCount = i a := newAutoscaler(context.Background(), testNamespace, testRevision, metrics, pc, deciderSpec, nil) if !a.panicTime.IsZero() { @@ -731,7 +731,7 @@ func BenchmarkAutoscaler(b *testing.B) { a := newTestAutoscalerNoPC(10, 101, metrics) now := time.Now() - for i := 0; i < b.N; i++ { + for range b.N { a.Scale(logtesting.TestLogger(b), now) } } diff --git a/pkg/autoscaler/statserver/server_test.go b/pkg/autoscaler/statserver/server_test.go index 86febddd0d9e..1e9aeef3ecdd 100644 --- a/pkg/autoscaler/statserver/server_test.go +++ b/pkg/autoscaler/statserver/server_test.go @@ -214,12 +214,12 @@ func BenchmarkStatServer(b *testing.B) { // the respective number of active revisions, sending via the activator. for _, size := range []int{1, 2, 5, 10, 20, 50, 100} { msgs := make([]metrics.StatMessage, 0, size) - for i := 0; i < size; i++ { + for range size { msgs = append(msgs, msg1) } b.Run(fmt.Sprintf("proto-encoding-%d-msgs", len(msgs)), func(b *testing.B) { - for i := 0; i < b.N; i++ { + for range b.N { if err := sendProto(statSink, msgs); err != nil { b.Fatal("Expected send to succeed, but got:", err) } diff --git a/pkg/http/handler/timeout_test.go b/pkg/http/handler/timeout_test.go index 55109ab900b0..061a691eef60 100644 --- a/pkg/http/handler/timeout_test.go +++ b/pkg/http/handler/timeout_test.go @@ -413,7 +413,7 @@ func BenchmarkTimeoutHandler(b *testing.B) { b.Run("sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/http/request_log_test.go b/pkg/http/request_log_test.go index 4fe808083262..0895377fd931 100644 --- a/pkg/http/request_log_test.go +++ b/pkg/http/request_log_test.go @@ -242,7 +242,7 @@ func BenchmarkRequestLogHandlerNoTemplate(b *testing.B) { resp := httptest.NewRecorder() b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) @@ -267,7 +267,7 @@ func BenchmarkRequestLogHandlerDefaultTemplate(b *testing.B) { resp := httptest.NewRecorder() b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/metrics/tags_test.go b/pkg/metrics/tags_test.go index 66e33f4c6470..135ca8342342 100644 --- a/pkg/metrics/tags_test.go +++ b/pkg/metrics/tags_test.go @@ -232,7 +232,7 @@ func BenchmarkPodRevisionContext(b *testing.B) { for _, revisions := range []int{1, 1024, 4095, 0xFFFF, 409600} { b.Run(fmt.Sprintf("sequential-%d-revisions", revisions), func(b *testing.B) { contextCache.Purge() - for i := 0; i < b.N; i++ { + for range b.N { rev := "name" + strconv.Itoa(rand.Intn(revisions)) PodRevisionContext("pod", "container", "ns", "svc", "cfg", rev) } diff --git a/pkg/queue/breaker.go b/pkg/queue/breaker.go index 2968c77465bf..50f68c3b4dda 100644 --- a/pkg/queue/breaker.go +++ b/pkg/queue/breaker.go @@ -276,7 +276,7 @@ func (s *semaphore) updateCapacity(size int) { if s.state.CompareAndSwap(old, pack(s64, in)) { if s64 > capacity { - for i := uint64(0); i < s64-capacity; i++ { + for range s64 - capacity { select { case s.queue <- struct{}{}: default: diff --git a/pkg/queue/breaker_test.go b/pkg/queue/breaker_test.go index 79044873579a..547959a1da54 100644 --- a/pkg/queue/breaker_test.go +++ b/pkg/queue/breaker_test.go @@ -253,7 +253,7 @@ func TestSemaphoreAcquireHasCapacity(t *testing.T) { tryAcquire(sem, gotChan) sem.updateCapacity(1) // Allows 1 acquire - for i := 0; i < want; i++ { + for range want { select { case <-gotChan: // Successfully acquired a token. @@ -380,7 +380,7 @@ func BenchmarkBreakerMaybe(b *testing.B) { breaker := NewBreaker(BreakerParams{QueueDepth: 10000000, MaxConcurrency: c, InitialCapacity: c}) b.Run(fmt.Sprintf("%d-sequential", c), func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { breaker.Maybe(context.Background(), op) } }) @@ -400,7 +400,7 @@ func BenchmarkBreakerReserve(b *testing.B) { breaker := NewBreaker(BreakerParams{QueueDepth: 1, MaxConcurrency: 10000000, InitialCapacity: 10000000}) b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { free, got := breaker.Reserve(context.Background()) op() if got { diff --git a/pkg/queue/forwarded_shim_test.go b/pkg/queue/forwarded_shim_test.go index 67a4cd2d514d..87a49f53ee63 100644 --- a/pkg/queue/forwarded_shim_test.go +++ b/pkg/queue/forwarded_shim_test.go @@ -119,7 +119,7 @@ func TestForwardedShimHandler(t *testing.T) { } func BenchmarkForwardedShimHandler(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { generateForwarded("127.0.0.1,127.0.0.2,::1", "http", "localhost") } } diff --git a/pkg/queue/handler_test.go b/pkg/queue/handler_test.go index adc7d803f1e8..201444393cd5 100644 --- a/pkg/queue/handler_test.go +++ b/pkg/queue/handler_test.go @@ -52,7 +52,7 @@ func TestHandlerBreakerQueueFull(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "http://localhost:8081/time", nil) resps := make(chan *httptest.ResponseRecorder) - for i := 0; i < 3; i++ { + for range 3 { go func() { rec := httptest.NewRecorder() h(rec, req) @@ -73,7 +73,7 @@ func TestHandlerBreakerQueueFull(t *testing.T) { // Allow the remaining requests to pass. close(resp) - for i := 0; i < 2; i++ { + for range 2 { res := <-resps if got, want := res.Code, http.StatusOK; got != want { t.Errorf("Code = %d, want: %d", got, want) @@ -265,7 +265,7 @@ func BenchmarkProxyHandler(b *testing.B) { h := ProxyHandler(tc.breaker, stats, true /*tracingEnabled*/, baseHandler) b.Run("sequential-"+tc.label, func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { h(resp, req) } }) diff --git a/pkg/queue/readiness/probe_test.go b/pkg/queue/readiness/probe_test.go index 67307e881392..d42f5b98da4e 100644 --- a/pkg/queue/readiness/probe_test.go +++ b/pkg/queue/readiness/probe_test.go @@ -292,7 +292,7 @@ func TestHTTPManyParallel(t *testing.T) { }}) var grp errgroup.Group - for i := 0; i < 2; i++ { + for range 2 { grp.Go(func() error { if !pb.ProbeContainer() { return errors.New("failed to probe container") diff --git a/pkg/queue/request_metric_test.go b/pkg/queue/request_metric_test.go index 79bd841d4fdb..1482be00d646 100644 --- a/pkg/queue/request_metric_test.go +++ b/pkg/queue/request_metric_test.go @@ -196,7 +196,7 @@ func BenchmarkNewRequestMetricsHandler(b *testing.B) { req := httptest.NewRequest(http.MethodPost, targetURI, nil) b.Run("sequential", func(b *testing.B) { - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) @@ -297,7 +297,7 @@ func BenchmarkRequestMetricsHandler(b *testing.B) { b.Run("sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) @@ -324,7 +324,7 @@ func BenchmarkAppRequestMetricsHandler(b *testing.B) { b.Run("sequential", func(b *testing.B) { resp := httptest.NewRecorder() - for j := 0; j < b.N; j++ { + for range b.N { handler.ServeHTTP(resp, req) } }) diff --git a/pkg/queue/sharedmain/main_test.go b/pkg/queue/sharedmain/main_test.go index a8209fc95d30..429e13d98e00 100644 --- a/pkg/queue/sharedmain/main_test.go +++ b/pkg/queue/sharedmain/main_test.go @@ -172,7 +172,7 @@ func TestQueueTraceSpans(t *testing.T) { spanNames = append([]string{"queue_wait"}, spanNames...) } gs := []string{} - for i := 0; i < len(gotSpans); i++ { + for i := range gotSpans { gs = append(gs, gotSpans[i].Name) } t.Log(spanNames) diff --git a/pkg/reconciler/autoscaling/kpa/kpa_test.go b/pkg/reconciler/autoscaling/kpa/kpa_test.go index 9a2ade731bfb..137a955b16eb 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa_test.go +++ b/pkg/reconciler/autoscaling/kpa/kpa_test.go @@ -1784,7 +1784,7 @@ func newTestRevision(namespace, name string) *v1.Revision { func makeReadyPods(num int, ns, n string) []runtime.Object { r := make([]runtime.Object, num) - for i := 0; i < num; i++ { + for i := range num { p := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: n + strconv.Itoa(i), diff --git a/pkg/reconciler/gc/gc.go b/pkg/reconciler/gc/gc.go index 3c27c7625bee..f0ba872800a4 100644 --- a/pkg/reconciler/gc/gc.go +++ b/pkg/reconciler/gc/gc.go @@ -75,7 +75,7 @@ func collect( // If we need `min` to remain, this is the max count of rev can delete. maxIdx := len(revs) - min staleCount := 0 - for i := 0; i < count; i++ { + for i := range count { rev := revs[i] if !isRevisionStale(cfg, rev, logger) { continue diff --git a/pkg/reconciler/revision/background.go b/pkg/reconciler/revision/background.go index b5d03a16746b..a53a0f2f0fd3 100644 --- a/pkg/reconciler/revision/background.go +++ b/pkg/reconciler/revision/background.go @@ -100,7 +100,7 @@ func (r *backgroundResolver) Start(stop <-chan struct{}, maxInFlight int) (done // Run the worker threads. wg.Add(maxInFlight) - for i := 0; i < maxInFlight; i++ { + for range maxInFlight { go func() { defer wg.Done() for { diff --git a/pkg/reconciler/revision/background_test.go b/pkg/reconciler/revision/background_test.go index 1e892966810f..c4cf3e3e70aa 100644 --- a/pkg/reconciler/revision/background_test.go +++ b/pkg/reconciler/revision/background_test.go @@ -158,7 +158,7 @@ func TestResolveInBackground(t *testing.T) { <-done }() - for i := 0; i < 2; i++ { + for i := range 2 { t.Run(fmt.Sprint("iteration", i), func(t *testing.T) { logger := logtesting.TestLogger(t) initContainerStatuses, statuses, err := subject.Resolve(logger, fakeRevision, k8schain.Options{ServiceAccountName: "san"}, sets.New("skip"), timeout) @@ -226,7 +226,7 @@ func TestRateLimitPerItem(t *testing.T) { }() revision := rev("rev", "img1", "img2") - for i := 0; i < 3; i++ { + for i := range 3 { subject.Clear(types.NamespacedName{Name: revision.Name, Namespace: revision.Namespace}) start := time.Now() initResolution, resolution, err := subject.Resolve(logger, revision, k8schain.Options{ServiceAccountName: "san"}, sets.New("skip"), 0) diff --git a/pkg/reconciler/revision/rate_limiter_test.go b/pkg/reconciler/revision/rate_limiter_test.go index cf9cc1cc8a5b..7524e63de9f7 100644 --- a/pkg/reconciler/revision/rate_limiter_test.go +++ b/pkg/reconciler/revision/rate_limiter_test.go @@ -67,14 +67,14 @@ func TestItemExponentialFailureRateLimiter(t *testing.T) { func TestItemExponentialFailureRateLimiterOverFlow(t *testing.T) { limiter := newItemExponentialFailureRateLimiter(1*time.Millisecond, 1000*time.Second) - for i := 0; i < 5; i++ { + for range 5 { limiter.When("one") } if e, a := 16*time.Millisecond, limiter.When("one"); e != a { t.Errorf("expected %v, got %v", e, a) } - for i := 0; i < 1000; i++ { + for range 1000 { limiter.When("overflow1") } if e, a := 1000*time.Second, limiter.When("overflow1"); e != a { @@ -82,14 +82,14 @@ func TestItemExponentialFailureRateLimiterOverFlow(t *testing.T) { } limiter = newItemExponentialFailureRateLimiter(1*time.Minute, 1000*time.Hour) - for i := 0; i < 2; i++ { + for range 2 { limiter.When("two") } if e, a := 2*time.Minute, limiter.When("two"); e != a { t.Errorf("expected %v, got %v", e, a) } - for i := 0; i < 1000; i++ { + for range 1000 { limiter.When("overflow2") } if e, a := 1000*time.Hour, limiter.When("overflow2"); e != a { diff --git a/pkg/reconciler/serverlessservice/serverlessservice_test.go b/pkg/reconciler/serverlessservice/serverlessservice_test.go index 3a743236f8e2..69ae964d525d 100644 --- a/pkg/reconciler/serverlessservice/serverlessservice_test.go +++ b/pkg/reconciler/serverlessservice/serverlessservice_test.go @@ -881,10 +881,10 @@ func endpointspriv(namespace, name string, eo ...EndpointsOption) *corev1.Endpoi func withNSubsets(numSS, numAddr int) EndpointsOption { return func(ep *corev1.Endpoints) { ep.Subsets = make([]corev1.EndpointSubset, numSS) - for i := 0; i < numSS; i++ { + for i := range numSS { ep.Subsets[i].Ports = []corev1.EndpointPort{{Port: 8012}, {Port: 8013}} ep.Subsets[i].Addresses = make([]corev1.EndpointAddress, numAddr) - for j := 0; j < numAddr; j++ { + for j := range numAddr { ep.Subsets[i].Addresses[j].IP = fmt.Sprintf("10.1.%d.%d", i+1, j+1) } } diff --git a/pkg/resources/endpoints_test.go b/pkg/resources/endpoints_test.go index a789a1bc1738..2d070e3a9b43 100644 --- a/pkg/resources/endpoints_test.go +++ b/pkg/resources/endpoints_test.go @@ -140,11 +140,11 @@ func endpoints(readyIPCount, notReadyIPCount int) *corev1.Endpoints { addresses := make([]corev1.EndpointAddress, readyIPCount) notReadyAddresses := make([]corev1.EndpointAddress, notReadyIPCount) - for i := 0; i < readyIPCount; i++ { + for i := range readyIPCount { addresses[i] = corev1.EndpointAddress{IP: fmt.Sprint("127.0.0.", i*3+1)} } - for i := 0; i < notReadyIPCount; i++ { + for i := range notReadyIPCount { notReadyAddresses[i] = corev1.EndpointAddress{IP: fmt.Sprint("127.0.0.", i*3+2)} } diff --git a/pkg/resources/pods_test.go b/pkg/resources/pods_test.go index df0b0284b97c..ff469968bb27 100644 --- a/pkg/resources/pods_test.go +++ b/pkg/resources/pods_test.go @@ -337,18 +337,18 @@ func phasedPod(name string, phase corev1.PodPhase) *corev1.Pod { func podsInPhases(running, pending, terminating int) []*corev1.Pod { pods := make([]*corev1.Pod, 0, running+pending+terminating) - for i := 0; i < running; i++ { + for i := range running { pods = append(pods, phasedPod("running-pod-"+strconv.Itoa(i), corev1.PodRunning)) } now := metav1.Now() - for i := 0; i < terminating; i++ { + for i := range terminating { p := phasedPod("terminating-pod-"+strconv.Itoa(i), corev1.PodRunning) p.DeletionTimestamp = &now pods = append(pods, p) } - for i := 0; i < pending; i++ { + for i := range pending { pods = append(pods, phasedPod("pending-pod-"+strconv.Itoa(i), corev1.PodPending)) } return pods diff --git a/test/conformance/api/shared/util.go b/test/conformance/api/shared/util.go index 23f5e5ec83b2..4aff02f7ae0f 100644 --- a/test/conformance/api/shared/util.go +++ b/test/conformance/api/shared/util.go @@ -73,7 +73,7 @@ func sendRequests(ctx context.Context, client *spoof.SpoofingClient, url *url.UR // Launch "num" requests, recording the responses we get in "responses". g, gCtx := errgroup.WithContext(ctx) g.SetLimit(8) - for i := 0; i < num; i++ { + for i := range num { // We don't index into "responses" inside the goroutine to avoid a race, see #1545. result := &responses[i] g.Go(func() error { diff --git a/test/conformance/api/v1/single_threaded_test.go b/test/conformance/api/v1/single_threaded_test.go index 0a740ae067c6..2611860a519f 100644 --- a/test/conformance/api/v1/single_threaded_test.go +++ b/test/conformance/api/v1/single_threaded_test.go @@ -86,7 +86,7 @@ func TestSingleConcurrency(t *testing.T) { duration := 20 * time.Second t.Logf("Maintaining %d concurrent requests for %v.", concurrency, duration) group, egCtx := errgroup.WithContext(context.Background()) - for i := 0; i < concurrency; i++ { + for i := range concurrency { threadIdx := i group.Go(func() error { requestIdx := 0 diff --git a/test/e2e/activator_test.go b/test/e2e/activator_test.go index f5e784afb1f9..e06d187d54ae 100644 --- a/test/e2e/activator_test.go +++ b/test/e2e/activator_test.go @@ -95,7 +95,7 @@ func TestActivatorOverload(t *testing.T) { eg, egCtx := errgroup.WithContext(context.Background()) // Send requests async and wait for the responses. - for i := 0; i < concurrency; i++ { + for range concurrency { eg.Go(func() error { // We need to create a new request per HTTP request because // the spoofing client mutates them. diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 8cb35d78630d..dc1e4491d016 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -128,13 +128,13 @@ func waitForActivatorEndpoints(ctx *TestContext) error { wantAct = int(sks.Spec.NumActivators) aset = make(sets.Set[string], wantAct) for _, ss := range actEps.Subsets { - for i := 0; i < len(ss.Addresses); i++ { + for i := range len(ss.Addresses) { aset.Insert(ss.Addresses[i].IP) } } svcSet = make(sets.Set[string], wantAct) for _, ss := range svcEps.Subsets { - for i := 0; i < len(ss.Addresses); i++ { + for i := range len(ss.Addresses) { svcSet.Insert(ss.Addresses[i].IP) } } diff --git a/test/e2e/grpc_test.go b/test/e2e/grpc_test.go index a23a6833ba0c..25a6d4118e50 100644 --- a/test/e2e/grpc_test.go +++ b/test/e2e/grpc_test.go @@ -147,7 +147,7 @@ func loadBalancingTest(ctx *TestContext, host, domain string) { return count } - for i := 0; i < wantHosts; i++ { + for range wantHosts { grp.Go(func() error { for { select { @@ -197,7 +197,7 @@ func loadBalancingTest(ctx *TestContext, host, domain string) { func generateGRPCTraffic(ctx *TestContext, concurrentRequests int, host, domain string, stopChan chan struct{}) error { var grp errgroup.Group - for i := 0; i < concurrentRequests; i++ { + for i := range concurrentRequests { grp.Go(func() error { for j := 0; ; j++ { select { @@ -288,7 +288,7 @@ func streamTest(tc *TestContext, host, domain string) { } const count = 3 - for i := 0; i < count; i++ { + for i := range count { tc.t.Logf("Sending stream %d of %d", i+1, count) want := "This is a short message!" diff --git a/test/e2e/scale.go b/test/e2e/scale.go index 01e4ac6b5a29..5e6d553ad4b8 100644 --- a/test/e2e/scale.go +++ b/test/e2e/scale.go @@ -86,7 +86,7 @@ func ScaleToWithin(t *testing.T, scale int, duration time.Duration, latencies La // TODO(mattmoor): Check globalSLO if localSLO isn't 1.0 }) - for i := 0; i < scale; i++ { + for i := range scale { t.Run(fmt.Sprintf("%03d-of-%03d", i, scale), func(t *testing.T) { t.Parallel() diff --git a/test/e2e/websocket_test.go b/test/e2e/websocket_test.go index de458bbd83db..ec7be61ac064 100644 --- a/test/e2e/websocket_test.go +++ b/test/e2e/websocket_test.go @@ -50,7 +50,7 @@ func webSocketResponseFreqs(t *testing.T, clients *test.Clients, url string, num var g errgroup.Group respCh := make(chan string, numReqs) resps := map[string]int{} - for i := 0; i < numReqs; i++ { + for range numReqs { g.Go(func() error { // Establish the websocket connection. Since they are persistent // we can't reuse. diff --git a/test/ha/workload_test.go b/test/ha/workload_test.go index 55a6452c17f3..b49ea1a9cda5 100644 --- a/test/ha/workload_test.go +++ b/test/ha/workload_test.go @@ -85,7 +85,7 @@ func TestWorkloadHA(t *testing.T) { prober.Spawn(resources.Service.Status.URL.URL()) defer assertSLO(t, prober, 1) - for i := 0; i < repetitionCount; i++ { + for range repetitionCount { deleteUserPods(t, ctx, clients, names.Service) } diff --git a/test/performance/benchmarks/load-test/main.go b/test/performance/benchmarks/load-test/main.go index 5c03e3ffd6c7..7ff1244447e3 100644 --- a/test/performance/benchmarks/load-test/main.go +++ b/test/performance/benchmarks/load-test/main.go @@ -186,7 +186,7 @@ func checkSLA(results *vegeta.Metrics, pacers []vegeta.Pacer, durations []time.D // SLA 4: making sure the defined vegeta total requests is met var expectedSum float64 var expectedRequests uint64 - for i := 0; i < len(pacers); i++ { + for i := range pacers { expectedSum += pacers[i].Rate(time.Second) * durations[i].Seconds() } expectedRequests = uint64(expectedSum) diff --git a/test/performance/benchmarks/real-traffic-test/main.go b/test/performance/benchmarks/real-traffic-test/main.go index cac6bcb98178..e3aa802f88a4 100644 --- a/test/performance/benchmarks/real-traffic-test/main.go +++ b/test/performance/benchmarks/real-traffic-test/main.go @@ -197,7 +197,7 @@ func createServices(clients *test.Clients, count int) ([]*serviceConfig, func(), testNames := make([]*test.ResourceNames, count) // Initialize our service names. - for i := 0; i < count; i++ { + for i := range count { testNames[i] = &test.ResourceNames{ Service: test.AppendRandomString(fmt.Sprintf("%s-%02d", serviceName, i)), // The crd.go helpers will convert to the actual image path. @@ -207,7 +207,7 @@ func createServices(clients *test.Clients, count int) ([]*serviceConfig, func(), cleanupNames := func() { log.Println("Cleaning up all created services") - for i := 0; i < count; i++ { + for i := range count { test.TearDown(clients, testNames[i]) } } @@ -227,7 +227,7 @@ func createServices(clients *test.Clients, count int) ([]*serviceConfig, func(), } g := errgroup.Group{} - for i := 0; i < count; i++ { + for i := range count { ndx := i g.Go(func() error { annotations := map[string]string{config.AllowHTTPFullDuplexFeatureKey: "Enabled"} diff --git a/test/performance/benchmarks/scale-from-zero/main.go b/test/performance/benchmarks/scale-from-zero/main.go index 36f0bb31991e..cfa1b2b653c2 100644 --- a/test/performance/benchmarks/scale-from-zero/main.go +++ b/test/performance/benchmarks/scale-from-zero/main.go @@ -177,7 +177,7 @@ func createServices(clients *test.Clients, count int) ([]*v1test.ResourceObjects testNames := make([]*test.ResourceNames, count) // Initialize our service names. - for i := 0; i < count; i++ { + for i := range count { testNames[i] = &test.ResourceNames{ Service: test.AppendRandomString(fmt.Sprintf("%s-%02d", serviceName, i)), // The crd.go helpers will convert to the actual image path. @@ -186,7 +186,7 @@ func createServices(clients *test.Clients, count int) ([]*v1test.ResourceObjects } cleanupNames := func() { - for i := 0; i < count; i++ { + for i := range count { test.TearDown(clients, testNames[i]) } } @@ -211,7 +211,7 @@ func createServices(clients *test.Clients, count int) ([]*v1test.ResourceObjects ktest.WithServiceLabel(netapi.VisibilityLabelKey, serving.VisibilityClusterLocal), } g := errgroup.Group{} - for i := 0; i < count; i++ { + for i := range count { ndx := i g.Go(func() error { var err error @@ -230,7 +230,7 @@ func createServices(clients *test.Clients, count int) ([]*v1test.ResourceObjects func waitForScaleToZero(ctx context.Context, objs []*v1test.ResourceObjects) error { g := errgroup.Group{} - for i := 0; i < len(objs); i++ { + for i := range objs { idx := i ro := objs[i] g.Go(func() error { @@ -254,7 +254,7 @@ func parallelScaleFromZero(ctx context.Context, clients *test.Clients, objs []*v count := len(objs) var wg sync.WaitGroup wg.Add(count) - for i := 0; i < count; i++ { + for i := range count { ndx := i go func() { defer wg.Done() diff --git a/test/test_images/autoscale/autoscale.go b/test/test_images/autoscale/autoscale.go index b8266387ff44..8c1cf3387ec0 100644 --- a/test/test_images/autoscale/autoscale.go +++ b/test/test_images/autoscale/autoscale.go @@ -69,7 +69,7 @@ func primes(N int) []int { //nolint isPrime[3] = true primes := make([]int, 0, 1270606) - for x = 0; x < len(isPrime)-1; x++ { + for range len(isPrime) - 1 { if isPrime[x] { primes = append(primes, x) } From f8e8ba7c26bd3a2aaff8f7650a90e9d44bcbd07f Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 19:39:21 -0500 Subject: [PATCH 33/35] fix prealloc linter --- cmd/schema-tweak/overrides.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/schema-tweak/overrides.go b/cmd/schema-tweak/overrides.go index 9e4c784de3b7..4089a4ffc6ab 100644 --- a/cmd/schema-tweak/overrides.go +++ b/cmd/schema-tweak/overrides.go @@ -405,8 +405,8 @@ func revSpecOverrides(prefixPath string) []entry { func revisionSpecFields() []string { var ( - fields []string revType = reflect.TypeOf(v1.RevisionSpec{}) + fields = make([]string, 0, revType.NumField()) ) for i := range revType.NumField() { From b6a3c385db88ff46d64705e25e477325140cbf02 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 22:17:10 -0500 Subject: [PATCH 34/35] fix flakey kpa test --- pkg/reconciler/autoscaling/kpa/kpa_test.go | 23 ++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/pkg/reconciler/autoscaling/kpa/kpa_test.go b/pkg/reconciler/autoscaling/kpa/kpa_test.go index 137a955b16eb..f7edd35c9bc0 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa_test.go +++ b/pkg/reconciler/autoscaling/kpa/kpa_test.go @@ -1873,7 +1873,7 @@ func TestMetricsReporter(t *testing.T) { metricstest.IntMetric("pending_pods", 1996, nil).WithResource(wantResource), metricstest.IntMetric("terminating_pods", 1983, nil).WithResource(wantResource), } - metricstest.AssertMetric(t, wantMetrics...) + assertMetric(t, wantMetrics) // Verify `want` is ignored, when it is equal to -1. pc.want = -1 @@ -1888,7 +1888,26 @@ func TestMetricsReporter(t *testing.T) { metricstest.IntMetric("pending_pods", 1996, nil).WithResource(wantResource), metricstest.IntMetric("terminating_pods", 1955, nil).WithResource(wantResource), } - metricstest.AssertMetric(t, wantMetrics...) + assertMetric(t, wantMetrics) +} + +// We don't use metricstest.AssertMetrics because it doesn't filter resources properly +func assertMetric(t *testing.T, values []metricstest.Metric) { + t.Helper() + metricstest.EnsureRecorded() +outer: + for _, v := range values { + metrics := metricstest.GetMetric(v.Name) + for _, m := range metrics { + if cmp.Equal(m.Resource, v.Resource) { + if diff := cmp.Diff(v, m); diff != "" { + t.Error("Wrong metric (-want +got):", diff) + } + continue outer + } + } + t.Fatal("unable to find metrics with name and resource", v.Name, v.Resource) + } } func TestResolveScrapeTarget(t *testing.T) { From 86b4390f8621384d9a044915420b56c2eae0db79 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 12 Jan 2025 22:46:43 -0500 Subject: [PATCH 35/35] fix gofumpt linter --- cmd/activator/main.go | 4 +- cmd/autoscaler/leaderelection.go | 1 - cmd/autoscaler/main.go | 3 +- pkg/activator/activator.go | 14 +- pkg/activator/certificate/cache_test.go | 44 +- pkg/activator/handler/handler.go | 3 +- pkg/activator/handler/main_test.go | 1 - pkg/activator/net/revision_backends.go | 6 +- pkg/activator/net/throttler.go | 3 +- pkg/activator/net/throttler_test.go | 3 +- .../autoscaling/v1alpha1/podscalable_types.go | 8 +- pkg/apis/config/features_test.go | 633 +++-- pkg/apis/serving/k8s_validation_test.go | 2527 ++++++++--------- .../v1/configuration_lifecycle_test.go | 1 - .../v1/configuration_validation_test.go | 13 +- .../serving/v1/revision_lifecycle_test.go | 1 - .../serving/v1/revision_validation_test.go | 6 +- pkg/apis/serving/v1/route_lifecycle_test.go | 2 - pkg/apis/serving/v1/route_validation_test.go | 12 +- pkg/apis/serving/v1/service_lifecycle_test.go | 1 - .../serving/v1/service_validation_test.go | 6 +- .../v1beta1/domainmapping_validation_test.go | 12 +- pkg/autoscaler/aggregation/bucketing_test.go | 1 + pkg/autoscaler/bucket/bucket_test.go | 3 +- pkg/autoscaler/metrics/collector.go | 9 +- pkg/autoscaler/metrics/stats_scraper.go | 6 +- pkg/autoscaler/metrics/stats_scraper_test.go | 49 +- pkg/autoscaler/scaling/autoscaler.go | 6 +- pkg/autoscaler/scaling/autoscaler_test.go | 6 +- pkg/autoscaler/scaling/multiscaler.go | 3 +- pkg/autoscaler/scaling/multiscaler_test.go | 6 +- .../statforwarder/forwarder_test.go | 4 +- pkg/autoscaler/statforwarder/leases.go | 4 +- pkg/autoscaler/statserver/server.go | 2 +- pkg/client/certmanager/testing/factory.go | 3 +- pkg/http/handler/timeout.go | 6 +- pkg/http/request_log.go | 3 +- pkg/metrics/tags.go | 8 +- pkg/queue/breaker.go | 6 +- pkg/queue/certificate/watcher_test.go | 4 +- pkg/queue/health/handler.go | 9 +- pkg/queue/health/probe.go | 2 - pkg/queue/readiness/probe_encoding_test.go | 2 - pkg/queue/readiness/probe_test.go | 3 +- pkg/queue/request_metric.go | 6 +- pkg/queue/sharedmain/handlers.go | 4 +- pkg/queue/sharedmain/servers.go | 2 +- .../accessor/networking/certificate.go | 3 +- pkg/reconciler/autoscaling/hpa/hpa_test.go | 1 + pkg/reconciler/autoscaling/kpa/kpa_test.go | 57 +- pkg/reconciler/autoscaling/kpa/scaler.go | 6 +- pkg/reconciler/autoscaling/kpa/scaler_test.go | 1 - pkg/reconciler/autoscaling/reconciler.go | 3 +- .../certificate/certificate_test.go | 12 +- .../resources/cert_manager_certificate.go | 3 +- .../cert_manager_certificate_test.go | 12 +- pkg/reconciler/gc/gc.go | 3 +- pkg/reconciler/gc/gc_test.go | 3 +- pkg/reconciler/gc/reconciler_test.go | 3 +- pkg/reconciler/labeler/accessors.go | 9 +- pkg/reconciler/labeler/labeler.go | 6 +- pkg/reconciler/labeler/labeler_test.go | 6 +- pkg/reconciler/nscert/nscert.go | 2 + pkg/reconciler/nscert/nscert_test.go | 31 +- pkg/reconciler/revision/cruds.go | 1 - pkg/reconciler/revision/resolve.go | 3 +- pkg/reconciler/revision/resolve_test.go | 1 + .../revision/resources/deploy_test.go | 36 +- pkg/reconciler/revision/resources/pa_test.go | 9 +- .../revision/resources/queue_test.go | 8 +- .../resources/resourceboundary_test.go | 13 +- pkg/reconciler/revision/revision_test.go | 23 +- pkg/reconciler/revision/table_test.go | 6 +- pkg/reconciler/route/config/domain.go | 8 +- pkg/reconciler/route/domains/domains.go | 4 +- pkg/reconciler/route/reconcile_resources.go | 4 +- .../route/reconcile_resources_test.go | 3 +- .../route/resources/certificate_test.go | 2 +- pkg/reconciler/route/resources/ingress.go | 6 +- .../route/resources/ingress_test.go | 6 +- pkg/reconciler/route/route_test.go | 6 +- pkg/reconciler/route/table_test.go | 7 +- pkg/reconciler/route/traffic/traffic.go | 9 +- pkg/reconciler/route/traffic/traffic_test.go | 4 +- pkg/reconciler/service/service.go | 3 +- pkg/reconciler/service/service_test.go | 12 +- pkg/reconciler/testing/v1/factory.go | 3 +- pkg/testing/v1/revision.go | 4 +- pkg/testing/v1/service.go | 24 +- pkg/webhook/validate_unstructured_test.go | 16 +- test/conformance/api/v1/configuration_test.go | 2 +- .../conformance/api/v1/errorcondition_test.go | 1 - test/conformance/api/v1/revision_test.go | 2 +- .../api/v1/revision_timeout_test.go | 3 +- test/conformance/api/v1/route_test.go | 2 +- test/conformance/api/v1/service_test.go | 2 +- test/conformance/api/v1/util.go | 3 +- test/conformance/api/v1/volumes_test.go | 2 +- test/conformance/runtime/cgroup_test.go | 10 +- .../runtime/liveness_probe_test.go | 1 - .../runtime/readiness_probe_test.go | 2 +- test/conformance/runtime/user_test.go | 1 - test/conformance/runtime/util.go | 3 +- test/e2e/autoscale.go | 4 +- test/e2e/autoscale_test.go | 4 +- test/e2e/domainmapping/domain_mapping_test.go | 4 +- test/e2e/egress_traffic_test.go | 1 - test/e2e/externaldomaintls/auto_tls_test.go | 8 +- test/e2e/externaldomaintls/util_test.go | 12 +- test/e2e/grpc_test.go | 1 - test/e2e/httpproxy.go | 1 - test/e2e/logging_test.go | 4 +- .../multicontainer_readiness_test.go | 131 +- test/e2e/pod_schedule_error_test.go | 2 - test/e2e/readiness_test.go | 1 - test/e2e/resource_quota_error_test.go | 1 - test/e2e/scale.go | 1 - test/e2e/timeout_test.go | 3 +- test/ha/activator_test.go | 1 - .../benchmarks/dataplane-probe/main.go | 72 +- test/performance/benchmarks/load-test/main.go | 4 +- .../benchmarks/reconciliation-delay/main.go | 3 +- .../benchmarks/rollout-probe/main.go | 38 +- .../benchmarks/scale-from-zero/main.go | 3 +- test/performance/performance/runtime.go | 3 +- test/test_images/httpproxy/httpproxy.go | 3 +- test/test_images/runtime/handlers/cgroup.go | 8 +- test/test_images/runtime/handlers/file.go | 3 +- test/test_images/runtime/handlers/mount.go | 3 +- test/test_images/runtime/handlers/runtime.go | 3 +- test/test_images/volumes/emptydir.go | 2 +- test/upgrade/deployment_failure.go | 2 - 132 files changed, 2150 insertions(+), 2053 deletions(-) diff --git a/cmd/activator/main.go b/cmd/activator/main.go index a57d1aa026c6..aaab0ba421d6 100644 --- a/cmd/activator/main.go +++ b/cmd/activator/main.go @@ -214,11 +214,11 @@ func main() { ah := activatorhandler.New(ctx, throttler, transport, networkConfig.EnableMeshPodAddressability, logger, tlsEnabled) ah = handler.NewTimeoutHandler(ah, "activator request timeout", func(r *http.Request) (time.Duration, time.Duration, time.Duration) { if rev := activatorhandler.RevisionFrom(r.Context()); rev != nil { - var responseStartTimeout = 0 * time.Second + responseStartTimeout := 0 * time.Second if rev.Spec.ResponseStartTimeoutSeconds != nil { responseStartTimeout = time.Duration(*rev.Spec.ResponseStartTimeoutSeconds) * time.Second } - var idleTimeout = 0 * time.Second + idleTimeout := 0 * time.Second if rev.Spec.IdleTimeoutSeconds != nil { idleTimeout = time.Duration(*rev.Spec.IdleTimeoutSeconds) * time.Second } diff --git a/cmd/autoscaler/leaderelection.go b/cmd/autoscaler/leaderelection.go index 5035f8d30ac8..cbf366e31c58 100644 --- a/cmd/autoscaler/leaderelection.go +++ b/cmd/autoscaler/leaderelection.go @@ -66,7 +66,6 @@ func setupSharedElector(ctx context.Context, controllers []*controller.Impl) (le noopEnqueue := func(reconciler.Bucket, types.NamespacedName) {} el, err := leaderelection.BuildElector(ctx, coalesce(reconcilers), queueName, noopEnqueue) - if err != nil { return nil, err } diff --git a/cmd/autoscaler/main.go b/cmd/autoscaler/main.go index 38335d227026..2736bf2a0bcc 100644 --- a/cmd/autoscaler/main.go +++ b/cmd/autoscaler/main.go @@ -231,7 +231,8 @@ func main() { } func uniScalerFactoryFunc(podLister corev1listers.PodLister, - metricClient asmetrics.MetricClient) scaling.UniScalerFactory { + metricClient asmetrics.MetricClient, +) scaling.UniScalerFactory { return func(decider *scaling.Decider) (scaling.UniScaler, error) { configName := decider.Labels[serving.ConfigurationLabelKey] if configName == "" { diff --git a/pkg/activator/activator.go b/pkg/activator/activator.go index eb8d73d18c2f..f34f3794bb5c 100644 --- a/pkg/activator/activator.go +++ b/pkg/activator/activator.go @@ -25,11 +25,9 @@ const ( RevisionHeaderNamespace = "Knative-Serving-Namespace" ) -var ( - // RevisionHeaders are the headers the activator uses to identify the - // revision. They are removed before reaching the user container. - RevisionHeaders = []string{ - RevisionHeaderName, - RevisionHeaderNamespace, - } -) +// RevisionHeaders are the headers the activator uses to identify the +// revision. They are removed before reaching the user container. +var RevisionHeaders = []string{ + RevisionHeaderName, + RevisionHeaderNamespace, +} diff --git a/pkg/activator/certificate/cache_test.go b/pkg/activator/certificate/cache_test.go index 7ab6c006bf90..99ffc95f6232 100644 --- a/pkg/activator/certificate/cache_test.go +++ b/pkg/activator/certificate/cache_test.go @@ -53,30 +53,26 @@ func TestReconcile(t *testing.T) { secret: secret, configMap: nil, expectedPool: getPoolWithCerts(secret.Data[certificates.CaCertName]), - }, - { - name: "Valid CA only in configmap", - secret: func() *corev1.Secret { - s := secret.DeepCopy() - delete(s.Data, certificates.CaCertName) - return s - }(), - configMap: validConfigmap, - expectedPool: getPoolWithCerts(configmapCA), - }, - { - name: "Valid CA in both configmap and secret", - secret: secret, - configMap: validConfigmap, - expectedPool: getPoolWithCerts(secretCA, configmapCA), - }, - { - name: "Invalid CA in configmap", - secret: secret, - configMap: invalidConfigmap, - expectedPool: getPoolWithCerts(secretCA), - }, - } + }, { + name: "Valid CA only in configmap", + secret: func() *corev1.Secret { + s := secret.DeepCopy() + delete(s.Data, certificates.CaCertName) + return s + }(), + configMap: validConfigmap, + expectedPool: getPoolWithCerts(configmapCA), + }, { + name: "Valid CA in both configmap and secret", + secret: secret, + configMap: validConfigmap, + expectedPool: getPoolWithCerts(secretCA, configmapCA), + }, { + name: "Invalid CA in configmap", + secret: secret, + configMap: invalidConfigmap, + expectedPool: getPoolWithCerts(secretCA), + }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/pkg/activator/handler/handler.go b/pkg/activator/handler/handler.go index 74acbb7ed327..747f4263f3af 100644 --- a/pkg/activator/handler/handler.go +++ b/pkg/activator/handler/handler.go @@ -114,7 +114,8 @@ func (a *activationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func (a *activationHandler) proxyRequest(revID types.NamespacedName, w http.ResponseWriter, - r *http.Request, target string, tracingEnabled bool, usePassthroughLb bool) { + r *http.Request, target string, tracingEnabled bool, usePassthroughLb bool, +) { netheader.RewriteHostIn(r) r.Header.Set(netheader.ProxyKey, activator.Name) diff --git a/pkg/activator/handler/main_test.go b/pkg/activator/handler/main_test.go index 133e92ab5be7..d6f65c87161a 100644 --- a/pkg/activator/handler/main_test.go +++ b/pkg/activator/handler/main_test.go @@ -260,7 +260,6 @@ func send(client *http.Client, url string, body []byte, rHost string) error { bd := io.Reader(resp.Body) rec, err := io.ReadAll(bd) - if err != nil { return fmt.Errorf("failed to read body: %w", err) } diff --git a/pkg/activator/net/revision_backends.go b/pkg/activator/net/revision_backends.go index 2a773c0e7ff1..8940054393cf 100644 --- a/pkg/activator/net/revision_backends.go +++ b/pkg/activator/net/revision_backends.go @@ -137,7 +137,8 @@ func newRevisionWatcher(ctx context.Context, rev types.NamespacedName, protocol transport http.RoundTripper, serviceLister corev1listers.ServiceLister, usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, enableProbeOptimisation bool, - logger *zap.SugaredLogger) *revisionWatcher { + logger *zap.SugaredLogger, +) *revisionWatcher { ctx, cancel := context.WithCancel(ctx) return &revisionWatcher{ stopCh: ctx.Done(), @@ -469,7 +470,8 @@ func newRevisionBackendsManager(ctx context.Context, tr http.RoundTripper, usePa // newRevisionBackendsManagerWithProbeFrequency creates a fully spec'd RevisionBackendsManager. func newRevisionBackendsManagerWithProbeFrequency(ctx context.Context, tr http.RoundTripper, - usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, probeFreq time.Duration) *revisionBackendsManager { + usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, probeFreq time.Duration, +) *revisionBackendsManager { rbm := &revisionBackendsManager{ ctx: ctx, revisionLister: revisioninformer.Get(ctx).Lister(), diff --git a/pkg/activator/net/throttler.go b/pkg/activator/net/throttler.go index 54d466afbc5e..e8db757d79a8 100644 --- a/pkg/activator/net/throttler.go +++ b/pkg/activator/net/throttler.go @@ -171,7 +171,8 @@ type revisionThrottler struct { func newRevisionThrottler(revID types.NamespacedName, containerConcurrency int, proto string, breakerParams queue.BreakerParams, - logger *zap.SugaredLogger) *revisionThrottler { + logger *zap.SugaredLogger, +) *revisionThrottler { logger = logger.With(zap.String(logkey.Key, revID.String())) var ( revBreaker breaker diff --git a/pkg/activator/net/throttler_test.go b/pkg/activator/net/throttler_test.go index 22f4c1eb8a8b..71d510de0d09 100644 --- a/pkg/activator/net/throttler_test.go +++ b/pkg/activator/net/throttler_test.go @@ -855,7 +855,8 @@ func TestMultipleActivators(t *testing.T) { }, Subsets: []corev1.EndpointSubset{ *epSubset(8012, "http", []string{"130.0.0.1", "130.0.0.2"}, - nil)}, + nil), + }, } fake.CoreV1().Endpoints(testNamespace).Create(ctx, publicEp, metav1.CreateOptions{}) endpoints.Informer().GetIndexer().Add(publicEp) diff --git a/pkg/apis/autoscaling/v1alpha1/podscalable_types.go b/pkg/apis/autoscaling/v1alpha1/podscalable_types.go index b6d05a7b73b6..b667c7b593db 100644 --- a/pkg/apis/autoscaling/v1alpha1/podscalable_types.go +++ b/pkg/apis/autoscaling/v1alpha1/podscalable_types.go @@ -54,9 +54,11 @@ type PodScalableStatus struct { Replicas int32 `json:"replicas,omitempty"` } -var _ duck.Populatable = (*PodScalable)(nil) -var _ duck.Implementable = (*PodScalable)(nil) -var _ apis.Listable = (*PodScalable)(nil) +var ( + _ duck.Populatable = (*PodScalable)(nil) + _ duck.Implementable = (*PodScalable)(nil) + _ apis.Listable = (*PodScalable)(nil) +) // GetFullType implements duck.Implementable func (*PodScalable) GetFullType() duck.Populatable { diff --git a/pkg/apis/config/features_test.go b/pkg/apis/config/features_test.go index b3d1213871c9..6a1762d892cf 100644 --- a/pkg/apis/config/features_test.go +++ b/pkg/apis/config/features_test.go @@ -356,323 +356,322 @@ func TestFeaturesConfiguration(t *testing.T) { data: map[string]string{ "kubernetes.podspec-securitycontext": "Disabled", }, - }, - { - name: "shared process namespace Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecShareProcessNamespace: Allowed, - }), - data: map[string]string{ - "kubernetes.podspec-shareprocessnamespace": "Allowed", - }, - }, { - name: "shared process namespace Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecShareProcessNamespace: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-shareprocessnamespace": "Disabled", - }, - }, { - name: "kubernetes.containerspec-addcapabilities Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - ContainerSpecAddCapabilities: Disabled, - }), - data: map[string]string{ - "kubernetes.containerspec-addcapabilities": "Disabled", - }, - }, { - name: "kubernetes.containerspec-addcapabilities Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - ContainerSpecAddCapabilities: Enabled, - }), - data: map[string]string{ - "kubernetes.containerspec-addcapabilities": "Enabled", - }, - }, { - name: "kubernetes.containerspec-addcapabilities Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - ContainerSpecAddCapabilities: Allowed, - }), - data: map[string]string{ - "kubernetes.containerspec-addcapabilities": "Allowed", - }, - }, { - name: "tag-header-based-routing Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - TagHeaderBasedRouting: Allowed, - }), - data: map[string]string{ - "tag-header-based-routing": "Allowed", - }, - }, { - name: "tag-header-based-routing Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - TagHeaderBasedRouting: Enabled, - }), - data: map[string]string{ - "tag-header-based-routing": "Enabled", - }, - }, { - name: "kubernetes.podspec-volumes-emptyDir Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecVolumesEmptyDir: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-volumes-emptydir": "Disabled", - }, - }, { - name: "kubernetes.podspec-volumes-emptyDir Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecVolumesEmptyDir: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-volumes-emptydir": "Enabled", - }, - }, { - name: "kubernetes.podspec-volumes-hostpath Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecVolumesHostPath: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-volumes-hostpath": "Disabled", - }, - }, { - name: "kubernetes.podspec-volumes-hostpath Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecVolumesHostPath: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-volumes-hostpath": "Enabled", - }, - }, { - name: "kubernetes.podspec-persistent-volume-claim Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPersistentVolumeClaim: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-persistent-volume-claim": "Disabled", - }, - }, { - name: "kubernetes.podspec-persistent-volume-claim Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPersistentVolumeClaim: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-persistent-volume-claim": "Enabled", - }, - }, { - name: "kubernetes.podspec-persistent-volume-write Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPersistentVolumeWrite: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-persistent-volume-write": "Disabled", - }, - }, { - name: "kubernetes.podspec-persistent-volume-claim Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPersistentVolumeWrite: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-persistent-volume-write": "Enabled", - }, - }, { - name: "kubernetes.podspec-init-containers Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecInitContainers: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-init-containers": "Disabled", - }, - }, { - name: "kubernetes.podspec-init-container Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecInitContainers: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-init-containers": "Enabled", - }, - }, { - name: "kubernetes.podspec-priorityclassname Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPriorityClassName: Allowed, - }), - data: map[string]string{ - "kubernetes.podspec-priorityclassname": "Allowed", - }, - }, { - name: "kubernetes.podspec-priorityclassname Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPriorityClassName: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-priorityclassname": "Enabled", - }, - }, { - name: "kubernetes.podspec-priorityclassname Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecPriorityClassName: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-priorityclassname": "Disabled", - }, - }, { - name: "kubernetes.podspec-schedulername Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecSchedulerName: Allowed, - }), - data: map[string]string{ - "kubernetes.podspec-schedulername": "Allowed", - }, - }, { - name: "kubernetes.podspec-schedulername Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecSchedulerName: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-schedulername": "Enabled", - }, - }, { - name: "kubernetes.podspec-schedulername Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecSchedulerName: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-schedulername": "Disabled", - }, - }, { - name: "kubernetes.podspec-dnspolicy Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSPolicy: Allowed, - }), - data: map[string]string{ - "kubernetes.podspec-dnspolicy": "Allowed", - }, - }, { - name: "kubernetes.podspec-dnspolicy Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSPolicy: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-dnspolicy": "Enabled", - }, - }, { - name: "kubernetes.podspec-dnspolicy Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSPolicy: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-dnspolicy": "Disabled", - }, - }, { - name: "kubernetes.podspec-dnsconfig Allowed", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSConfig: Allowed, - }), - data: map[string]string{ - "kubernetes.podspec-dnsconfig": "Allowed", - }, - }, { - name: "kubernetes.podspec-dnsconfig Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSConfig: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-dnsconfig": "Enabled", - }, - }, { - name: "kubernetes.podspec-dnsconfig Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecDNSConfig: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-dnsconfig": "Disabled", - }, - }, { - name: "kubernetes.podspec-hostipc Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostIPC: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostipc": "Enabled", - }, - }, { - name: "kubernetes.podspec-hostipc Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostIPC: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostipc": "Disabled", - }, - }, { - name: "kubernetes.podspec-hostpid Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostPID: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostpid": "Enabled", - }, - }, { - name: "kubernetes.podspec-hostpid Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostPID: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostpid": "Disabled", - }, - }, { - name: "kubernetes.podspec-hostnetwork Enabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostNetwork: Enabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostnetwork": "Enabled", - }, - }, { - name: "kubernetes.podspec-hostnetwork Disabled", - wantErr: false, - wantFeatures: defaultWith(&Features{ - PodSpecHostNetwork: Disabled, - }), - data: map[string]string{ - "kubernetes.podspec-hostnetwork": "Disabled", - }, - }} + }, { + name: "shared process namespace Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecShareProcessNamespace: Allowed, + }), + data: map[string]string{ + "kubernetes.podspec-shareprocessnamespace": "Allowed", + }, + }, { + name: "shared process namespace Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecShareProcessNamespace: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-shareprocessnamespace": "Disabled", + }, + }, { + name: "kubernetes.containerspec-addcapabilities Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + ContainerSpecAddCapabilities: Disabled, + }), + data: map[string]string{ + "kubernetes.containerspec-addcapabilities": "Disabled", + }, + }, { + name: "kubernetes.containerspec-addcapabilities Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + ContainerSpecAddCapabilities: Enabled, + }), + data: map[string]string{ + "kubernetes.containerspec-addcapabilities": "Enabled", + }, + }, { + name: "kubernetes.containerspec-addcapabilities Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + ContainerSpecAddCapabilities: Allowed, + }), + data: map[string]string{ + "kubernetes.containerspec-addcapabilities": "Allowed", + }, + }, { + name: "tag-header-based-routing Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + TagHeaderBasedRouting: Allowed, + }), + data: map[string]string{ + "tag-header-based-routing": "Allowed", + }, + }, { + name: "tag-header-based-routing Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + TagHeaderBasedRouting: Enabled, + }), + data: map[string]string{ + "tag-header-based-routing": "Enabled", + }, + }, { + name: "kubernetes.podspec-volumes-emptyDir Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecVolumesEmptyDir: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-volumes-emptydir": "Disabled", + }, + }, { + name: "kubernetes.podspec-volumes-emptyDir Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecVolumesEmptyDir: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-volumes-emptydir": "Enabled", + }, + }, { + name: "kubernetes.podspec-volumes-hostpath Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecVolumesHostPath: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-volumes-hostpath": "Disabled", + }, + }, { + name: "kubernetes.podspec-volumes-hostpath Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecVolumesHostPath: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-volumes-hostpath": "Enabled", + }, + }, { + name: "kubernetes.podspec-persistent-volume-claim Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPersistentVolumeClaim: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-persistent-volume-claim": "Disabled", + }, + }, { + name: "kubernetes.podspec-persistent-volume-claim Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPersistentVolumeClaim: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-persistent-volume-claim": "Enabled", + }, + }, { + name: "kubernetes.podspec-persistent-volume-write Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPersistentVolumeWrite: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-persistent-volume-write": "Disabled", + }, + }, { + name: "kubernetes.podspec-persistent-volume-claim Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPersistentVolumeWrite: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-persistent-volume-write": "Enabled", + }, + }, { + name: "kubernetes.podspec-init-containers Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecInitContainers: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-init-containers": "Disabled", + }, + }, { + name: "kubernetes.podspec-init-container Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecInitContainers: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-init-containers": "Enabled", + }, + }, { + name: "kubernetes.podspec-priorityclassname Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPriorityClassName: Allowed, + }), + data: map[string]string{ + "kubernetes.podspec-priorityclassname": "Allowed", + }, + }, { + name: "kubernetes.podspec-priorityclassname Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPriorityClassName: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-priorityclassname": "Enabled", + }, + }, { + name: "kubernetes.podspec-priorityclassname Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecPriorityClassName: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-priorityclassname": "Disabled", + }, + }, { + name: "kubernetes.podspec-schedulername Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecSchedulerName: Allowed, + }), + data: map[string]string{ + "kubernetes.podspec-schedulername": "Allowed", + }, + }, { + name: "kubernetes.podspec-schedulername Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecSchedulerName: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-schedulername": "Enabled", + }, + }, { + name: "kubernetes.podspec-schedulername Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecSchedulerName: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-schedulername": "Disabled", + }, + }, { + name: "kubernetes.podspec-dnspolicy Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSPolicy: Allowed, + }), + data: map[string]string{ + "kubernetes.podspec-dnspolicy": "Allowed", + }, + }, { + name: "kubernetes.podspec-dnspolicy Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSPolicy: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-dnspolicy": "Enabled", + }, + }, { + name: "kubernetes.podspec-dnspolicy Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSPolicy: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-dnspolicy": "Disabled", + }, + }, { + name: "kubernetes.podspec-dnsconfig Allowed", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSConfig: Allowed, + }), + data: map[string]string{ + "kubernetes.podspec-dnsconfig": "Allowed", + }, + }, { + name: "kubernetes.podspec-dnsconfig Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSConfig: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-dnsconfig": "Enabled", + }, + }, { + name: "kubernetes.podspec-dnsconfig Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecDNSConfig: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-dnsconfig": "Disabled", + }, + }, { + name: "kubernetes.podspec-hostipc Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostIPC: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostipc": "Enabled", + }, + }, { + name: "kubernetes.podspec-hostipc Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostIPC: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostipc": "Disabled", + }, + }, { + name: "kubernetes.podspec-hostpid Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostPID: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostpid": "Enabled", + }, + }, { + name: "kubernetes.podspec-hostpid Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostPID: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostpid": "Disabled", + }, + }, { + name: "kubernetes.podspec-hostnetwork Enabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostNetwork: Enabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostnetwork": "Enabled", + }, + }, { + name: "kubernetes.podspec-hostnetwork Disabled", + wantErr: false, + wantFeatures: defaultWith(&Features{ + PodSpecHostNetwork: Disabled, + }), + data: map[string]string{ + "kubernetes.podspec-hostnetwork": "Disabled", + }, + }} for _, tt := range configTests { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/apis/serving/k8s_validation_test.go b/pkg/apis/serving/k8s_validation_test.go index 0cc355940a2d..e38fae560997 100644 --- a/pkg/apis/serving/k8s_validation_test.go +++ b/pkg/apis/serving/k8s_validation_test.go @@ -375,14 +375,12 @@ func TestPodSpecValidation(t *testing.T) { MountPath: "/dbg", }}, }}, - Volumes: []corev1.Volume{ - { - Name: "debugging-support-files", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, + Volumes: []corev1.Volume{{ + Name: "debugging-support-files", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, }, - }, + }}, }, cfgOpts: []configOption{withPodSpecVolumesEmptyDirEnabled(), withPodSpecInitContainersEnabled()}, want: nil, @@ -400,14 +398,12 @@ func TestPodSpecValidation(t *testing.T) { Containers: []corev1.Container{{ Image: "busybox", }}, - Volumes: []corev1.Volume{ - { - Name: "debugging-support-files", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, + Volumes: []corev1.Volume{{ + Name: "debugging-support-files", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, }, - }, + }}, }, cfgOpts: []configOption{withPodSpecVolumesEmptyDirEnabled(), withPodSpecInitContainersEnabled()}, want: nil, @@ -429,19 +425,18 @@ func TestPodSpecValidation(t *testing.T) { MountPath: "/data", }}, }}, - Volumes: []corev1.Volume{ - { - Name: "debugging-support-files", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }, { - Name: "data", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, + Volumes: []corev1.Volume{{ + Name: "debugging-support-files", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, + }, + }, { + Name: "data", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }}, + }, cfgOpts: []configOption{withPodSpecVolumesEmptyDirEnabled(), withPodSpecInitContainersEnabled()}, want: nil, }, { @@ -458,19 +453,18 @@ func TestPodSpecValidation(t *testing.T) { MountPath: "/data", }}, }}, - Volumes: []corev1.Volume{ - { - Name: "debugging-support-files", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }, { - Name: "data", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, + Volumes: []corev1.Volume{{ + Name: "debugging-support-files", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, + }, + }, { + Name: "data", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }}, + }, cfgOpts: []configOption{withPodSpecVolumesEmptyDirEnabled(), withPodSpecInitContainersEnabled()}, want: &apis.FieldError{ Message: `volume with name "debugging-support-files" not mounted`, @@ -529,8 +523,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: false, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled()}, want: &apis.FieldError{ Message: `Persistent volume write support is disabled, but found persistent volume claim myclaim that is not read-only`, @@ -553,8 +548,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: false, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled()}, want: &apis.FieldError{ Message: `Persistent volume write support is disabled, but found persistent volume claim myclaim that is not read-only`, @@ -577,8 +573,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: true, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled()}, want: &apis.FieldError{ Message: "volume is readOnly but volume mount is not", @@ -602,8 +599,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: true, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled()}, }, { name: "PVC not read-only, write enabled", @@ -623,8 +621,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: false, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled(), withPodSpecPersistentVolumeWriteEnabled()}, }, { name: "PVC read-only, write enabled", @@ -644,8 +643,9 @@ func TestPodSpecValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: false, }, - }}, + }, }}, + }, cfgOpts: []configOption{withPodSpecPersistentVolumeClaimEnabled(), withPodSpecPersistentVolumeWriteEnabled()}, }, { name: "insecure security context default struct", @@ -980,14 +980,14 @@ func TestPodSpecMultiContainerValidation(t *testing.T) { }, { name: "Volume mounts ok with single container", ps: corev1.PodSpec{ - Volumes: []corev1.Volume{ - {Name: "the-name", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo", - }, - }}, - }, + Volumes: []corev1.Volume{{ + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo", + }, + }, + }}, Containers: []corev1.Container{{ Image: "busybox", VolumeMounts: []corev1.VolumeMount{{ @@ -1001,14 +1001,14 @@ func TestPodSpecMultiContainerValidation(t *testing.T) { }, { name: "Volume not mounted when having a single container", ps: corev1.PodSpec{ - Volumes: []corev1.Volume{ - {Name: "the-name", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo", - }, - }}, - }, + Volumes: []corev1.Volume{{ + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo", + }, + }, + }}, Containers: []corev1.Container{{ Image: "busybox", }}, @@ -1016,80 +1016,76 @@ func TestPodSpecMultiContainerValidation(t *testing.T) { cfgOpts: []configOption{withPodSpecFieldRefEnabled()}, want: &apis.FieldError{ Message: `volume with name "the-name" not mounted`, - Paths: []string{"volumes[0].name"}}, + Paths: []string{"volumes[0].name"}, + }, }, { name: "Volume mounts ok when having multiple containers", ps: corev1.PodSpec{ - Volumes: []corev1.Volume{ - {Name: "the-name1", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo1", - }, + Volumes: []corev1.Volume{{ + Name: "the-name1", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo1", }, }, - {Name: "the-name2", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo2", - }, - }}, - }, - Containers: []corev1.Container{ - { - Name: "container-a", - Image: "busybox", - Ports: []corev1.ContainerPort{{ContainerPort: 8888}}, - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name1", - ReadOnly: true, - }}, - }, - { - Name: "container-b", - Image: "busybox", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name2", - ReadOnly: true, - }}, + }, { + Name: "the-name2", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo2", + }, }, - }, + }}, + Containers: []corev1.Container{{ + Name: "container-a", + Image: "busybox", + Ports: []corev1.ContainerPort{{ContainerPort: 8888}}, + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name1", + ReadOnly: true, + }}, + }, { + Name: "container-b", + Image: "busybox", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name2", + ReadOnly: true, + }}, + }}, }, }, { name: "Volume not mounted when having multiple containers", ps: corev1.PodSpec{ - Volumes: []corev1.Volume{ - {Name: "the-name1", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo1", - }, + Volumes: []corev1.Volume{{ + Name: "the-name1", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo1", }, }, - {Name: "the-name2", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "foo2", - }, - }}, - }, - Containers: []corev1.Container{ - { - Name: "container-a", - Image: "busybox", - Ports: []corev1.ContainerPort{{ContainerPort: 8888}}, - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name1", - ReadOnly: true, - }}, + }, { + Name: "the-name2", + VolumeSource: corev1.VolumeSource{ + Secret: &corev1.SecretVolumeSource{ + SecretName: "foo2", + }, }, - { - Name: "container-b", - Image: "busybox"}, - }, + }}, + Containers: []corev1.Container{{ + Name: "container-a", + Image: "busybox", + Ports: []corev1.ContainerPort{{ContainerPort: 8888}}, + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name1", + ReadOnly: true, + }}, + }, { + Name: "container-b", + Image: "busybox", + }}, }, want: &apis.FieldError{ Message: `volume with name "the-name2" not mounted`, @@ -1118,19 +1114,18 @@ func TestPodSpecMultiContainerValidation(t *testing.T) { MountPath: "/dbg", }}, }}, - Volumes: []corev1.Volume{ - { - Name: "debugging-support-files", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, - }, { - Name: "data", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{}, - }, + Volumes: []corev1.Volume{{ + Name: "debugging-support-files", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, + }, + }, { + Name: "data", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }}, + }, cfgOpts: []configOption{withPodSpecVolumesEmptyDirEnabled(), withPodSpecInitContainersEnabled()}, want: nil, }} @@ -1500,478 +1495,476 @@ func TestPodSpecFieldRefValidation(t *testing.T) { } func TestUserContainerValidation(t *testing.T) { - tests := []containerValidationTestCase{ - { - name: "has a lifecycle", - c: corev1.Container{ - Name: "foo", - Image: "foo", - Lifecycle: &corev1.Lifecycle{}, - }, - want: apis.ErrDisallowedFields("lifecycle"), - cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, - }, { - name: "has lifecycle", - c: corev1.Container{ - Image: "foo", - Lifecycle: &corev1.Lifecycle{}, - }, - want: apis.ErrDisallowedFields("lifecycle"), + tests := []containerValidationTestCase{{ + name: "has a lifecycle", + c: corev1.Container{ + Name: "foo", + Image: "foo", + Lifecycle: &corev1.Lifecycle{}, + }, + want: apis.ErrDisallowedFields("lifecycle"), + cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, + }, { + name: "has lifecycle", + c: corev1.Container{ + Image: "foo", + Lifecycle: &corev1.Lifecycle{}, }, - { - name: "has valid unnamed user port", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8181, - }}, - }, - want: nil, - }, { - name: "has valid user port http1", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Name: "http1", - }}, - }, - want: nil, - }, { - name: "has valid user port h2c", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Name: "h2c", - }}, - }, - want: nil, - }, { - name: "has more than one ports with valid names", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Name: "h2c", - }, { - Name: "http1", - }}, - }, - want: &apis.FieldError{ - Message: "more than one container port is set", - Paths: []string{"ports"}, - Details: "Only a single port is allowed across all containers", - }, - }, { - name: "has an empty port set", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{}}, - }, - want: nil, - }, { - name: "has more than one unnamed port", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8080, - }, { - ContainerPort: 8181, - }}, - }, - want: &apis.FieldError{ - Message: "more than one container port is set", - Paths: []string{"ports"}, - Details: "Only a single port is allowed across all containers", + want: apis.ErrDisallowedFields("lifecycle"), + }, { + name: "has valid unnamed user port", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8181, + }}, + }, + want: nil, + }, { + name: "has valid user port http1", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Name: "http1", + }}, + }, + want: nil, + }, { + name: "has valid user port h2c", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Name: "h2c", + }}, + }, + want: nil, + }, { + name: "has more than one ports with valid names", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Name: "h2c", + }, { + Name: "http1", + }}, + }, + want: &apis.FieldError{ + Message: "more than one container port is set", + Paths: []string{"ports"}, + Details: "Only a single port is allowed across all containers", + }, + }, { + name: "has an empty port set", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{}}, + }, + want: nil, + }, { + name: "has more than one unnamed port", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8080, + }, { + ContainerPort: 8181, + }}, + }, + want: &apis.FieldError{ + Message: "more than one container port is set", + Paths: []string{"ports"}, + Details: "Only a single port is allowed across all containers", + }, + }, { + name: "has tcp protocol", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Protocol: corev1.ProtocolTCP, + }}, + }, + want: nil, + }, { + name: "has invalid protocol", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Protocol: "tdp", + }}, + }, + want: apis.ErrInvalidValue("tdp", "ports.protocol"), + }, { + name: "has host port", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + HostPort: 80, + }}, + }, + want: apis.ErrDisallowedFields("ports.hostPort"), + }, { + name: "has invalid port name", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + Name: "foobar", + }}, + }, + want: &apis.FieldError{ + Message: fmt.Sprintf("Port name %v is not allowed", "foobar"), + Paths: []string{"ports"}, + Details: "Name must be empty, or one of: 'h2c', 'http1'", + }, + }, { + name: "valid with probes (no port)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + }, + }, }, - }, { - name: "has tcp protocol", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Protocol: corev1.ProtocolTCP, - }}, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{}, + }, }, - want: nil, - }, { - name: "has invalid protocol", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Protocol: "tdp", - }}, + }, + want: nil, + }, { + name: "valid with exec probes ", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + InitialDelaySeconds: 0, + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + }, + }, }, - want: apis.ErrInvalidValue("tdp", "ports.protocol"), - }, { - name: "has host port", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - HostPort: 80, - }}, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + Exec: &corev1.ExecAction{}, + }, }, - want: apis.ErrDisallowedFields("ports.hostPort"), - }, { - name: "has invalid port name", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - Name: "foobar", - }}, + }, + want: nil, + }, { + name: "invalid with no handler", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + }, + }, }, - want: &apis.FieldError{ - Message: fmt.Sprintf("Port name %v is not allowed", "foobar"), - Paths: []string{"ports"}, - Details: "Name must be empty, or one of: 'h2c', 'http1'", + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{}, }, - }, { - name: "valid with probes (no port)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, + }, + want: apis.ErrMissingOneOf("livenessProbe.httpGet", "livenessProbe.tcpSocket", "livenessProbe.exec", "livenessProbe.grpc"), + }, { + name: "valid with startup probe", + c: corev1.Container{ + Image: "foo", + StartupProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{}, + }, + }, + want: nil, + }, { + name: "invalid with multiple handlers", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, + Exec: &corev1.ExecAction{}, + TCPSocket: &corev1.TCPSocketAction{}, }, }, - want: nil, - }, { - name: "valid with exec probes ", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - InitialDelaySeconds: 0, - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, - }, - }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - Exec: &corev1.ExecAction{}, - }, - }, - }, - want: nil, - }, { - name: "invalid with no handler", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, - }, - }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{}, - }, - }, - want: apis.ErrMissingOneOf("livenessProbe.httpGet", "livenessProbe.tcpSocket", "livenessProbe.exec", "livenessProbe.grpc"), - }, { - name: "valid with startup probe", - c: corev1.Container{ - Image: "foo", - StartupProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, - }, - }, - }, - want: nil, - }, { - name: "invalid with multiple handlers", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, - Exec: &corev1.ExecAction{}, - TCPSocket: &corev1.TCPSocketAction{}, + }, + want: apis.ErrMultipleOneOf("readinessProbe.exec", "readinessProbe.tcpSocket", "readinessProbe.httpGet"), + }, { + name: "valid liveness http probe with a different container port", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - want: apis.ErrMultipleOneOf("readinessProbe.exec", "readinessProbe.tcpSocket", "readinessProbe.httpGet"), - }, { - name: "valid liveness http probe with a different container port", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + want: nil, + }, { + name: "valid liveness tcp probe with a different container port", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt(5000), }, }, }, - want: nil, - }, { - name: "valid liveness tcp probe with a different container port", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt(5000), - }, + }, + want: nil, + }, { + name: "valid readiness http probe with a different container port", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - want: nil, - }, { - name: "valid readiness http probe with a different container port", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + want: nil, + }, { + name: "valid readiness tcp probe with a different container port", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt(5000), }, }, }, - want: nil, - }, { - name: "valid readiness tcp probe with a different container port", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt(5000), - }, + }, + want: nil, + }, { + name: "valid readiness http probe with port", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Port: intstr.FromString("http"), // http is the default }, }, }, - want: nil, - }, { - name: "valid readiness http probe with port", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Port: intstr.FromString("http"), // http is the default - }, + }, + want: nil, + }, { + name: "invalid readiness probe (has failureThreshold while using special probe)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 0, + FailureThreshold: 2, + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, }, }, - want: nil, - }, { - name: "invalid readiness probe (has failureThreshold while using special probe)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 0, - FailureThreshold: 2, - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, + }, + want: &apis.FieldError{ + Message: "failureThreshold is disallowed when periodSeconds is zero", + Paths: []string{"readinessProbe.failureThreshold"}, + }, + }, { + name: "invalid readiness probe (has timeoutSeconds while using special probe)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 0, + TimeoutSeconds: 2, + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, }, }, - want: &apis.FieldError{ - Message: "failureThreshold is disallowed when periodSeconds is zero", - Paths: []string{"readinessProbe.failureThreshold"}, - }, - }, { - name: "invalid readiness probe (has timeoutSeconds while using special probe)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 0, - TimeoutSeconds: 2, - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, - }, + }, + want: &apis.FieldError{ + Message: "timeoutSeconds is disallowed when periodSeconds is zero", + Paths: []string{"readinessProbe.timeoutSeconds"}, + }, + }, { + name: "out of bounds probe values", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: -1, + TimeoutSeconds: 0, + SuccessThreshold: 0, + FailureThreshold: 0, + InitialDelaySeconds: -1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{}, }, }, - want: &apis.FieldError{ - Message: "timeoutSeconds is disallowed when periodSeconds is zero", - Paths: []string{"readinessProbe.timeoutSeconds"}, - }, - }, { - name: "out of bounds probe values", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: -1, - TimeoutSeconds: 0, - SuccessThreshold: 0, - FailureThreshold: 0, - InitialDelaySeconds: -1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{}, + }, + want: apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.periodSeconds").Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.timeoutSeconds")).Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.successThreshold")).Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.failureThreshold")).Also( + apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.initialDelaySeconds")), + }, { + name: "reserved env var name for serving container", + c: corev1.Container{ + Image: "foo", + Env: []corev1.EnvVar{{ + Name: "PORT", + Value: "Foo", + }}, + Ports: []corev1.ContainerPort{{ + ContainerPort: 8888, + }}, + }, + want: &apis.FieldError{ + Message: `"PORT" is a reserved environment variable`, + Paths: []string{"env[0].name"}, + }, + }, { + name: "invalid liveness tcp probe (has port)", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromString("imap"), }, }, }, - want: apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.periodSeconds").Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.timeoutSeconds")).Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.successThreshold")).Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.failureThreshold")).Also( - apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.initialDelaySeconds")), - }, { - name: "reserved env var name for serving container", - c: corev1.Container{ - Image: "foo", - Env: []corev1.EnvVar{{ - Name: "PORT", - Value: "Foo", - }}, - Ports: []corev1.ContainerPort{{ + }, + want: apis.ErrInvalidValue("imap", "livenessProbe.tcpSocket.port", "Probe port must match container port"), + }, { + name: "valid liveness tcp probe with correct port", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{ + { ContainerPort: 8888, - }}, - }, - want: &apis.FieldError{ - Message: `"PORT" is a reserved environment variable`, - Paths: []string{"env[0].name"}, - }, - }, { - name: "invalid liveness tcp probe (has port)", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromString("imap"), - }, - }, }, }, - want: apis.ErrInvalidValue("imap", "livenessProbe.tcpSocket.port", "Probe port must match container port"), - }, { - name: "valid liveness tcp probe with correct port", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{ - { - ContainerPort: 8888, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt(8888), }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt(8888), - }, - }, - }, - }, - }, { - name: "disallowed container fields", - c: corev1.Container{ - Image: "foo", - Name: "fail", - Stdin: true, - StdinOnce: true, - TTY: true, - Lifecycle: &corev1.Lifecycle{}, - VolumeDevices: []corev1.VolumeDevice{{ - Name: "disallowed", - DevicePath: "/", - }}, - }, - want: apis.ErrDisallowedFields("lifecycle").Also( - apis.ErrDisallowedFields("stdin")).Also( - apis.ErrDisallowedFields("stdinOnce")).Also( - apis.ErrDisallowedFields("tty")).Also( - apis.ErrDisallowedFields("volumeDevices")), - }, { - name: "has numerous problems", - c: corev1.Container{ - Lifecycle: &corev1.Lifecycle{}, }, - want: apis.ErrDisallowedFields("lifecycle").Also( - apis.ErrMissingField("image")), - }, { - name: "valid grpc probe", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - GRPC: &corev1.GRPCAction{ - Port: 46, - }, + }, + }, { + name: "disallowed container fields", + c: corev1.Container{ + Image: "foo", + Name: "fail", + Stdin: true, + StdinOnce: true, + TTY: true, + Lifecycle: &corev1.Lifecycle{}, + VolumeDevices: []corev1.VolumeDevice{{ + Name: "disallowed", + DevicePath: "/", + }}, + }, + want: apis.ErrDisallowedFields("lifecycle").Also( + apis.ErrDisallowedFields("stdin")).Also( + apis.ErrDisallowedFields("stdinOnce")).Also( + apis.ErrDisallowedFields("tty")).Also( + apis.ErrDisallowedFields("volumeDevices")), + }, { + name: "has numerous problems", + c: corev1.Container{ + Lifecycle: &corev1.Lifecycle{}, + }, + want: apis.ErrDisallowedFields("lifecycle").Also( + apis.ErrMissingField("image")), + }, { + name: "valid grpc probe", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + GRPC: &corev1.GRPCAction{ + Port: 46, }, }, }, - }, { - name: "valid grpc probe with service", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - GRPC: &corev1.GRPCAction{ - Port: 46, - Service: ptr.String("foo"), - }, + }, + }, { + name: "valid grpc probe with service", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + GRPC: &corev1.GRPCAction{ + Port: 46, + Service: ptr.String("foo"), }, }, }, }, - } + }} + tests = append(tests, getCommonContainerValidationTestCases()...) for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -1995,316 +1988,313 @@ func TestUserContainerValidation(t *testing.T) { } func TestSidecarContainerValidation(t *testing.T) { - tests := []containerValidationTestCase{ - { - name: "probes not allowed", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, + tests := []containerValidationTestCase{{ + name: "probes not allowed", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{}, - }, + }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{}, }, }, - want: apis.ErrDisallowedFields("livenessProbe", "readinessProbe", "readinessProbe.failureThreshold", "readinessProbe.periodSeconds", "readinessProbe.successThreshold", "readinessProbe.timeoutSeconds"), }, - { - name: "invalid probes (no port defined)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - }, + want: apis.ErrDisallowedFields("livenessProbe", "readinessProbe", "readinessProbe.failureThreshold", "readinessProbe.periodSeconds", "readinessProbe.successThreshold", "readinessProbe.timeoutSeconds"), + }, { + name: "invalid probes (no port defined)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{}, - }, + }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{}, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: apis.ErrInvalidValue(0, "livenessProbe.tcpSocket.port, readinessProbe.httpGet.port", "Probe port must be specified"), - }, { - name: "valid with exec probes", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - InitialDelaySeconds: 0, - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: apis.ErrInvalidValue(0, "livenessProbe.tcpSocket.port, readinessProbe.httpGet.port", "Probe port must be specified"), + }, { + name: "valid with exec probes", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + InitialDelaySeconds: 0, + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(5000), }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - Exec: &corev1.ExecAction{}, - }, + }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + Exec: &corev1.ExecAction{}, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "invalid with no handler", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "invalid with no handler", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(5000), }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{}, - }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: apis.ErrMissingOneOf("livenessProbe.httpGet", "livenessProbe.tcpSocket", "livenessProbe.exec", "livenessProbe.grpc"), - }, { - name: "invalid with multiple handlers", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(5000), - }, - Exec: &corev1.ExecAction{}, - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt32(5000), - }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{}, + }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: apis.ErrMissingOneOf("livenessProbe.httpGet", "livenessProbe.tcpSocket", "livenessProbe.exec", "livenessProbe.grpc"), + }, { + name: "invalid with multiple handlers", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(5000), + }, + Exec: &corev1.ExecAction{}, + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt32(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: apis.ErrMultipleOneOf("readinessProbe.exec", "readinessProbe.tcpSocket", "readinessProbe.httpGet"), - }, { - name: "valid liveness http probe", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: apis.ErrMultipleOneOf("readinessProbe.exec", "readinessProbe.tcpSocket", "readinessProbe.httpGet"), + }, { + name: "valid liveness http probe", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "valid liveness tcp probe", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "valid liveness tcp probe", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "valid readiness http probe", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "valid readiness http probe", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "valid readiness tcp probe", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "valid readiness tcp probe", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "valid readiness http probe with named port", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Port: intstr.FromString("http"), // http is the default - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "valid readiness http probe with named port", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Port: intstr.FromString("http"), // http is the default }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "invalid readiness probe (has failureThreshold while using special probe)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 0, - FailureThreshold: 2, - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "invalid readiness probe (has failureThreshold while using special probe)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 0, + FailureThreshold: 2, + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: &apis.FieldError{ - Message: "failureThreshold is disallowed when periodSeconds is zero", - Paths: []string{"readinessProbe.failureThreshold"}, - }, - }, { - name: "invalid readiness probe (has timeoutSeconds while using special probe)", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 0, - TimeoutSeconds: 2, - SuccessThreshold: 1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: &apis.FieldError{ + Message: "failureThreshold is disallowed when periodSeconds is zero", + Paths: []string{"readinessProbe.failureThreshold"}, + }, + }, { + name: "invalid readiness probe (has timeoutSeconds while using special probe)", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 0, + TimeoutSeconds: 2, + SuccessThreshold: 1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: &apis.FieldError{ - Message: "timeoutSeconds is disallowed when periodSeconds is zero", - Paths: []string{"readinessProbe.timeoutSeconds"}, - }, - }, { - name: "out of bounds probe values", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: -1, - TimeoutSeconds: 0, - SuccessThreshold: 0, - FailureThreshold: 0, - InitialDelaySeconds: -1, - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Port: intstr.FromInt(5000), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: &apis.FieldError{ + Message: "timeoutSeconds is disallowed when periodSeconds is zero", + Paths: []string{"readinessProbe.timeoutSeconds"}, + }, + }, { + name: "out of bounds probe values", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: -1, + TimeoutSeconds: 0, + SuccessThreshold: 0, + FailureThreshold: 0, + InitialDelaySeconds: -1, + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Port: intstr.FromInt(5000), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.periodSeconds").Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.timeoutSeconds")).Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.successThreshold")).Also( - apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.failureThreshold")).Also( - apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.initialDelaySeconds")), - }, { - name: "valid grpc probe", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - GRPC: &corev1.GRPCAction{ - Port: 46, - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.periodSeconds").Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.timeoutSeconds")).Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.successThreshold")).Also( + apis.ErrOutOfBoundsValue(0, 1, math.MaxInt32, "readinessProbe.failureThreshold")).Also( + apis.ErrOutOfBoundsValue(-1, 0, math.MaxInt32, "readinessProbe.initialDelaySeconds")), + }, { + name: "valid grpc probe", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + GRPC: &corev1.GRPCAction{ + Port: 46, }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, - }, { - name: "valid grpc probe with service", - c: corev1.Container{ - Image: "foo", - ReadinessProbe: &corev1.Probe{ - PeriodSeconds: 1, - TimeoutSeconds: 1, - SuccessThreshold: 1, - FailureThreshold: 3, - ProbeHandler: corev1.ProbeHandler{ - GRPC: &corev1.GRPCAction{ - Port: 46, - Service: ptr.String("foo"), - }, + }, + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }, { + name: "valid grpc probe with service", + c: corev1.Container{ + Image: "foo", + ReadinessProbe: &corev1.Probe{ + PeriodSeconds: 1, + TimeoutSeconds: 1, + SuccessThreshold: 1, + FailureThreshold: 3, + ProbeHandler: corev1.ProbeHandler{ + GRPC: &corev1.GRPCAction{ + Port: 46, + Service: ptr.String("foo"), }, }, }, - cfgOpts: []configOption{withMultiContainerProbesEnabled()}, - want: nil, }, - } + cfgOpts: []configOption{withMultiContainerProbesEnabled()}, + want: nil, + }} tests = append(tests, getCommonContainerValidationTestCases()...) for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -2326,79 +2316,78 @@ func TestSidecarContainerValidation(t *testing.T) { } func TestInitContainerValidation(t *testing.T) { - tests := []containerValidationTestCase{ - { - name: "has a lifecycle", - c: corev1.Container{ - Name: "foo", - Image: "foo", - Lifecycle: &corev1.Lifecycle{}, - }, - want: apis.ErrDisallowedFields("lifecycle").Also(&apis.FieldError{ - Message: "field not allowed in an init container", - Paths: []string{"lifecycle"}, - }), - cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, - }, { - name: "has lifecycle", - c: corev1.Container{ - Image: "foo", - Lifecycle: &corev1.Lifecycle{}, - }, - want: apis.ErrDisallowedFields("lifecycle").Also(&apis.FieldError{ - Message: "field not allowed in an init container", - Paths: []string{"lifecycle"}, - }), - }, { - name: "invalid liveness tcp probe (has port)", - c: corev1.Container{ - Image: "foo", - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - TCPSocket: &corev1.TCPSocketAction{ - Port: intstr.FromString("http"), - }, + tests := []containerValidationTestCase{{ + name: "has a lifecycle", + c: corev1.Container{ + Name: "foo", + Image: "foo", + Lifecycle: &corev1.Lifecycle{}, + }, + want: apis.ErrDisallowedFields("lifecycle").Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"lifecycle"}, + }), + cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, + }, { + name: "has lifecycle", + c: corev1.Container{ + Image: "foo", + Lifecycle: &corev1.Lifecycle{}, + }, + want: apis.ErrDisallowedFields("lifecycle").Also(&apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"lifecycle"}, + }), + }, { + name: "invalid liveness tcp probe (has port)", + c: corev1.Container{ + Image: "foo", + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + TCPSocket: &corev1.TCPSocketAction{ + Port: intstr.FromString("http"), }, }, }, - want: &apis.FieldError{ + }, + want: &apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"livenessProbe"}, + }, + }, { + name: "disallowed container fields", + c: corev1.Container{ + Image: "foo", + Name: "fail", + Stdin: true, + StdinOnce: true, + TTY: true, + Lifecycle: &corev1.Lifecycle{}, + VolumeDevices: []corev1.VolumeDevice{{ + Name: "disallowed", + DevicePath: "/", + }}, + }, + want: apis.ErrDisallowedFields("lifecycle").Also( + &apis.FieldError{ Message: "field not allowed in an init container", - Paths: []string{"livenessProbe"}}, - }, { - name: "disallowed container fields", - c: corev1.Container{ - Image: "foo", - Name: "fail", - Stdin: true, - StdinOnce: true, - TTY: true, - Lifecycle: &corev1.Lifecycle{}, - VolumeDevices: []corev1.VolumeDevice{{ - Name: "disallowed", - DevicePath: "/", - }}, - }, - want: apis.ErrDisallowedFields("lifecycle").Also( - &apis.FieldError{ - Message: "field not allowed in an init container", - Paths: []string{"lifecycle"}, - }).Also( - apis.ErrDisallowedFields("stdin")).Also( - apis.ErrDisallowedFields("stdinOnce")).Also( - apis.ErrDisallowedFields("tty")).Also( - apis.ErrDisallowedFields("volumeDevices")), - }, { - name: "has numerous problems", - c: corev1.Container{ - Lifecycle: &corev1.Lifecycle{}, - }, - want: apis.ErrDisallowedFields("lifecycle").Also( - &apis.FieldError{ - Message: "field not allowed in an init container", - Paths: []string{"lifecycle"}, - }).Also(apis.ErrMissingField("image")), + Paths: []string{"lifecycle"}, + }).Also( + apis.ErrDisallowedFields("stdin")).Also( + apis.ErrDisallowedFields("stdinOnce")).Also( + apis.ErrDisallowedFields("tty")).Also( + apis.ErrDisallowedFields("volumeDevices")), + }, { + name: "has numerous problems", + c: corev1.Container{ + Lifecycle: &corev1.Lifecycle{}, }, - } + want: apis.ErrDisallowedFields("lifecycle").Also( + &apis.FieldError{ + Message: "field not allowed in an init container", + Paths: []string{"lifecycle"}, + }).Also(apis.ErrMissingField("image")), + }} tests = append(tests, getCommonContainerValidationTestCases()...) for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -2421,424 +2410,423 @@ func TestInitContainerValidation(t *testing.T) { func getCommonContainerValidationTestCases() []containerValidationTestCase { bidir := corev1.MountPropagationBidirectional - return []containerValidationTestCase{ - { - name: "empty container", - c: corev1.Container{}, - want: apis.ErrMissingField(apis.CurrentField), - cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, - }, { - name: "valid container", - c: corev1.Container{ - Image: "foo", - }, - want: nil, - }, { - name: "invalid container image", - c: corev1.Container{ - Image: "foo:bar:baz", - }, - want: &apis.FieldError{ - Message: "Failed to parse image reference", - Paths: []string{"image"}, - Details: `image: "foo:bar:baz", error: could not parse reference: foo:bar:baz`, - }, - }, { - name: "has resources", - c: corev1.Container{ - Image: "foo", - Resources: corev1.ResourceRequirements{ - Limits: corev1.ResourceList{ - corev1.ResourceMemory: resource.MustParse("250M"), - }, - Requests: corev1.ResourceList{ - corev1.ResourceCPU: resource.MustParse("25m"), - }, - }, - }, - want: nil, - }, { - name: "has no container ports set", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{}, - }, - want: nil, - }, { - name: "has container port value too large", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 65536, - }}, - }, - want: apis.ErrOutOfBoundsValue(65536, 0, 65535, "ports.containerPort"), - }, { - name: "has host ip", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - HostIP: "127.0.0.1", - }}, - }, - want: apis.ErrDisallowedFields("ports.hostIP"), - }, { - name: "port conflicts with profiling port", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8008, - }}, - }, - want: apis.ErrInvalidValue("8008 is a reserved port", "ports.containerPort", - "8008 is a reserved port, please use a different value"), - }, { - name: "port conflicts with queue proxy", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8013, - }}, - }, - want: apis.ErrInvalidValue("8013 is a reserved port", "ports.containerPort", - "8013 is a reserved port, please use a different value"), - }, { - name: "port conflicts with queue proxy", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8012, - }}, - }, - want: apis.ErrInvalidValue("8012 is a reserved port", "ports.containerPort", - "8012 is a reserved port, please use a different value"), - }, { - name: "port conflicts with queue proxy metrics", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 9090, - }}, - }, - want: apis.ErrInvalidValue("9090 is a reserved port", "ports.containerPort", - "9090 is a reserved port, please use a different value"), - }, { - name: "port conflicts with user queue proxy metrics for user", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 9091, - }}, - }, - want: apis.ErrInvalidValue("9091 is a reserved port", "ports.containerPort", - "9091 is a reserved port, please use a different value"), - }, { - name: "port conflicts with queue proxy admin", - c: corev1.Container{ - Image: "foo", - Ports: []corev1.ContainerPort{{ - ContainerPort: 8022, - }}, - }, - want: apis.ErrInvalidValue("8022 is a reserved port", "ports.containerPort", - "8022 is a reserved port, please use a different value"), - }, { - name: "has unknown volumeMounts", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - Name: "the-name", - SubPath: "oops", - MountPropagation: &bidir, - }}, - }, - want: (&apis.FieldError{ - Message: "volumeMount has no matching volume", - Paths: []string{"name"}, - }).ViaFieldIndex("volumeMounts", 0).Also( - (&apis.FieldError{ - Message: "volume mount should be readOnly for this type of volume", - Paths: []string{"readOnly"}, - }).ViaFieldIndex("volumeMounts", 0)).Also( - apis.ErrMissingField("mountPath").ViaFieldIndex("volumeMounts", 0)).Also( - apis.ErrDisallowedFields("mountPropagation").ViaFieldIndex("volumeMounts", 0)), - }, { - name: "has known volumeMounts", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name", - ReadOnly: true, - }}, + return []containerValidationTestCase{{ + name: "empty container", + c: corev1.Container{}, + want: apis.ErrMissingField(apis.CurrentField), + cfgOpts: []configOption{withPodSpecInitContainersEnabled()}, + }, { + name: "valid container", + c: corev1.Container{ + Image: "foo", + }, + want: nil, + }, { + name: "invalid container image", + c: corev1.Container{ + Image: "foo:bar:baz", + }, + want: &apis.FieldError{ + Message: "Failed to parse image reference", + Paths: []string{"image"}, + Details: `image: "foo:bar:baz", error: could not parse reference: foo:bar:baz`, + }, + }, { + name: "has resources", + c: corev1.Container{ + Image: "foo", + Resources: corev1.ResourceRequirements{ + Limits: corev1.ResourceList{ + corev1.ResourceMemory: resource.MustParse("250M"), + }, + Requests: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("25m"), + }, }, - volumes: map[string]corev1.Volume{ - "the-name": { - Name: "the-name", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "test-cm", - }, + }, + want: nil, + }, { + name: "has no container ports set", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{}, + }, + want: nil, + }, { + name: "has container port value too large", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 65536, + }}, + }, + want: apis.ErrOutOfBoundsValue(65536, 0, 65535, "ports.containerPort"), + }, { + name: "has host ip", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + HostIP: "127.0.0.1", + }}, + }, + want: apis.ErrDisallowedFields("ports.hostIP"), + }, { + name: "port conflicts with profiling port", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8008, + }}, + }, + want: apis.ErrInvalidValue("8008 is a reserved port", "ports.containerPort", + "8008 is a reserved port, please use a different value"), + }, { + name: "port conflicts with queue proxy", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8013, + }}, + }, + want: apis.ErrInvalidValue("8013 is a reserved port", "ports.containerPort", + "8013 is a reserved port, please use a different value"), + }, { + name: "port conflicts with queue proxy", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8012, + }}, + }, + want: apis.ErrInvalidValue("8012 is a reserved port", "ports.containerPort", + "8012 is a reserved port, please use a different value"), + }, { + name: "port conflicts with queue proxy metrics", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 9090, + }}, + }, + want: apis.ErrInvalidValue("9090 is a reserved port", "ports.containerPort", + "9090 is a reserved port, please use a different value"), + }, { + name: "port conflicts with user queue proxy metrics for user", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 9091, + }}, + }, + want: apis.ErrInvalidValue("9091 is a reserved port", "ports.containerPort", + "9091 is a reserved port, please use a different value"), + }, { + name: "port conflicts with queue proxy admin", + c: corev1.Container{ + Image: "foo", + Ports: []corev1.ContainerPort{{ + ContainerPort: 8022, + }}, + }, + want: apis.ErrInvalidValue("8022 is a reserved port", "ports.containerPort", + "8022 is a reserved port, please use a different value"), + }, { + name: "has unknown volumeMounts", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + Name: "the-name", + SubPath: "oops", + MountPropagation: &bidir, + }}, + }, + want: (&apis.FieldError{ + Message: "volumeMount has no matching volume", + Paths: []string{"name"}, + }).ViaFieldIndex("volumeMounts", 0).Also( + (&apis.FieldError{ + Message: "volume mount should be readOnly for this type of volume", + Paths: []string{"readOnly"}, + }).ViaFieldIndex("volumeMounts", 0)).Also( + apis.ErrMissingField("mountPath").ViaFieldIndex("volumeMounts", 0)).Also( + apis.ErrDisallowedFields("mountPropagation").ViaFieldIndex("volumeMounts", 0)), + }, { + name: "has known volumeMounts", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name", + ReadOnly: true, + }}, + }, + volumes: map[string]corev1.Volume{ + "the-name": { + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test-cm", }, }, }, }, - }, { - name: "has known volumeMounts, but at reserved path", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "//dev//", - Name: "the-name", - ReadOnly: true, - }}, - }, - volumes: map[string]corev1.Volume{ - "the-name": { - Name: "the-name", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "test-cm", - }, + }, + }, { + name: "has known volumeMounts, but at reserved path", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "//dev//", + Name: "the-name", + ReadOnly: true, + }}, + }, + volumes: map[string]corev1.Volume{ + "the-name": { + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test-cm", }, }, }, }, - want: (&apis.FieldError{ - Message: `mountPath "/dev" is a reserved path`, - Paths: []string{"mountPath"}, - }).ViaFieldIndex("volumeMounts", 0), - }, { - name: "has known volumeMounts, bad mountPath", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "not/absolute", - Name: "the-name", - ReadOnly: true, - }}, - }, - volumes: map[string]corev1.Volume{ - "the-name": { - Name: "the-name", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "test-cm", - }, + }, + want: (&apis.FieldError{ + Message: `mountPath "/dev" is a reserved path`, + Paths: []string{"mountPath"}, + }).ViaFieldIndex("volumeMounts", 0), + }, { + name: "has known volumeMounts, bad mountPath", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "not/absolute", + Name: "the-name", + ReadOnly: true, + }}, + }, + volumes: map[string]corev1.Volume{ + "the-name": { + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test-cm", }, }, }, }, - want: apis.ErrInvalidValue("not/absolute", "volumeMounts[0].mountPath"), - }, { - name: "Empty dir has rw access", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name", - }}, - }, - volumes: map[string]corev1.Volume{ - "the-name": { - Name: "the-name", - VolumeSource: corev1.VolumeSource{ - EmptyDir: &corev1.EmptyDirVolumeSource{ - Medium: "Memory", - }, + }, + want: apis.ErrInvalidValue("not/absolute", "volumeMounts[0].mountPath"), + }, { + name: "Empty dir has rw access", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name", + }}, + }, + volumes: map[string]corev1.Volume{ + "the-name": { + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + EmptyDir: &corev1.EmptyDirVolumeSource{ + Medium: "Memory", }, }, }, - }, { - name: "has known volumeMount twice", - c: corev1.Container{ - Image: "foo", - VolumeMounts: []corev1.VolumeMount{{ - MountPath: "/mount/path", - Name: "the-name", - ReadOnly: true, - }, { - MountPath: "/another/mount/path", - Name: "the-name", - ReadOnly: true, - }}, - }, - volumes: map[string]corev1.Volume{ - "the-name": { - Name: "the-name", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "test-cm", - }, + }, + }, { + name: "has known volumeMount twice", + c: corev1.Container{ + Image: "foo", + VolumeMounts: []corev1.VolumeMount{{ + MountPath: "/mount/path", + Name: "the-name", + ReadOnly: true, + }, { + MountPath: "/another/mount/path", + Name: "the-name", + ReadOnly: true, + }}, + }, + volumes: map[string]corev1.Volume{ + "the-name": { + Name: "the-name", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "test-cm", }, }, }, }, - }, { - name: "not allowed to add a security context capability", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - Capabilities: &corev1.Capabilities{ - Add: []corev1.Capability{"all"}, - }, + }, + }, { + name: "not allowed to add a security context capability", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Add: []corev1.Capability{"all"}, }, }, - want: apis.ErrDisallowedFields("securityContext.capabilities.add"), - }, { - name: "allowed to add a security context capability when gate is enabled", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - Capabilities: &corev1.Capabilities{ - Add: []corev1.Capability{"all"}, - }, + }, + want: apis.ErrDisallowedFields("securityContext.capabilities.add"), + }, { + name: "allowed to add a security context capability when gate is enabled", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Add: []corev1.Capability{"all"}, }, }, - cfgOpts: []configOption{withContainerSpecAddCapabilitiesEnabled()}, - want: nil, - }, { - name: "disallowed security context field", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - Privileged: ptr.Bool(true), - }, + }, + cfgOpts: []configOption{withContainerSpecAddCapabilitiesEnabled()}, + want: nil, + }, { + name: "disallowed security context field", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + Privileged: ptr.Bool(true), }, - want: apis.ErrDisallowedFields("securityContext.privileged"), - }, { - name: "allowed setting security context field Privileged to false", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - Privileged: ptr.Bool(false), - }, + }, + want: apis.ErrDisallowedFields("securityContext.privileged"), + }, { + name: "allowed setting security context field Privileged to false", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + Privileged: ptr.Bool(false), }, - want: nil, - }, { - name: "too large uid", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - RunAsUser: ptr.Int64(math.MaxInt32 + 1), - }, + }, + want: nil, + }, { + name: "too large uid", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + RunAsUser: ptr.Int64(math.MaxInt32 + 1), }, - want: apis.ErrOutOfBoundsValue(int64(math.MaxInt32+1), 0, math.MaxInt32, "securityContext.runAsUser"), - }, { - name: "negative uid", - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - RunAsUser: ptr.Int64(-10), - }, + }, + want: apis.ErrOutOfBoundsValue(int64(math.MaxInt32+1), 0, math.MaxInt32, "securityContext.runAsUser"), + }, { + name: "negative uid", + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + RunAsUser: ptr.Int64(-10), }, - want: apis.ErrOutOfBoundsValue(-10, 0, math.MaxInt32, "securityContext.runAsUser"), - }, { - name: "too large gid - feature enabled", - cfgOpts: []configOption{withPodSpecSecurityContextEnabled()}, - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - RunAsGroup: ptr.Int64(math.MaxInt32 + 1), - }, + }, + want: apis.ErrOutOfBoundsValue(-10, 0, math.MaxInt32, "securityContext.runAsUser"), + }, { + name: "too large gid - feature enabled", + cfgOpts: []configOption{withPodSpecSecurityContextEnabled()}, + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + RunAsGroup: ptr.Int64(math.MaxInt32 + 1), }, - want: apis.ErrOutOfBoundsValue(int64(math.MaxInt32+1), 0, math.MaxInt32, "securityContext.runAsGroup"), - }, { - name: "negative gid - feature enabled", - cfgOpts: []configOption{withPodSpecSecurityContextEnabled()}, - c: corev1.Container{ - Image: "foo", - SecurityContext: &corev1.SecurityContext{ - RunAsGroup: ptr.Int64(-10), - }, - }, - want: apis.ErrOutOfBoundsValue(-10, 0, math.MaxInt32, "securityContext.runAsGroup"), - }, { - name: "envFrom - None of", - c: corev1.Container{ - Image: "foo", - EnvFrom: []corev1.EnvFromSource{{}}, - }, - want: apis.ErrMissingOneOf("envFrom.configMapRef", "envFrom.secretRef"), - }, { - name: "envFrom - Multiple", - c: corev1.Container{ - Image: "foo", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "ConfigMapName", - }, + }, + want: apis.ErrOutOfBoundsValue(int64(math.MaxInt32+1), 0, math.MaxInt32, "securityContext.runAsGroup"), + }, { + name: "negative gid - feature enabled", + cfgOpts: []configOption{withPodSpecSecurityContextEnabled()}, + c: corev1.Container{ + Image: "foo", + SecurityContext: &corev1.SecurityContext{ + RunAsGroup: ptr.Int64(-10), + }, + }, + want: apis.ErrOutOfBoundsValue(-10, 0, math.MaxInt32, "securityContext.runAsGroup"), + }, { + name: "envFrom - None of", + c: corev1.Container{ + Image: "foo", + EnvFrom: []corev1.EnvFromSource{{}}, + }, + want: apis.ErrMissingOneOf("envFrom.configMapRef", "envFrom.secretRef"), + }, { + name: "envFrom - Multiple", + c: corev1.Container{ + Image: "foo", + EnvFrom: []corev1.EnvFromSource{{ + ConfigMapRef: &corev1.ConfigMapEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "ConfigMapName", }, - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "SecretName", - }, + }, + SecretRef: &corev1.SecretEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "SecretName", }, - }}, - }, - want: apis.ErrMultipleOneOf("envFrom.configMapRef", "envFrom.secretRef"), - }, { - name: "envFrom - Secret", - c: corev1.Container{ - Image: "foo", - EnvFrom: []corev1.EnvFromSource{{ - SecretRef: &corev1.SecretEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "SecretName", - }, + }, + }}, + }, + want: apis.ErrMultipleOneOf("envFrom.configMapRef", "envFrom.secretRef"), + }, { + name: "envFrom - Secret", + c: corev1.Container{ + Image: "foo", + EnvFrom: []corev1.EnvFromSource{{ + SecretRef: &corev1.SecretEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "SecretName", }, - }}, - }, - want: nil, - }, { - name: "envFrom - ConfigMap", - c: corev1.Container{ - Image: "foo", - EnvFrom: []corev1.EnvFromSource{{ - ConfigMapRef: &corev1.ConfigMapEnvSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "ConfigMapName", - }, + }, + }}, + }, + want: nil, + }, { + name: "envFrom - ConfigMap", + c: corev1.Container{ + Image: "foo", + EnvFrom: []corev1.EnvFromSource{{ + ConfigMapRef: &corev1.ConfigMapEnvSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "ConfigMapName", }, - }}, - }, - want: nil, - }, { - name: "termination message policy", - c: corev1.Container{ - Image: "foo", - TerminationMessagePolicy: "Not a Policy", - }, - want: apis.ErrInvalidValue(corev1.TerminationMessagePolicy("Not a Policy"), "terminationMessagePolicy"), - }, { - name: "empty env var name", - c: corev1.Container{ - Image: "foo", - Env: []corev1.EnvVar{{ - Value: "Foo", - }}, - }, - want: apis.ErrMissingField("env[0].name"), - }, { - name: "disallowed envvarsource", - c: corev1.Container{ - Image: "foo", - Env: []corev1.EnvVar{{ - Name: "Foo", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "/v1", - }, + }, + }}, + }, + want: nil, + }, { + name: "termination message policy", + c: corev1.Container{ + Image: "foo", + TerminationMessagePolicy: "Not a Policy", + }, + want: apis.ErrInvalidValue(corev1.TerminationMessagePolicy("Not a Policy"), "terminationMessagePolicy"), + }, { + name: "empty env var name", + c: corev1.Container{ + Image: "foo", + Env: []corev1.EnvVar{{ + Value: "Foo", + }}, + }, + want: apis.ErrMissingField("env[0].name"), + }, { + name: "disallowed envvarsource", + c: corev1.Container{ + Image: "foo", + Env: []corev1.EnvVar{{ + Name: "Foo", + ValueFrom: &corev1.EnvVarSource{ + FieldRef: &corev1.ObjectFieldSelector{ + FieldPath: "/v1", }, - }}, - }, - want: apis.ErrDisallowedFields("env[0].valueFrom.fieldRef"), - }} + }, + }}, + }, + want: apis.ErrDisallowedFields("env[0].valueFrom.fieldRef"), + }} } func TestVolumeValidation(t *testing.T) { @@ -2954,7 +2942,8 @@ func TestVolumeValidation(t *testing.T) { ClaimName: "myclaim", ReadOnly: false, }, - }}, + }, + }, want: (&apis.FieldError{ Message: `Persistent volume claim support is disabled, but found persistent volume claim myclaim`, }).Also(&apis.FieldError{ @@ -3125,14 +3114,15 @@ func TestVolumeValidation(t *testing.T) { Name: "foo", }, Items: []corev1.KeyToPath{{}}, - }}, { + }, + }, { ConfigMap: &corev1.ConfigMapProjection{ LocalObjectReference: corev1.LocalObjectReference{ Name: "foo", }, Items: []corev1.KeyToPath{{}}, - }}, - }, + }, + }}, }, }, }, @@ -3218,8 +3208,7 @@ func TestVolumeValidation(t *testing.T) { }, }, want: apis.ErrGeneric("Within a single item, cannot set both", "projected[0].downwardAPI.items[0].fieldRef", "projected[0].downwardAPI.items[0].resourceFieldRef"), - }, - } + }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/pkg/apis/serving/v1/configuration_lifecycle_test.go b/pkg/apis/serving/v1/configuration_lifecycle_test.go index 5e394aa47a81..407a78eec52b 100644 --- a/pkg/apis/serving/v1/configuration_lifecycle_test.go +++ b/pkg/apis/serving/v1/configuration_lifecycle_test.go @@ -200,7 +200,6 @@ func TestConfigurationIsFailed(t *testing.T) { name: "Unknown condition status should not be failed", status: ConfigurationStatus{ Status: duckv1.Status{ - Conditions: duckv1.Conditions{{ Type: ConfigurationConditionReady, Status: corev1.ConditionUnknown, diff --git a/pkg/apis/serving/v1/configuration_validation_test.go b/pkg/apis/serving/v1/configuration_validation_test.go index 37bc278279b1..e4f4f0c767cb 100644 --- a/pkg/apis/serving/v1/configuration_validation_test.go +++ b/pkg/apis/serving/v1/configuration_validation_test.go @@ -412,6 +412,7 @@ func TestConfigurationLabelValidation(t *testing.T) { }) } } + func TestImmutableConfigurationFields(t *testing.T) { tests := []struct { name string @@ -751,8 +752,10 @@ func TestConfigurationAnnotationUpdate(t *testing.T) { }, Spec: getConfigurationSpec("helloworld:foo"), }, - want: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + want: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update creator annotation with spec changes", this: &Configuration{ @@ -775,8 +778,10 @@ func TestConfigurationAnnotationUpdate(t *testing.T) { }, Spec: getConfigurationSpec("helloworld:foo"), }, - want: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + want: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update lastModifier annotation without spec changes", this: &Configuration{ diff --git a/pkg/apis/serving/v1/revision_lifecycle_test.go b/pkg/apis/serving/v1/revision_lifecycle_test.go index 128d56cb1069..62781c3b4641 100644 --- a/pkg/apis/serving/v1/revision_lifecycle_test.go +++ b/pkg/apis/serving/v1/revision_lifecycle_test.go @@ -227,7 +227,6 @@ func TestRevisionIsFailed(t *testing.T) { name: "Unknown condition status should not be failed", status: RevisionStatus{ Status: duckv1.Status{ - Conditions: duckv1.Conditions{{ Type: RevisionConditionReady, Status: corev1.ConditionUnknown, diff --git a/pkg/apis/serving/v1/revision_validation_test.go b/pkg/apis/serving/v1/revision_validation_test.go index 93ba8ce164f7..9373923ad229 100644 --- a/pkg/apis/serving/v1/revision_validation_test.go +++ b/pkg/apis/serving/v1/revision_validation_test.go @@ -458,7 +458,8 @@ func TestRevisionSpecValidation(t *testing.T) { "revision-timeout-seconds": "25", "max-revision-timeout-seconds": "50", "revision-response-start-timeout-seconds": "10", - "revision-idle-timeout-seconds": "10"}, + "revision-idle-timeout-seconds": "10", + }, }) return s.ToContext(ctx) }, @@ -574,7 +575,8 @@ func TestImmutableFields(t *testing.T) { "revision-timeout-seconds": "25", "max-revision-timeout-seconds": "50", "revision-response-start-timeout-seconds": "10", - "revision-idle-timeout-seconds": "10"}, + "revision-idle-timeout-seconds": "10", + }, }) return s.ToContext(ctx) }, diff --git a/pkg/apis/serving/v1/route_lifecycle_test.go b/pkg/apis/serving/v1/route_lifecycle_test.go index 6614a13a8658..4a10b085689f 100644 --- a/pkg/apis/serving/v1/route_lifecycle_test.go +++ b/pkg/apis/serving/v1/route_lifecycle_test.go @@ -106,7 +106,6 @@ func TestRouteIsReady(t *testing.T) { name: "Unknown condition status should not be ready", status: RouteStatus{ Status: duckv1.Status{ - Conditions: duckv1.Conditions{{ Type: RouteConditionReady, Status: corev1.ConditionUnknown, @@ -205,7 +204,6 @@ func TestRouteIsFailed(t *testing.T) { name: "Unknown condition status should not be failed", status: RouteStatus{ Status: duckv1.Status{ - Conditions: duckv1.Conditions{{ Type: RouteConditionReady, Status: corev1.ConditionUnknown, diff --git a/pkg/apis/serving/v1/route_validation_test.go b/pkg/apis/serving/v1/route_validation_test.go index ff9dd806a97e..50b3a62cf98a 100644 --- a/pkg/apis/serving/v1/route_validation_test.go +++ b/pkg/apis/serving/v1/route_validation_test.go @@ -641,8 +641,10 @@ func TestRouteAnnotationUpdate(t *testing.T) { }, Spec: getRouteSpec("old"), }, - wantErr: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + wantErr: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update creator annotation with spec changes", this: &Route{ @@ -665,8 +667,10 @@ func TestRouteAnnotationUpdate(t *testing.T) { }, Spec: getRouteSpec("old"), }, - wantErr: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + wantErr: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update lastModifier annotation without spec changes", this: &Route{ diff --git a/pkg/apis/serving/v1/service_lifecycle_test.go b/pkg/apis/serving/v1/service_lifecycle_test.go index 051deae7e4c5..29935232c567 100644 --- a/pkg/apis/serving/v1/service_lifecycle_test.go +++ b/pkg/apis/serving/v1/service_lifecycle_test.go @@ -199,7 +199,6 @@ func TestServiceIsFailed(t *testing.T) { name: "Unknown condition status should not be failed", status: ServiceStatus{ Status: duckv1.Status{ - Conditions: duckv1.Conditions{{ Type: ServiceConditionReady, Status: corev1.ConditionUnknown, diff --git a/pkg/apis/serving/v1/service_validation_test.go b/pkg/apis/serving/v1/service_validation_test.go index f4c1a0c2d55b..8e5fa344ac84 100644 --- a/pkg/apis/serving/v1/service_validation_test.go +++ b/pkg/apis/serving/v1/service_validation_test.go @@ -731,8 +731,10 @@ func TestServiceAnnotationUpdate(t *testing.T) { }, Spec: getServiceSpec("helloworld:foo"), }, - want: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + want: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update lastModifier without spec changes", this: &Service{ diff --git a/pkg/apis/serving/v1beta1/domainmapping_validation_test.go b/pkg/apis/serving/v1beta1/domainmapping_validation_test.go index 3f3092dde903..1e909ef2afe9 100644 --- a/pkg/apis/serving/v1beta1/domainmapping_validation_test.go +++ b/pkg/apis/serving/v1beta1/domainmapping_validation_test.go @@ -196,8 +196,10 @@ func TestDomainMappingAnnotationUpdate(t *testing.T) { }, Spec: spec("old"), }, - want: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + want: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update creator annotation with spec changes", this: &DomainMapping{ @@ -222,8 +224,10 @@ func TestDomainMappingAnnotationUpdate(t *testing.T) { }, Spec: spec("old"), }, - want: (&apis.FieldError{Message: "annotation value is immutable", - Paths: []string{serving.CreatorAnnotation}}).ViaField("metadata.annotations"), + want: (&apis.FieldError{ + Message: "annotation value is immutable", + Paths: []string{serving.CreatorAnnotation}, + }).ViaField("metadata.annotations"), }, { name: "update lastModifier annotation without spec changes", this: &DomainMapping{ diff --git a/pkg/autoscaler/aggregation/bucketing_test.go b/pkg/autoscaler/aggregation/bucketing_test.go index 504bf59d3a9c..80c58092a526 100644 --- a/pkg/autoscaler/aggregation/bucketing_test.go +++ b/pkg/autoscaler/aggregation/bucketing_test.go @@ -604,6 +604,7 @@ func TestTimedFloat64BucketsWindowUpdateNoOp(t *testing.T) { t.Errorf("FirstWrite after update = %v, want: %v", got, want) } } + func BenchmarkWindowAverage(b *testing.B) { // Window lengths in secs. for _, wl := range []int{30, 60, 120, 240, 600} { diff --git a/pkg/autoscaler/bucket/bucket_test.go b/pkg/autoscaler/bucket/bucket_test.go index 8f48955f8142..3a6a4c4f519f 100644 --- a/pkg/autoscaler/bucket/bucket_test.go +++ b/pkg/autoscaler/bucket/bucket_test.go @@ -64,7 +64,8 @@ func TestAutoscalerBucketSet(t *testing.T) { } want = []string{ - "autoscaler-bucket-00-of-03", "autoscaler-bucket-01-of-03", "autoscaler-bucket-02-of-03"} + "autoscaler-bucket-00-of-03", "autoscaler-bucket-01-of-03", "autoscaler-bucket-02-of-03", + } if got := bucketNames(AutoscalerBucketSet(3).Buckets()); !cmp.Equal(got, want) { t.Errorf("AutoscalerBucketSet = %v, want = %v", got, want) } diff --git a/pkg/autoscaler/metrics/collector.go b/pkg/autoscaler/metrics/collector.go index 9719fac388eb..a17b6e1d463e 100644 --- a/pkg/autoscaler/metrics/collector.go +++ b/pkg/autoscaler/metrics/collector.go @@ -96,8 +96,10 @@ type MetricCollector struct { watcher func(types.NamespacedName) } -var _ Collector = (*MetricCollector)(nil) -var _ MetricClient = (*MetricCollector)(nil) +var ( + _ Collector = (*MetricCollector)(nil) + _ MetricClient = (*MetricCollector)(nil) +) // NewMetricCollector creates a new metric collector. func NewMetricCollector(statsScraperFactory StatsScraperFactory, logger *zap.SugaredLogger) *MetricCollector { @@ -263,7 +265,8 @@ func (c *collection) getScraper() StatsScraper { // newCollection creates a new collection, which uses the given scraper to // collect stats every scrapeTickInterval. func newCollection(metric *autoscalingv1alpha1.Metric, scraper StatsScraper, clock clock.WithTicker, - callback func(types.NamespacedName), logger *zap.SugaredLogger) *collection { + callback func(types.NamespacedName), logger *zap.SugaredLogger, +) *collection { // Pick the constructor to use to build the buckets. // NB: this relies on the fact that aggregation algorithm is set on annotation of revision // and as such is immutable. diff --git a/pkg/autoscaler/metrics/stats_scraper.go b/pkg/autoscaler/metrics/stats_scraper.go index fa97b44b206a..ab39e09aff0e 100644 --- a/pkg/autoscaler/metrics/stats_scraper.go +++ b/pkg/autoscaler/metrics/stats_scraper.go @@ -160,7 +160,8 @@ type serviceScraper struct { // NewStatsScraper creates a new StatsScraper for the Revision which // the given Metric is responsible for. func NewStatsScraper(metric *autoscalingv1alpha1.Metric, revisionName string, podAccessor resources.PodAccessor, - usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, logger *zap.SugaredLogger) StatsScraper { + usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, logger *zap.SugaredLogger, +) StatsScraper { directClient := newHTTPScrapeClient(client) meshClient := newHTTPScrapeClient(noKeepaliveClient) return newServiceScraperWithClient(metric, revisionName, podAccessor, usePassthroughLb, meshMode, directClient, meshClient, logger) @@ -173,7 +174,8 @@ func newServiceScraperWithClient( usePassthroughLb bool, meshMode netcfg.MeshCompatibilityMode, directClient, meshClient scrapeClient, - logger *zap.SugaredLogger) *serviceScraper { + logger *zap.SugaredLogger, +) *serviceScraper { svcName := metric.Labels[serving.ServiceLabelKey] cfgName := metric.Labels[serving.ConfigurationLabelKey] diff --git a/pkg/autoscaler/metrics/stats_scraper_test.go b/pkg/autoscaler/metrics/stats_scraper_test.go index 5494a979a47e..cd99691fa76b 100644 --- a/pkg/autoscaler/metrics/stats_scraper_test.go +++ b/pkg/autoscaler/metrics/stats_scraper_test.go @@ -42,27 +42,25 @@ import ( . "knative.dev/pkg/reconciler/testing" ) -var ( - testStats = []Stat{{ - PodName: "pod-1", - AverageConcurrentRequests: 3.0, - AverageProxiedConcurrentRequests: 2.0, - RequestCount: 5, - ProxiedRequestCount: 4, - }, { - PodName: "pod-2", - AverageConcurrentRequests: 5.0, - AverageProxiedConcurrentRequests: 4.0, - RequestCount: 7, - ProxiedRequestCount: 6, - }, { - PodName: "pod-3", - AverageConcurrentRequests: 3.0, - AverageProxiedConcurrentRequests: 2.0, - RequestCount: 5, - ProxiedRequestCount: 4, - }} -) +var testStats = []Stat{{ + PodName: "pod-1", + AverageConcurrentRequests: 3.0, + AverageProxiedConcurrentRequests: 2.0, + RequestCount: 5, + ProxiedRequestCount: 4, +}, { + PodName: "pod-2", + AverageConcurrentRequests: 5.0, + AverageProxiedConcurrentRequests: 4.0, + RequestCount: 7, + ProxiedRequestCount: 6, +}, { + PodName: "pod-3", + AverageConcurrentRequests: 3.0, + AverageProxiedConcurrentRequests: 2.0, + RequestCount: 5, + ProxiedRequestCount: 4, +}} const ( testRevision = "just-a-test-revision" @@ -537,8 +535,10 @@ func TestScrapeReportErrorIfAnyFails(t *testing.T) { makePods(ctx, "pods-", 2, metav1.Now()) // 1 success and 10 failures so one scrape fails permanently through retries. - client := newTestScrapeClient(testStats, []error{nil, errTest, errTest, - errTest, errTest, errTest, errTest, errTest, errTest, errTest, errTest}) + client := newTestScrapeClient(testStats, []error{ + nil, errTest, errTest, + errTest, errTest, errTest, errTest, errTest, errTest, errTest, errTest, + }) scraper := serviceScraperForTest(ctx, t, netcfg.MeshCompatibilityModeAuto, client, client, false /*podsAddressable*/, false /*passthroughLb*/) _, err = scraper.Scrape(defaultMetric.Spec.StableWindow) @@ -789,7 +789,8 @@ func TestPodDirectPassthroughScrapeNoneSucceed(t *testing.T) { } func serviceScraperForTest(ctx context.Context, t *testing.T, meshMode netcfg.MeshCompatibilityMode, directClient, meshClient scrapeClient, - podsAddressable bool, usePassthroughLb bool) *serviceScraper { + podsAddressable bool, usePassthroughLb bool, +) *serviceScraper { metric := testMetric() accessor := resources.NewPodAccessor( fakepodsinformer.Get(ctx).Lister(), diff --git a/pkg/autoscaler/scaling/autoscaler.go b/pkg/autoscaler/scaling/autoscaler.go index fb0bd66ec949..0986c415e687 100644 --- a/pkg/autoscaler/scaling/autoscaler.go +++ b/pkg/autoscaler/scaling/autoscaler.go @@ -68,7 +68,8 @@ func New( namespace, revision string, metricClient metrics.MetricClient, podCounter resources.EndpointsCounter, - deciderSpec *DeciderSpec) UniScaler { + deciderSpec *DeciderSpec, +) UniScaler { var delayer *max.TimeWindow if deciderSpec.ScaleDownDelay > 0 { delayer = max.NewTimeWindow(deciderSpec.ScaleDownDelay, tickInterval) @@ -84,7 +85,8 @@ func newAutoscaler( metricClient metrics.MetricClient, podCounter podCounter, deciderSpec *DeciderSpec, - delayWindow *max.TimeWindow) *autoscaler { + delayWindow *max.TimeWindow, +) *autoscaler { // We always start in the panic mode, if the deployment is scaled up over 1 pod. // If the scale is 0 or 1, normal Autoscaler behavior is fine. // When Autoscaler restarts we lose metric history, which causes us to diff --git a/pkg/autoscaler/scaling/autoscaler_test.go b/pkg/autoscaler/scaling/autoscaler_test.go index 48547ff11663..63e6e6f67142 100644 --- a/pkg/autoscaler/scaling/autoscaler_test.go +++ b/pkg/autoscaler/scaling/autoscaler_test.go @@ -566,13 +566,15 @@ func TestAutoscalerUpdateTarget(t *testing.T) { // For table tests and tests that don't care about changing scale. func newTestAutoscalerNoPC(targetValue, targetBurstCapacity float64, - metrics metrics.MetricClient) *autoscaler { + metrics metrics.MetricClient, +) *autoscaler { a, _ := newTestAutoscaler(targetValue, targetBurstCapacity, metrics) return a } func newTestAutoscaler(targetValue, targetBurstCapacity float64, - metrics metrics.MetricClient) (*autoscaler, *fakePodCounter) { + metrics metrics.MetricClient, +) (*autoscaler, *fakePodCounter) { return newTestAutoscalerWithScalingMetric(targetValue, targetBurstCapacity, metrics, "concurrency", false /*panic*/) } diff --git a/pkg/autoscaler/scaling/multiscaler.go b/pkg/autoscaler/scaling/multiscaler.go index 973657d5998e..d1f59b511bc2 100644 --- a/pkg/autoscaler/scaling/multiscaler.go +++ b/pkg/autoscaler/scaling/multiscaler.go @@ -193,7 +193,8 @@ type MultiScaler struct { func NewMultiScaler( stopCh <-chan struct{}, uniScalerFactory UniScalerFactory, - logger *zap.SugaredLogger) *MultiScaler { + logger *zap.SugaredLogger, +) *MultiScaler { return &MultiScaler{ scalers: make(map[types.NamespacedName]*scalerRunner), scalersStopCh: stopCh, diff --git a/pkg/autoscaler/scaling/multiscaler_test.go b/pkg/autoscaler/scaling/multiscaler_test.go index a64dee134fd4..d63243fe319b 100644 --- a/pkg/autoscaler/scaling/multiscaler_test.go +++ b/pkg/autoscaler/scaling/multiscaler_test.go @@ -418,12 +418,14 @@ func TestSameSign(t *testing.T) { tests := []struct { a, b int32 want bool - }{{1982, 1984, true}, + }{ + {1982, 1984, true}, {-1984, -1988, true}, {-1988, 2006, false}, {-2006, 2009, false}, {0, 1, true}, // 0 is considered positive for our needs - {0, -42, false}} + {0, -42, false}, + } for _, test := range tests { if got, want := sameSign(test.a, test.b), test.want; got != want { t.Errorf("%d <=> %d: got: %v, want: %v", test.a, test.b, got, want) diff --git a/pkg/autoscaler/statforwarder/forwarder_test.go b/pkg/autoscaler/statforwarder/forwarder_test.go index 65f985afecc4..1a8bb8212509 100644 --- a/pkg/autoscaler/statforwarder/forwarder_test.go +++ b/pkg/autoscaler/statforwarder/forwarder_test.go @@ -132,8 +132,8 @@ func TestForwarderReconcile(t *testing.T) { Name: autoscalerPortName, Port: autoscalerPort, Protocol: corev1.ProtocolTCP, - }}}, - } + }}, + }} // Check the endpoints got updated. el := endpoints.Lister().Endpoints(testNs) diff --git a/pkg/autoscaler/statforwarder/leases.go b/pkg/autoscaler/statforwarder/leases.go index 81bab06782c5..1806ffeae255 100644 --- a/pkg/autoscaler/statforwarder/leases.go +++ b/pkg/autoscaler/statforwarder/leases.go @@ -244,8 +244,8 @@ func (f *leaseTracker) createOrUpdateEndpoints(ctx context.Context, ns, n string Name: autoscalerPortName, Port: autoscalerPort, Protocol: corev1.ProtocolTCP, - }}}, - } + }}, + }} exists := true var lastErr error diff --git a/pkg/autoscaler/statserver/server.go b/pkg/autoscaler/statserver/server.go index 18a90c1e3633..24d2255df999 100644 --- a/pkg/autoscaler/statserver/server.go +++ b/pkg/autoscaler/statserver/server.go @@ -70,7 +70,7 @@ func New(statsServerAddr string, statsCh chan<- metrics.StatMessage, logger *zap Addr: statsServerAddr, Handler: mux, ConnState: svr.onConnStateChange, - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 } return &svr } diff --git a/pkg/client/certmanager/testing/factory.go b/pkg/client/certmanager/testing/factory.go index 92fef2787459..10d673671a95 100644 --- a/pkg/client/certmanager/testing/factory.go +++ b/pkg/client/certmanager/testing/factory.go @@ -42,7 +42,8 @@ type Ctor func(context.Context, *Listers, configmap.Watcher) controller.Reconcil // MakeFactory creates a reconciler factory with fake clients and controller created by `ctor`. func MakeFactory(ctor Ctor) rtesting.Factory { return func(t *testing.T, r *rtesting.TableRow) ( - controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList) { + controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList, + ) { ls := NewListers(r.Objects) ctx := r.Ctx diff --git a/pkg/http/handler/timeout.go b/pkg/http/handler/timeout.go index f864a07fb268..2391e2862d59 100644 --- a/pkg/http/handler/timeout.go +++ b/pkg/http/handler/timeout.go @@ -163,8 +163,10 @@ type timeoutWriter struct { lastWriteTime time.Time } -var _ http.Flusher = (*timeoutWriter)(nil) -var _ http.ResponseWriter = (*timeoutWriter)(nil) +var ( + _ http.Flusher = (*timeoutWriter)(nil) + _ http.ResponseWriter = (*timeoutWriter)(nil) +) // Unwrap returns the underlying writer func (tw *timeoutWriter) Unwrap() http.ResponseWriter { diff --git a/pkg/http/request_log.go b/pkg/http/request_log.go index 1a7bc362fff7..1803bb7e6e96 100644 --- a/pkg/http/request_log.go +++ b/pkg/http/request_log.go @@ -85,7 +85,8 @@ func RequestLogTemplateInputGetterFromRevision(rev *RequestLogRevision) RequestL // NewRequestLogHandler creates an http.Handler that logs request logs to an io.Writer. func NewRequestLogHandler(h http.Handler, w io.Writer, templateStr string, - inputGetter RequestLogTemplateInputGetter, enableProbeRequestLog bool) (*RequestLogHandler, error) { + inputGetter RequestLogTemplateInputGetter, enableProbeRequestLog bool, +) (*RequestLogHandler, error) { reqHandler := &RequestLogHandler{ handler: h, writer: w, diff --git a/pkg/metrics/tags.go b/pkg/metrics/tags.go index bfaa3020a0ed..ddece2c62577 100644 --- a/pkg/metrics/tags.go +++ b/pkg/metrics/tags.go @@ -28,11 +28,9 @@ import ( "go.opencensus.io/tag" ) -var ( - // contextCache stores the metrics recorder contexts in an LRU cache. - // Hashicorp LRU cache is synchronized. - contextCache *lru.Cache -) +// contextCache stores the metrics recorder contexts in an LRU cache. +// Hashicorp LRU cache is synchronized. +var contextCache *lru.Cache // This is a fairly arbitrary number but we want it to be higher than the // number of active revisions a single activator might be handling, to avoid diff --git a/pkg/queue/breaker.go b/pkg/queue/breaker.go index 50f68c3b4dda..918f57b743a5 100644 --- a/pkg/queue/breaker.go +++ b/pkg/queue/breaker.go @@ -24,10 +24,8 @@ import ( "sync/atomic" ) -var ( - // ErrRequestQueueFull indicates the breaker queue depth was exceeded. - ErrRequestQueueFull = errors.New("pending request queue full") -) +// ErrRequestQueueFull indicates the breaker queue depth was exceeded. +var ErrRequestQueueFull = errors.New("pending request queue full") // MaxBreakerCapacity is the largest valid value for the MaxConcurrency value of BreakerParams. // This is limited by the maximum size of a chan struct{} in the current implementation. diff --git a/pkg/queue/certificate/watcher_test.go b/pkg/queue/certificate/watcher_test.go index 6ecb94cd9f91..7b84cdaa31a9 100644 --- a/pkg/queue/certificate/watcher_test.go +++ b/pkg/queue/certificate/watcher_test.go @@ -136,11 +136,11 @@ func createAndSaveCertificate(san, dir string) error { Bytes: x509.MarshalPKCS1PrivateKey(pk), }) - if err := os.WriteFile(dir+"/"+certificates.CertName, caPEM.Bytes(), 0644); err != nil { + if err := os.WriteFile(dir+"/"+certificates.CertName, caPEM.Bytes(), 0o644); err != nil { return err } - return os.WriteFile(dir+"/"+certificates.PrivateKeyName, caPrivKeyPEM.Bytes(), 0644) + return os.WriteFile(dir+"/"+certificates.PrivateKeyName, caPrivKeyPEM.Bytes(), 0o644) } func getSAN(c *tls.Certificate) (string, error) { diff --git a/pkg/queue/health/handler.go b/pkg/queue/health/handler.go index cdcab8b05018..47737ca1439a 100644 --- a/pkg/queue/health/handler.go +++ b/pkg/queue/health/handler.go @@ -43,20 +43,23 @@ func ProbeHandler(prober func() bool, tracingEnabled bool) http.HandlerFunc { if ph != queue.Name { http.Error(w, badProbeTemplate+ph, http.StatusBadRequest) probeSpan.Annotate([]trace.Attribute{ - trace.StringAttribute("queueproxy.probe.error", badProbeTemplate+ph)}, "error") + trace.StringAttribute("queueproxy.probe.error", badProbeTemplate+ph), + }, "error") return } if prober == nil { http.Error(w, "no probe", http.StatusInternalServerError) probeSpan.Annotate([]trace.Attribute{ - trace.StringAttribute("queueproxy.probe.error", "no probe")}, "error") + trace.StringAttribute("queueproxy.probe.error", "no probe"), + }, "error") return } if !prober() { probeSpan.Annotate([]trace.Attribute{ - trace.StringAttribute("queueproxy.probe.error", "container not ready")}, "error") + trace.StringAttribute("queueproxy.probe.error", "container not ready"), + }, "error") w.WriteHeader(http.StatusServiceUnavailable) return } diff --git a/pkg/queue/health/probe.go b/pkg/queue/health/probe.go index 26b416007458..fa262777a5e1 100644 --- a/pkg/queue/health/probe.go +++ b/pkg/queue/health/probe.go @@ -251,7 +251,6 @@ func GRPCProbe(config GRPCProbeConfigOptions) error { addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(int(config.Port))) conn, err := grpc.NewClient(addr, opts...) - if err != nil { if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("failed to connect service %q within %v: %w", addr, config.Timeout, err) @@ -268,7 +267,6 @@ func GRPCProbe(config GRPCProbeConfigOptions) error { resp, err := client.Check(metadata.NewOutgoingContext(ctx, make(metadata.MD)), &grpchealth.HealthCheckRequest{ Service: ptr.StringValue(config.Service), }) - if err != nil { stat, ok := status.FromError(err) if ok { diff --git a/pkg/queue/readiness/probe_encoding_test.go b/pkg/queue/readiness/probe_encoding_test.go index 6f28823a1f60..c5204a392531 100644 --- a/pkg/queue/readiness/probe_encoding_test.go +++ b/pkg/queue/readiness/probe_encoding_test.go @@ -111,7 +111,6 @@ func TestEncodeSingleProbe(t *testing.T) { } jsonProbe, err := EncodeSingleProbe(probe) - if err != nil { t.Fatalf("Expected no errer, got: %#v", err) } @@ -143,7 +142,6 @@ func TestEncodeMultipleProbes(t *testing.T) { }} jsonProbe, err := EncodeMultipleProbes(probes) - if err != nil { t.Fatalf("Expected no errer, got: %#v", err) } diff --git a/pkg/queue/readiness/probe_test.go b/pkg/queue/readiness/probe_test.go index d42f5b98da4e..44a6eb4141d6 100644 --- a/pkg/queue/readiness/probe_test.go +++ b/pkg/queue/readiness/probe_test.go @@ -169,7 +169,8 @@ func TestExecHandler(t *testing.T) { ProbeHandler: corev1.ProbeHandler{ Exec: &corev1.ExecAction{ Command: []string{"echo", "hello"}, - }}, + }, + }, }}) if pb.ProbeContainer() { diff --git a/pkg/queue/request_metric.go b/pkg/queue/request_metric.go index 6f43a01bc3e8..2a0a4d84df39 100644 --- a/pkg/queue/request_metric.go +++ b/pkg/queue/request_metric.go @@ -74,7 +74,8 @@ type appRequestMetricsHandler struct { // NewRequestMetricsHandler creates an http.Handler that emits request metrics. func NewRequestMetricsHandler(next http.Handler, - ns, service, config, rev, pod string) (http.Handler, error) { + ns, service, config, rev, pod string, +) (http.Handler, error) { keys := []tag.Key{metrics.PodKey, metrics.ContainerKey, metrics.ResponseCodeKey, metrics.ResponseCodeClassKey, metrics.RouteTagKey} if err := pkgmetrics.RegisterResourceView( &view.View{ @@ -136,7 +137,8 @@ func (h *requestMetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request // NewAppRequestMetricsHandler creates an http.Handler that emits request metrics. func NewAppRequestMetricsHandler(next http.Handler, b *Breaker, - ns, service, config, rev, pod string) (http.Handler, error) { + ns, service, config, rev, pod string, +) (http.Handler, error) { keys := []tag.Key{metrics.PodKey, metrics.ContainerKey, metrics.ResponseCodeKey, metrics.ResponseCodeClassKey} if err := pkgmetrics.RegisterResourceView(&view.View{ Description: "The number of requests that are routed to user-container", diff --git a/pkg/queue/sharedmain/handlers.go b/pkg/queue/sharedmain/handlers.go index 91aebfc779f3..8f8b56d22611 100644 --- a/pkg/queue/sharedmain/handlers.go +++ b/pkg/queue/sharedmain/handlers.go @@ -55,11 +55,11 @@ func mainHandler( breaker := buildBreaker(logger, env) tracingEnabled := env.TracingConfigBackend != tracingconfig.None timeout := time.Duration(env.RevisionTimeoutSeconds) * time.Second - var responseStartTimeout = 0 * time.Second + responseStartTimeout := 0 * time.Second if env.RevisionResponseStartTimeoutSeconds != 0 { responseStartTimeout = time.Duration(env.RevisionResponseStartTimeoutSeconds) * time.Second } - var idleTimeout = 0 * time.Second + idleTimeout := 0 * time.Second if env.RevisionIdleTimeoutSeconds != 0 { idleTimeout = time.Duration(env.RevisionIdleTimeoutSeconds) * time.Second } diff --git a/pkg/queue/sharedmain/servers.go b/pkg/queue/sharedmain/servers.go index d8e1fe9a3486..8100e4e222ec 100644 --- a/pkg/queue/sharedmain/servers.go +++ b/pkg/queue/sharedmain/servers.go @@ -46,6 +46,6 @@ func metricsServer(reporter *queue.ProtobufStatsReporter) *http.Server { return &http.Server{ Addr: ":" + strconv.Itoa(networking.AutoscalingQueueMetricsPort), Handler: metricsMux, - ReadHeaderTimeout: time.Minute, //https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 + ReadHeaderTimeout: time.Minute, // https://medium.com/a-journey-with-go/go-understand-and-mitigate-slowloris-attack-711c1b1403f6 } } diff --git a/pkg/reconciler/accessor/networking/certificate.go b/pkg/reconciler/accessor/networking/certificate.go index 8f6a45e21259..ef072b6437cd 100644 --- a/pkg/reconciler/accessor/networking/certificate.go +++ b/pkg/reconciler/accessor/networking/certificate.go @@ -40,7 +40,8 @@ type CertificateAccessor interface { // ReconcileCertificate reconciles Certificate to the desired status. func ReconcileCertificate(ctx context.Context, owner kmeta.Accessor, desired *v1alpha1.Certificate, - certAccessor CertificateAccessor) (*v1alpha1.Certificate, error) { + certAccessor CertificateAccessor, +) (*v1alpha1.Certificate, error) { recorder := controller.GetEventRecorder(ctx) if recorder == nil { return nil, fmt.Errorf("recorder for reconciling Certificate %s/%s is not created", desired.Namespace, desired.Name) diff --git a/pkg/reconciler/autoscaling/hpa/hpa_test.go b/pkg/reconciler/autoscaling/hpa/hpa_test.go index 06d3c8813b81..bcbca4983a0e 100644 --- a/pkg/reconciler/autoscaling/hpa/hpa_test.go +++ b/pkg/reconciler/autoscaling/hpa/hpa_test.go @@ -490,6 +490,7 @@ func withScales(d, a int32) PodAutoscalerOption { pa.Status.DesiredScale, pa.Status.ActualScale = ptr.Int32(d), ptr.Int32(a) } } + func withHPAScaleStatus(d, a int32) hpaOption { return func(hpa *autoscalingv2.HorizontalPodAutoscaler) { hpa.Status.DesiredReplicas, hpa.Status.CurrentReplicas = d, a diff --git a/pkg/reconciler/autoscaling/kpa/kpa_test.go b/pkg/reconciler/autoscaling/kpa/kpa_test.go index f7edd35c9bc0..da2ee9ad4807 100644 --- a/pkg/reconciler/autoscaling/kpa/kpa_test.go +++ b/pkg/reconciler/autoscaling/kpa/kpa_test.go @@ -337,7 +337,8 @@ func TestReconcile(t *testing.T) { withScales(1, defaultScale), WithPAStatusService(testRevision), WithObservedGeneration(1)), defaultSKS, metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, }, { Name: "status update retry", Key: key, @@ -346,7 +347,8 @@ func TestReconcile(t *testing.T) { withScales(0, defaultScale)), defaultSKS, metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, WithReactors: []clientgotesting.ReactionFunc{ func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) { if retryAttempted || !action.Matches("update", "podautoscalers") || action.GetSubresource() != "status" { @@ -374,7 +376,8 @@ func TestReconcile(t *testing.T) { kpa(testNamespace, testRevision, WithTraffic, WithPAMetricsService(privateSvc), withScales(1, defaultScale), WithPAStatusService(testRevision), WithObservedGeneration(1)), sks(testNamespace, testRevision, WithDeployRef(deployName), WithSKSReady), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("create", "metrics"), }, @@ -394,7 +397,8 @@ func TestReconcile(t *testing.T) { withScales(1, defaultScale), WithPAStatusService(testRevision), WithObservedGeneration(1)), sks(testNamespace, testRevision, WithDeployRef(deployName), WithSKSReady), defaultDeployment, - metricWithDiffSvc(testNamespace, testRevision), defaultReady}, + metricWithDiffSvc(testNamespace, testRevision), defaultReady, + }, WithReactors: []clientgotesting.ReactionFunc{ InduceFailure("update", "metrics"), }, @@ -412,7 +416,8 @@ func TestReconcile(t *testing.T) { Objects: []runtime.Object{ kpa(testNamespace, testRevision, WithTraffic, markScaleTargetInitialized, withScales(1, defaultScale), WithPAStatusService(testRevision)), - defaultSKS, defaultDeployment, defaultReady}, + defaultSKS, defaultDeployment, defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, WithTraffic, markScaleTargetInitialized, withScales(1, defaultScale), WithPASKSReady, WithPAStatusService(testRevision), @@ -430,7 +435,8 @@ func TestReconcile(t *testing.T) { WithObservedGeneration(1)), defaultSKS, metric(testNamespace, testRevision), - deploy(testNamespace, testRevision), defaultReady}, + deploy(testNamespace, testRevision), defaultReady, + }, WantPatches: []clientgotesting.PatchActionImpl{{ ActionImpl: clientgotesting.ActionImpl{ Namespace: testNamespace, @@ -450,7 +456,8 @@ func TestReconcile(t *testing.T) { withScales(1, defaultScale), WithPAStatusService(testRevision), WithObservedGeneration(1)), defaultSKS, metric(testNamespace, testRevision), - deploy(testNamespace, testRevision), defaultReady}, + deploy(testNamespace, testRevision), defaultReady, + }, WantPatches: []clientgotesting.PatchActionImpl{{ ActionImpl: clientgotesting.ActionImpl{ Namespace: testNamespace, @@ -491,7 +498,8 @@ func TestReconcile(t *testing.T) { sks(testNamespace, testRevision, WithDeployRef(deployName), WithPubService, WithPrivateService, WithNumActivators(scaledAct)), metric(testNamespace, testRevision), - defaultDeployment}, + defaultDeployment, + }, preciseReady...), WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, withScales(defaultScale, defaultScale), @@ -521,7 +529,8 @@ func TestReconcile(t *testing.T) { WithReachabilityReachable, WithPAMetricsService(privateSvc)), defaultSKS, metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, WithPASKSReady, WithBufferedTraffic, withMinScale(2), WithPAMetricsService(privateSvc), @@ -537,7 +546,8 @@ func TestReconcile(t *testing.T) { defaultSKS, metric(testNamespace, testRevision), defaultDeployment, - defaultReady}, + defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, WithPASKSReady, WithBufferedTraffic, withMinScale(2), WithPAMetricsService(privateSvc), @@ -552,7 +562,8 @@ func TestReconcile(t *testing.T) { WithPAMetricsService(privateSvc), WithReachabilityUnreachable), defaultSKS, metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, WithPASKSReady, WithTraffic, markScaleTargetInitialized, withMinScale(2), WithPAMetricsService(privateSvc), @@ -747,7 +758,8 @@ func TestReconcile(t *testing.T) { withScales(0, 0), WithPAStatusService(testRevision), WithPAMetricsService(privateSvc)), defaultSKS, metric(testNamespace, testRevision), - deploy(testNamespace, testRevision), defaultReady}, + deploy(testNamespace, testRevision), defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, markScaleTargetInitialized, withScales(1, 0), WithPASKSReady, WithPAMetricsService(privateSvc), @@ -769,7 +781,8 @@ func TestReconcile(t *testing.T) { WithPAStatusService(testRevision), WithPAMetricsService(privateSvc), WithObservedGeneration(1)), defaultSKS, metric(testNamespace, testRevision), - deploy(testNamespace, testRevision), defaultReady}, + deploy(testNamespace, testRevision), defaultReady, + }, }, { Name: "activation failure", Key: key, @@ -781,7 +794,8 @@ func TestReconcile(t *testing.T) { WithPAMetricsService(privateSvc)), defaultSKS, metric(testNamespace, testRevision), - deploy(testNamespace, testRevision), defaultReady}, + deploy(testNamespace, testRevision), defaultReady, + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: kpa(testNamespace, testRevision, markScaleTargetInitialized, WithPASKSReady, WithPAMetricsService(privateSvc), WithNoTraffic("TimedOut", "The target could not be activated."), withScales(1, 0), @@ -958,7 +972,8 @@ func TestReconcile(t *testing.T) { withScales(1, defaultScale), WithPAStatusService(testRevision), WithObservedGeneration(1)), defaultProxySKS, metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, }, { Name: "traffic increased, no longer enough burst capacity", Key: key, @@ -972,7 +987,8 @@ func TestReconcile(t *testing.T) { sks(testNamespace, testRevision, WithDeployRef(deployName), WithSKSReady, WithNumActivators(2)), metric(testNamespace, testRevision), - defaultDeployment, defaultReady}, + defaultDeployment, defaultReady, + }, WantUpdates: []clientgotesting.UpdateActionImpl{{ Object: sks(testNamespace, testRevision, WithSKSReady, WithDeployRef(deployName), WithProxyMode, WithNumActivators(minActivators+1)), @@ -990,7 +1006,8 @@ func TestReconcile(t *testing.T) { defaultProxySKS, metric(testNamespace, testRevision), defaultDeployment, - defaultReady}, + defaultReady, + }, WantUpdates: []clientgotesting.UpdateActionImpl{{ Object: defaultSKS, }}, @@ -1152,7 +1169,8 @@ func TestReconcile(t *testing.T) { defaultProxySKS, metric(testNamespace, testRevision), defaultDeployment, - defaultReady}, + defaultReady, + }, // No update from ProxySKS. }, { Name: "we have enough burst capacity, but switch to keep proxy mode as activator CA is turned on", @@ -1167,7 +1185,8 @@ func TestReconcile(t *testing.T) { defaultSKS, metric(testNamespace, testRevision), defaultDeployment, - defaultReady}, + defaultReady, + }, WantUpdates: []clientgotesting.UpdateActionImpl{{ Object: defaultProxySKS, }}, diff --git a/pkg/reconciler/autoscaling/kpa/scaler.go b/pkg/reconciler/autoscaling/kpa/scaler.go index 80fd7a5d7786..daafcf746cbb 100644 --- a/pkg/reconciler/autoscaling/kpa/scaler.go +++ b/pkg/reconciler/autoscaling/kpa/scaler.go @@ -172,7 +172,8 @@ func durationMax(d1, d2 time.Duration) time.Duration { } func (ks *scaler) handleScaleToZero(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, - sks *netv1alpha1.ServerlessService, desiredScale int32) (int32, bool) { + sks *netv1alpha1.ServerlessService, desiredScale int32, +) (int32, bool) { if desiredScale != 0 { return desiredScale, true } @@ -298,7 +299,8 @@ func (ks *scaler) handleScaleToZero(ctx context.Context, pa *autoscalingv1alpha1 } func (ks *scaler) applyScale(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, desiredScale int32, - ps *autoscalingv1alpha1.PodScalable) error { + ps *autoscalingv1alpha1.PodScalable, +) error { logger := logging.FromContext(ctx) gvr, name, err := resources.ScaleResourceArguments(pa.Spec.ScaleTargetRef) diff --git a/pkg/reconciler/autoscaling/kpa/scaler_test.go b/pkg/reconciler/autoscaling/kpa/scaler_test.go index 55045c5bac19..732406a8022c 100644 --- a/pkg/reconciler/autoscaling/kpa/scaler_test.go +++ b/pkg/reconciler/autoscaling/kpa/scaler_test.go @@ -648,7 +648,6 @@ func TestDisableScaleToZero(t *testing.T) { conf.Autoscaler.EnableScaleToZero = false ctx = config.ToContext(ctx, conf) desiredScale, err := revisionScaler.scale(ctx, pa, nil /*sks doesn't matter in this test*/, test.scaleTo) - if err != nil { t.Error("Scale got an unexpected error:", err) } diff --git a/pkg/reconciler/autoscaling/reconciler.go b/pkg/reconciler/autoscaling/reconciler.go index f7ef707df89b..5e9b5735bdf0 100644 --- a/pkg/reconciler/autoscaling/reconciler.go +++ b/pkg/reconciler/autoscaling/reconciler.go @@ -46,7 +46,8 @@ type Base struct { // ReconcileSKS reconciles a ServerlessService based on the given PodAutoscaler. func (c *Base) ReconcileSKS(ctx context.Context, pa *autoscalingv1alpha1.PodAutoscaler, - mode nv1alpha1.ServerlessServiceOperationMode, numActivators int32) (*nv1alpha1.ServerlessService, error) { + mode nv1alpha1.ServerlessServiceOperationMode, numActivators int32, +) (*nv1alpha1.ServerlessService, error) { logger := logging.FromContext(ctx) sksName := anames.SKS(pa.Name) diff --git a/pkg/reconciler/certificate/certificate_test.go b/pkg/reconciler/certificate/certificate_test.go index 4c9cbe057bc3..aa6b9f0a4ffe 100644 --- a/pkg/reconciler/certificate/certificate_test.go +++ b/pkg/reconciler/certificate/certificate_test.go @@ -265,7 +265,8 @@ func TestReconcile(t *testing.T) { knCert("knCert", "foo"), cmCertWithStatus("knCert", "foo", correctDNSNames, []cmv1.CertificateCondition{{ Type: cmv1.CertificateConditionReady, - Status: cmmeta.ConditionTrue}}, nil), + Status: cmmeta.ConditionTrue, + }}, nil), nonHTTP01Issuer, }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ @@ -289,7 +290,8 @@ func TestReconcile(t *testing.T) { knCert("knCert", "foo"), cmCertWithStatus("knCert", "foo", correctDNSNames, []cmv1.CertificateCondition{{ Type: cmv1.CertificateConditionReady, - Status: cmmeta.ConditionUnknown}}, nil), + Status: cmmeta.ConditionUnknown, + }}, nil), nonHTTP01Issuer, }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ @@ -313,7 +315,8 @@ func TestReconcile(t *testing.T) { knCert("knCert", "foo"), cmCertWithStatus("knCert", "foo", correctDNSNames, []cmv1.CertificateCondition{{ Type: cmv1.CertificateConditionReady, - Status: cmmeta.ConditionFalse}}, nil), + Status: cmmeta.ConditionFalse, + }}, nil), nonHTTP01Issuer, }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ @@ -666,7 +669,8 @@ func TestReconcile_HTTP01Challenges(t *testing.T) { cmCertWithStatus("knCert", "foo", correctDNSNames, []cmv1.CertificateCondition{{ Type: cmv1.CertificateConditionReady, Status: cmmeta.ConditionFalse, - Reason: "InProgress"}}, nil), + Reason: "InProgress", + }}, nil), knCert("knCert", "foo"), http01Issuer, }, diff --git a/pkg/reconciler/certificate/resources/cert_manager_certificate.go b/pkg/reconciler/certificate/resources/cert_manager_certificate.go index 1706b740d8a9..a17240974022 100644 --- a/pkg/reconciler/certificate/resources/cert_manager_certificate.go +++ b/pkg/reconciler/certificate/resources/cert_manager_certificate.go @@ -177,7 +177,8 @@ func MakeCertManagerCertificate(cmConfig *config.CertManagerConfig, knCert *v1al SecretTemplate: &cmv1.CertificateSecretTemplate{ Labels: map[string]string{ networking.CertificateUIDLabelKey: string(knCert.GetUID()), - }}, + }, + }, }, } return cert, nil diff --git a/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go b/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go index 7bf0c4086a80..bb9c7760dea3 100644 --- a/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go +++ b/pkg/reconciler/certificate/resources/cert_manager_certificate_test.go @@ -423,7 +423,8 @@ func TestGetReadyCondition(t *testing.T) { Status: cmmeta.ConditionTrue, Reason: "ready", Message: "ready", - }}, { + }, + }, { name: "not ready", cmCertificate: makeTestCertificate(cmmeta.ConditionFalse, cmv1.CertificateConditionReady, "not ready", "not ready"), want: &cmv1.CertificateCondition{ @@ -431,7 +432,8 @@ func TestGetReadyCondition(t *testing.T) { Status: cmmeta.ConditionFalse, Reason: "not ready", Message: "not ready", - }}, { + }, + }, { name: "unknow", cmCertificate: makeTestCertificate(cmmeta.ConditionUnknown, cmv1.CertificateConditionReady, "unknown", "unknown"), want: &cmv1.CertificateCondition{ @@ -439,12 +441,12 @@ func TestGetReadyCondition(t *testing.T) { Status: cmmeta.ConditionUnknown, Reason: "unknown", Message: "unknown", - }}, { + }, + }, { name: "condition not ready", cmCertificate: makeTestCertificate(cmmeta.ConditionTrue, cmv1.CertificateConditionIssuing, "Renewing", "Renewing certificate"), want: nil, - }, - } + }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/pkg/reconciler/gc/gc.go b/pkg/reconciler/gc/gc.go index f0ba872800a4..169849fddf1c 100644 --- a/pkg/reconciler/gc/gc.go +++ b/pkg/reconciler/gc/gc.go @@ -40,7 +40,8 @@ func collect( ctx context.Context, client clientset.Interface, revisionLister listers.RevisionLister, - config *v1.Configuration) pkgreconciler.Event { + config *v1.Configuration, +) pkgreconciler.Event { cfg := configns.FromContext(ctx).RevisionGC logger := logging.FromContext(ctx) diff --git a/pkg/reconciler/gc/gc_test.go b/pkg/reconciler/gc/gc_test.go index d6ae5f579e08..1b1aa67d5d9f 100644 --- a/pkg/reconciler/gc/gc_test.go +++ b/pkg/reconciler/gc/gc_test.go @@ -523,7 +523,8 @@ func runTest( cfgMap *config.Config, revs []*v1.Revision, cfg *v1.Configuration, - wantDeletes []clientgotesting.DeleteActionImpl) { + wantDeletes []clientgotesting.DeleteActionImpl, +) { t.Helper() ctx, _ := SetupFakeContext(t) ctx = config.ToContext(ctx, cfgMap) diff --git a/pkg/reconciler/gc/reconciler_test.go b/pkg/reconciler/gc/reconciler_test.go index 5bf753b3243f..c23af14fbb71 100644 --- a/pkg/reconciler/gc/reconciler_test.go +++ b/pkg/reconciler/gc/reconciler_test.go @@ -62,7 +62,8 @@ func TestGCReconcile(t *testing.T) { MaxNonActiveRevisions: gc.Disabled, }, }, - }} + }, + } fc := clocktest.NewFakePassiveClock(time.Now()) table := TableTest{{ diff --git a/pkg/reconciler/labeler/accessors.go b/pkg/reconciler/labeler/accessors.go index 3320bfa6b2a4..dce202bb135c 100644 --- a/pkg/reconciler/labeler/accessors.go +++ b/pkg/reconciler/labeler/accessors.go @@ -62,7 +62,8 @@ func newRevisionAccessor( tracker tracker.Interface, lister listers.RevisionLister, indexer cache.Indexer, - clock clock.PassiveClock) *revisionAccessor { + clock clock.PassiveClock, +) *revisionAccessor { return &revisionAccessor{ client: client, tracker: tracker, @@ -74,7 +75,8 @@ func newRevisionAccessor( // makeMetadataPatch makes a metadata map to be patched or nil if no changes are needed. func makeMetadataPatch( - acc kmeta.Accessor, routeName string, addRoutingState, remove bool, clock clock.PassiveClock) (map[string]interface{}, error) { + acc kmeta.Accessor, routeName string, addRoutingState, remove bool, clock clock.PassiveClock, +) (map[string]interface{}, error) { labels := map[string]interface{}{} annotations := map[string]interface{}{} @@ -195,7 +197,8 @@ func newConfigurationAccessor( tracker tracker.Interface, lister listers.ConfigurationLister, indexer cache.Indexer, - clock clock.PassiveClock) *configurationAccessor { + clock clock.PassiveClock, +) *configurationAccessor { return &configurationAccessor{ client: client, tracker: tracker, diff --git a/pkg/reconciler/labeler/labeler.go b/pkg/reconciler/labeler/labeler.go index d1983c9f4de2..1c343e70f069 100644 --- a/pkg/reconciler/labeler/labeler.go +++ b/pkg/reconciler/labeler/labeler.go @@ -31,8 +31,10 @@ type Reconciler struct { } // Check that our Reconciler implements routereconciler.Interface -var _ routereconciler.Interface = (*Reconciler)(nil) -var _ routereconciler.Finalizer = (*Reconciler)(nil) +var ( + _ routereconciler.Interface = (*Reconciler)(nil) + _ routereconciler.Finalizer = (*Reconciler)(nil) +) // FinalizeKind removes all Route reference metadata from its traffic targets. // This does not modify or observe spec for the Route itself. diff --git a/pkg/reconciler/labeler/labeler_test.go b/pkg/reconciler/labeler/labeler_test.go index da0d82aee263..e9501e8a37c1 100644 --- a/pkg/reconciler/labeler/labeler_test.go +++ b/pkg/reconciler/labeler/labeler_test.go @@ -370,8 +370,10 @@ func revTraffic(name string, latest bool) v1.TrafficTarget { func routeWithTraffic(namespace, name string, spec, status v1.TrafficTarget, opts ...RouteOption) *v1.Route { return Route(namespace, name, - append([]RouteOption{WithSpecTraffic(spec), WithStatusTraffic(status), WithInitRouteConditions, - MarkTrafficAssigned, MarkCertificateReady, MarkIngressReady, WithRouteObservedGeneration}, opts...)...) + append([]RouteOption{ + WithSpecTraffic(spec), WithStatusTraffic(status), WithInitRouteConditions, + MarkTrafficAssigned, MarkCertificateReady, MarkIngressReady, WithRouteObservedGeneration, + }, opts...)...) } func simpleRunLatest(namespace, name, config string, opts ...RouteOption) *v1.Route { diff --git a/pkg/reconciler/nscert/nscert.go b/pkg/reconciler/nscert/nscert.go index 883781061f29..9d11b0b8485f 100644 --- a/pkg/reconciler/nscert/nscert.go +++ b/pkg/reconciler/nscert/nscert.go @@ -53,6 +53,8 @@ type reconciler struct { // Check that our Reconciler implements namespacereconciler.Interface var _ namespacereconciler.Interface = (*reconciler)(nil) + +// precompile domain template regexp var domainTemplateRegex = regexp.MustCompile(`^\*\..+$`) func certClass(ctx context.Context, r *corev1.Namespace) string { diff --git a/pkg/reconciler/nscert/nscert_test.go b/pkg/reconciler/nscert/nscert_test.go index c27c7f6f0798..ea084cdd2525 100644 --- a/pkg/reconciler/nscert/nscert_test.go +++ b/pkg/reconciler/nscert/nscert_test.go @@ -77,7 +77,8 @@ var ( ) func newTestSetup(t *testing.T, configs ...*corev1.ConfigMap) ( - context.Context, context.CancelFunc, chan *netv1alpha1.Certificate, *configmap.ManualWatcher) { + context.Context, context.CancelFunc, chan *netv1alpha1.Certificate, *configmap.ManualWatcher, +) { t.Helper() ctx, ccl, ifs := SetupFakeContextWithCancel(t) @@ -148,14 +149,16 @@ func newTestSetup(t *testing.T, configs ...*corev1.ConfigMap) ( func TestNewController(t *testing.T) { ctx, _ := SetupFakeContext(t) - configMapWatcher := configmap.NewStaticWatcher(&corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: netcfg.ConfigMapName, - Namespace: system.Namespace(), + configMapWatcher := configmap.NewStaticWatcher( + &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: netcfg.ConfigMapName, + Namespace: system.Namespace(), + }, + Data: map[string]string{ + "DomainTemplate": defaultDomainTemplate, + }, }, - Data: map[string]string{ - "DomainTemplate": defaultDomainTemplate, - }}, &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: routecfg.DomainConfigName, @@ -163,7 +166,8 @@ func TestNewController(t *testing.T) { }, Data: map[string]string{ "svc.cluster.local": "", - }}, + }, + }, ) c := NewController(ctx, configMapWatcher) @@ -232,7 +236,8 @@ func TestReconcile(t *testing.T) { Key: "excludeWildcard", Operator: "NotIn", Values: []string{"yes", "true", "anything"}, - }}}), + }}, + }), }, { Name: "certificate not created for excluded namespace when both internal and external labels are present", Key: "foo", @@ -247,7 +252,8 @@ func TestReconcile(t *testing.T) { Key: disableWildcardCertLabelKey, Operator: "NotIn", Values: []string{"true"}, - }}}), + }}, + }), }, { Name: "certificate creation failed", Key: "foo", @@ -291,7 +297,8 @@ func TestReconcile(t *testing.T) { Key: disableWildcardCertLabelKey, Operator: "NotIn", Values: []string{"true"}, - }}}), + }}, + }), }} table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler { diff --git a/pkg/reconciler/revision/cruds.go b/pkg/reconciler/revision/cruds.go index 0943b3cbc998..a8eb1852adc3 100644 --- a/pkg/reconciler/revision/cruds.go +++ b/pkg/reconciler/revision/cruds.go @@ -38,7 +38,6 @@ func (c *Reconciler) createDeployment(ctx context.Context, rev *v1.Revision) (*a cfgs := config.FromContext(ctx) deployment, err := resources.MakeDeployment(rev, cfgs) - if err != nil { return nil, fmt.Errorf("failed to make deployment: %w", err) } diff --git a/pkg/reconciler/revision/resolve.go b/pkg/reconciler/revision/resolve.go index 458e3c8398de..dc967a00a09d 100644 --- a/pkg/reconciler/revision/resolve.go +++ b/pkg/reconciler/revision/resolve.go @@ -92,7 +92,8 @@ func (r *digestResolver) Resolve( ctx context.Context, image string, opt k8schain.Options, - registriesToSkip sets.Set[string]) (string, error) { + registriesToSkip sets.Set[string], +) (string, error) { kc, err := k8schain.New(ctx, r.client, opt) if err != nil { return "", fmt.Errorf("failed to initialize authentication: %w", err) diff --git a/pkg/reconciler/revision/resolve_test.go b/pkg/reconciler/revision/resolve_test.go index 0e63e57167aa..1b7f6e73be7c 100644 --- a/pkg/reconciler/revision/resolve_test.go +++ b/pkg/reconciler/revision/resolve_test.go @@ -503,6 +503,7 @@ func TestNewResolverTransport(t *testing.T) { }) } } + func TestNewResolverTransport_TLSMinVersion(t *testing.T) { cases := []struct { name string diff --git a/pkg/reconciler/revision/resources/deploy_test.go b/pkg/reconciler/revision/resources/deploy_test.go index b77ed06f638f..c3b6d4fd78e2 100644 --- a/pkg/reconciler/revision/resources/deploy_test.go +++ b/pkg/reconciler/revision/resources/deploy_test.go @@ -314,9 +314,11 @@ func refInt64(num int64) *int64 { return &num } -type containerOption func(*corev1.Container) -type podSpecOption func(*corev1.PodSpec) -type deploymentOption func(*appsv1.Deployment) +type ( + containerOption func(*corev1.Container) + podSpecOption func(*corev1.PodSpec) + deploymentOption func(*appsv1.Deployment) +) func container(container *corev1.Container, opts ...containerOption) corev1.Container { for _, option := range opts { @@ -365,7 +367,9 @@ func withTCPReadinessProbe(port int) *corev1.Probe { TCPSocket: &corev1.TCPSocketAction{ Host: "127.0.0.1", Port: intstr.FromInt(port), - }}} + }, + }, + } } func withHTTPReadinessProbe(port int) *corev1.Probe { @@ -375,7 +379,8 @@ func withHTTPReadinessProbe(port int) *corev1.Probe { Port: intstr.FromInt(port), Path: "/", }, - }} + }, + } } func withGRPCReadinessProbe(port int) *corev1.Probe { @@ -384,7 +389,8 @@ func withGRPCReadinessProbe(port int) *corev1.Probe { GRPC: &corev1.GRPCAction{ Port: int32(port), }, - }} + }, + } } func withExecReadinessProbe(command []string) *corev1.Probe { @@ -393,7 +399,8 @@ func withExecReadinessProbe(command []string) *corev1.Probe { Exec: &corev1.ExecAction{ Command: command, }, - }} + }, + } } func withLivenessProbe(handler corev1.ProbeHandler) containerOption { @@ -490,6 +497,7 @@ func WithRevisionAnnotations(annotations map[string]string) RevisionOption { revision.Annotations = kmeta.UnionMaps(revision.Annotations, annotations) } } + func withContainerConcurrency(cc int64) RevisionOption { return func(revision *v1.Revision) { revision.Spec.ContainerConcurrency = &cc @@ -610,7 +618,8 @@ func TestMakePodSpec(t *testing.T) { queueContainer( withEnvVar("USER_PORT", "8888"), withEnvVar("SERVING_READINESS_PROBE", `{"tcpSocket":{"port":8888,"host":"127.0.0.1"}}`), - )}), + ), + }), }, { name: "volumes passed through", rev: revision("bar", "foo", @@ -1067,7 +1076,9 @@ func TestMakePodSpec(t *testing.T) { LivenessProbe: &corev1.Probe{ ProbeHandler: corev1.ProbeHandler{ TCPSocket: &corev1.TCPSocketAction{}, - }}}}, + }, + }, + }}, ), WithContainerStatuses([]v1.ContainerStatus{{ ImageDigest: "busybox@sha256:deadbeef", @@ -1130,7 +1141,9 @@ func TestMakePodSpec(t *testing.T) { StartupProbe: &corev1.Probe{ ProbeHandler: corev1.ProbeHandler{ TCPSocket: &corev1.TCPSocketAction{}, - }}}}, + }, + }, + }}, ), WithContainerStatuses([]v1.ContainerStatus{{ ImageDigest: "busybox@sha256:deadbeef", @@ -1179,7 +1192,8 @@ func TestMakePodSpec(t *testing.T) { ), queueContainer( withEnvVar("SERVING_SERVICE", "svc"), - )}), + ), + }), }, { name: "complex pod spec for multiple containers with container data to all containers", rev: revision("bar", "foo", diff --git a/pkg/reconciler/revision/resources/pa_test.go b/pkg/reconciler/revision/resources/pa_test.go index cb4e101acbb1..069b0606b19a 100644 --- a/pkg/reconciler/revision/resources/pa_test.go +++ b/pkg/reconciler/revision/resources/pa_test.go @@ -139,7 +139,8 @@ func TestMakePA(t *testing.T) { }, ProtocolType: networking.ProtocolH2C, Reachability: autoscalingv1alpha1.ReachabilityUnreachable, - }}, + }, + }, }, { name: "unknown routing state", rev: &v1.Revision{ @@ -189,7 +190,8 @@ func TestMakePA(t *testing.T) { ProtocolType: networking.ProtocolH2C, // When the Revision has failed, we mark the PA as unreachable. Reachability: autoscalingv1alpha1.ReachabilityUnknown, - }}, + }, + }, }, { name: "pending routing state", rev: &v1.Revision{ @@ -242,7 +244,8 @@ func TestMakePA(t *testing.T) { ProtocolType: networking.ProtocolH2C, // When the Revision has failed, we mark the PA as unreachable. Reachability: autoscalingv1alpha1.ReachabilityUnknown, - }}, + }, + }, }, { name: "failed deployment", dep: &appsv1.Deployment{ diff --git a/pkg/reconciler/revision/resources/queue_test.go b/pkg/reconciler/revision/resources/queue_test.go index eedd6370a82a..fe29518e63fd 100644 --- a/pkg/reconciler/revision/resources/queue_test.go +++ b/pkg/reconciler/revision/resources/queue_test.go @@ -506,8 +506,8 @@ func TestMakeQueueContainerWithPercentageAnnotation(t *testing.T) { corev1.ResourceMemory: resource.MustParse("2Gi"), corev1.ResourceCPU: resource.MustParse("2"), }, - }}, - } + }, + }} }), want: queueContainer(func(c *corev1.Container) { c.Env = env(map[string]string{}) @@ -697,8 +697,8 @@ func TestMakeQueueContainerWithResourceAnnotations(t *testing.T) { corev1.ResourceMemory: resource.MustParse("2Gi"), corev1.ResourceCPU: resource.MustParse("2"), }, - }}, - } + }, + }} }), want: queueContainer(func(c *corev1.Container) { c.Env = env(map[string]string{}) diff --git a/pkg/reconciler/revision/resources/resourceboundary_test.go b/pkg/reconciler/revision/resources/resourceboundary_test.go index 0384a2110423..6cd33bd4e3b3 100644 --- a/pkg/reconciler/revision/resources/resourceboundary_test.go +++ b/pkg/reconciler/revision/resources/resourceboundary_test.go @@ -38,13 +38,12 @@ func TestResourceBoundary(t *testing.T) { boundary: queueContainerRequestCPU, resource: resource.MustParse("15m"), want: resource.MustParse("25m"), - }, - { - name: "resource lower than min boundary", - boundary: queueContainerRequestCPU, - resource: resource.MustParse("110m"), - want: resource.MustParse("100m"), - }} + }, { + name: "resource lower than min boundary", + boundary: queueContainerRequestCPU, + resource: resource.MustParse("110m"), + want: resource.MustParse("100m"), + }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/pkg/reconciler/revision/revision_test.go b/pkg/reconciler/revision/revision_test.go index d6572093b219..622e1f8cd138 100644 --- a/pkg/reconciler/revision/revision_test.go +++ b/pkg/reconciler/revision/revision_test.go @@ -83,7 +83,8 @@ func newTestController(t *testing.T, configs []*corev1.ConfigMap, opts ...reconc context.CancelFunc, []controller.Informer, *controller.Impl, - *configmap.ManualWatcher) { + *configmap.ManualWatcher, +) { ctx, cancel, informers := SetupFakeContextWithCancel(t) t.Cleanup(cancel) // cancel is reentrant, so if necessary callers can call it directly, if needed. configMapWatcher := &configmap.ManualWatcher{Namespace: system.Namespace()} @@ -399,16 +400,18 @@ func TestResolutionFailed(t *testing.T) { } func TestUpdateRevWithWithUpdatedLoggingURL(t *testing.T) { - ctx, _, _, controller, watcher := newTestController(t, []*corev1.ConfigMap{{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: system.Namespace(), - Name: metrics.ConfigMapName(), - }, - Data: map[string]string{ - "logging.enable-var-log-collection": "true", - "logging.revision-url-template": "http://old-logging.test.com?filter=${REVISION_UID}", + ctx, _, _, controller, watcher := newTestController(t, []*corev1.ConfigMap{ + testDeploymentCM(), + { + ObjectMeta: metav1.ObjectMeta{ + Namespace: system.Namespace(), + Name: metrics.ConfigMapName(), + }, + Data: map[string]string{ + "logging.enable-var-log-collection": "true", + "logging.revision-url-template": "http://old-logging.test.com?filter=${REVISION_UID}", + }, }, - }, testDeploymentCM(), }) revClient := fakeservingclient.Get(ctx).ServingV1().Revisions(testNamespace) diff --git a/pkg/reconciler/revision/table_test.go b/pkg/reconciler/revision/table_test.go index d390938b362e..57f020700096 100644 --- a/pkg/reconciler/revision/table_test.go +++ b/pkg/reconciler/revision/table_test.go @@ -708,7 +708,8 @@ func TestReconcile(t *testing.T) { // The first reconciliation of a Revision creates the following resources. pa("foo", "first-reconcile"), deploy(t, "foo", "first-reconcile", WithRevisionInitContainers()), - image("foo", "first-reconcile")}, + image("foo", "first-reconcile"), + }, imageInit("foo", "first-reconcile")...), WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: Revision("foo", "first-reconcile", WithRevisionInitContainers(), @@ -730,7 +731,8 @@ func TestReconcile(t *testing.T) { // The first reconciliation of a Revision creates the following resources. pa("foo", "first-reconcile"), deploy(t, "foo", "first-reconcile", WithRevisionPVC()), - image("foo", "first-reconcile")}, + image("foo", "first-reconcile"), + }, WantStatusUpdates: []clientgotesting.UpdateActionImpl{{ Object: Revision("foo", "first-reconcile", // The first reconciliation Populates the following status properties. diff --git a/pkg/reconciler/route/config/domain.go b/pkg/reconciler/route/config/domain.go index 134d75ceba2f..6154a0a0e9e6 100644 --- a/pkg/reconciler/route/config/domain.go +++ b/pkg/reconciler/route/config/domain.go @@ -35,11 +35,9 @@ const ( DomainTypeWildcard = "wildcard" ) -var ( - // DefaultDomain holds the domain that Route's live under by default - // when no label selector-based options apply. - DefaultDomain = "svc." + network.GetClusterDomainName() -) +// DefaultDomain holds the domain that Route's live under by default +// when no label selector-based options apply. +var DefaultDomain = "svc." + network.GetClusterDomainName() // LabelSelector represents map of {key,value} pairs. A single {key,value} in the // map is equivalent to a requirement key == value. The requirements are ANDed. diff --git a/pkg/reconciler/route/domains/domains.go b/pkg/reconciler/route/domains/domains.go index 0a3c63412a9b..50cce3e561f6 100644 --- a/pkg/reconciler/route/domains/domains.go +++ b/pkg/reconciler/route/domains/domains.go @@ -43,9 +43,7 @@ import ( // HTTPScheme is the string representation of http. const HTTPScheme string = "http" -var ( - ErrDomainName = errors.New("domain name error") -) +var ErrDomainName = errors.New("domain name error") // GetAllDomainsAndTags returns all of the domains and tags(including subdomains) associated with a Route func GetAllDomainsAndTags(ctx context.Context, r *v1.Route, names []string, visibility map[string]netv1alpha1.IngressVisibility) (map[string]string, error) { diff --git a/pkg/reconciler/route/reconcile_resources.go b/pkg/reconciler/route/reconcile_resources.go index 2fb29b6415cf..41799c237515 100644 --- a/pkg/reconciler/route/reconcile_resources.go +++ b/pkg/reconciler/route/reconcile_resources.go @@ -118,7 +118,6 @@ func (c *Reconciler) deleteOrphanedServices(ctx context.Context, r *v1.Route, ac routeLabelSelector := labels.SelectorFromSet(labels.Set{serving.RouteLabelKey: r.Name}) allServices, err := c.serviceLister.Services(ns).List(routeLabelSelector) - if err != nil { return fmt.Errorf("failed to fetch existing services: %w", err) } @@ -326,7 +325,8 @@ func deserializeRollout(ctx context.Context, ro string) *traffic.Rollout { func (c *Reconciler) reconcileRollout( ctx context.Context, r *v1.Route, tc *traffic.Config, - ingress *netv1alpha1.Ingress) *traffic.Rollout { + ingress *netv1alpha1.Ingress, +) *traffic.Rollout { cfg := config.FromContext(ctx) // Is there rollout duration specified? diff --git a/pkg/reconciler/route/reconcile_resources_test.go b/pkg/reconciler/route/reconcile_resources_test.go index 3ad86c76cd59..9628476c1b7f 100644 --- a/pkg/reconciler/route/reconcile_resources_test.go +++ b/pkg/reconciler/route/reconcile_resources_test.go @@ -551,7 +551,8 @@ func newTestRevision(namespace, name string) *v1.Revision { } func testIngressParams(t *testing.T, r *v1.Route, trafficOpts ...func(tc *traffic.Config)) (*traffic.Config, - []netv1alpha1.IngressTLS) { + []netv1alpha1.IngressTLS, +) { tc := &traffic.Config{ Targets: map[string]traffic.RevisionTargets{ traffic.DefaultTarget: {{ diff --git a/pkg/reconciler/route/resources/certificate_test.go b/pkg/reconciler/route/resources/certificate_test.go index 8bb5c81d0c2b..0e963ea65175 100644 --- a/pkg/reconciler/route/resources/certificate_test.go +++ b/pkg/reconciler/route/resources/certificate_test.go @@ -92,7 +92,7 @@ func TestMakeCertificates(t *testing.T) { } func TestMakeCertificates_FilterLastAppliedAnno(t *testing.T) { - var orgRoute = Route("default", "route", WithRouteUID("12345"), WithRouteLabel(map[string]string{"label-from-route": "foo", serving.RouteLabelKey: "foo"}), + orgRoute := Route("default", "route", WithRouteUID("12345"), WithRouteLabel(map[string]string{"label-from-route": "foo", serving.RouteLabelKey: "foo"}), WithRouteAnnotation(map[string]string{corev1.LastAppliedConfigAnnotation: "something-last-applied", networking.CertificateClassAnnotationKey: "passdown-cert"})) want := []*netv1alpha1.Certificate{ { diff --git a/pkg/reconciler/route/resources/ingress.go b/pkg/reconciler/route/resources/ingress.go index 2f7f7a60d2a4..ff8d2dc81da5 100644 --- a/pkg/reconciler/route/resources/ingress.go +++ b/pkg/reconciler/route/resources/ingress.go @@ -233,7 +233,8 @@ func makeIngressRule(domains sets.Set[string], ns string, visibility netv1alpha1.IngressVisibility, targets traffic.RevisionTargets, roCfgs []*traffic.ConfigurationRollout, - encryption bool) netv1alpha1.IngressRule { + encryption bool, +) netv1alpha1.IngressRule { return netv1alpha1.IngressRule{ Hosts: sets.List(domains), Visibility: visibility, @@ -270,7 +271,8 @@ func rolloutConfig(cfgName string, ros []*traffic.ConfigurationRollout) *traffic } func makeBaseIngressPath(ns string, targets traffic.RevisionTargets, - roCfgs []*traffic.ConfigurationRollout, encryption bool) *netv1alpha1.HTTPIngressPath { + roCfgs []*traffic.ConfigurationRollout, encryption bool, +) *netv1alpha1.HTTPIngressPath { // Optimistically allocate |targets| elements. splits := make([]netv1alpha1.IngressBackendSplit, 0, len(targets)) for _, t := range targets { diff --git a/pkg/reconciler/route/resources/ingress_test.go b/pkg/reconciler/route/resources/ingress_test.go index 6555d44ba45e..a8027008f04e 100644 --- a/pkg/reconciler/route/resources/ingress_test.go +++ b/pkg/reconciler/route/resources/ingress_test.go @@ -1294,7 +1294,8 @@ func TestMakeIngressACMEChallenges(t *testing.T) { "Knative-Serving-Namespace": "test-ns", }, }}, - }}}, + }}, + }, }, { Hosts: []string{ "test-route.test-ns.example.com", @@ -1324,7 +1325,8 @@ func TestMakeIngressACMEChallenges(t *testing.T) { "Knative-Serving-Namespace": "test-ns", }, }}, - }}}, + }}, + }, }} tc := &traffic.Config{ diff --git a/pkg/reconciler/route/route_test.go b/pkg/reconciler/route/route_test.go index 9a3993669364..1f243f55106e 100644 --- a/pkg/reconciler/route/route_test.go +++ b/pkg/reconciler/route/route_test.go @@ -99,7 +99,8 @@ func newTestSetup(t *testing.T, opts ...reconcilerOption) ( informers []controller.Informer, ctrl *controller.Impl, configMapWatcher *configmap.ManualWatcher, - cf context.CancelFunc) { + cf context.CancelFunc, +) { ctx, cf, informers = SetupFakeContextWithCancel(t) configMapWatcher = &configmap.ManualWatcher{Namespace: system.Namespace()} ctrl = newController(ctx, configMapWatcher, &clock.RealClock{}, opts...) @@ -1708,8 +1709,7 @@ func TestCreateRouteWithClusterLocalDomainTLSEnabled(t *testing.T) { Hosts: hosts, SecretName: "route--local", SecretNamespace: testNamespace, - }, - }, + }}, Rules: []v1alpha1.IngressRule{{ Hosts: hosts, Visibility: v1alpha1.IngressVisibilityClusterLocal, diff --git a/pkg/reconciler/route/table_test.go b/pkg/reconciler/route/table_test.go index 15dd77ae9f49..d9abd322cefb 100644 --- a/pkg/reconciler/route/table_test.go +++ b/pkg/reconciler/route/table_test.go @@ -65,9 +65,7 @@ import ( const testIngressClass = "ingress-class-foo" -var ( - fakeCurTime = time.Unix(1e9, 0) -) +var fakeCurTime = time.Unix(1e9, 0) type key int @@ -3660,7 +3658,8 @@ func url(s string) *apis.URL { type rolloutOption func(*traffic.Rollout) func simpleRollout(cfg string, revs []traffic.RevisionRollout, - now time.Time, ros ...rolloutOption) IngressOption { + now time.Time, ros ...rolloutOption, +) IngressOption { return func(i *netv1alpha1.Ingress) { r := &traffic.Rollout{ Configurations: []*traffic.ConfigurationRollout{{ diff --git a/pkg/reconciler/route/traffic/traffic.go b/pkg/reconciler/route/traffic/traffic.go index bd24754f1562..13a187402551 100644 --- a/pkg/reconciler/route/traffic/traffic.go +++ b/pkg/reconciler/route/traffic/traffic.go @@ -79,7 +79,8 @@ type Config struct { // // In the case that some target is missing, an error of type TargetError will be returned. func BuildTrafficConfiguration(configLister listers.ConfigurationLister, revLister listers.RevisionLister, - r *v1.Route) (*Config, error) { + r *v1.Route, +) (*Config, error) { return newBuilder(configLister, revLister, r).build() } @@ -118,7 +119,8 @@ func (cfg *Config) computeURL(ctx context.Context, r *v1.Route, tt *RevisionTarg } func (cfg *Config) targetToStatus(ctx context.Context, r *v1.Route, tt *RevisionTarget, - revs []RevisionRollout, results []v1.TrafficTarget) (_ []v1.TrafficTarget, err error) { + revs []RevisionRollout, results []v1.TrafficTarget, +) (_ []v1.TrafficTarget, err error) { var url *apis.URL // Do this once per tag. if tt.Tag != "" { @@ -207,7 +209,8 @@ type configBuilder struct { func newBuilder( configLister listers.ConfigurationLister, revLister listers.RevisionLister, - r *v1.Route) *configBuilder { + r *v1.Route, +) *configBuilder { return &configBuilder{ configLister: configLister.Configurations(r.Namespace), revLister: revLister.Revisions(r.Namespace), diff --git a/pkg/reconciler/route/traffic/traffic_test.go b/pkg/reconciler/route/traffic/traffic_test.go index 2ebcf948ae60..b6aecc8016cc 100644 --- a/pkg/reconciler/route/traffic/traffic_test.go +++ b/pkg/reconciler/route/traffic/traffic_test.go @@ -601,6 +601,7 @@ func TestBuildTrafficConfigThreeConfigs(t *testing.T) { t.Errorf("Rollout mismatch, diff(-want,+got):\n%s", cmp.Diff(wantR, gotR)) } } + func TestBuildTrafficConfigurationTwoEntriesSameConfigDifferentTags(t *testing.T) { expected := &Config{ Targets: map[string]RevisionTargets{ @@ -1364,7 +1365,8 @@ func (l revFakeErrorLister) Revisions(namespace string) listers.RevisionNamespac func TestBuildTrafficConfigurationFailedGetRevision(t *testing.T) { _, err := BuildTrafficConfiguration(configLister, revErrorLister, testRouteWithTrafficTargets(WithSpecTraffic(v1.TrafficTarget{ RevisionName: goodNewRev.Name, - Percent: ptr.Int64(50)}))) + Percent: ptr.Int64(50), + }))) if err != nil && err.Error() != errAPI.Error() { t.Errorf("err: %v, want: %v", err.Error(), errAPI.Error()) } else if err == nil { diff --git a/pkg/reconciler/service/service.go b/pkg/reconciler/service/service.go index d74a3ac6bf95..d1cffe4f3627 100644 --- a/pkg/reconciler/service/service.go +++ b/pkg/reconciler/service/service.go @@ -55,7 +55,8 @@ type Reconciler struct { // NewReconciler creates the reference to the Reconciler based on clientset.Interface, listers.ConfigurationLister, // listers.RevisionLister and listers.RouteLister. func NewReconciler(client clientset.Interface, configurationLister listers.ConfigurationLister, - revisionLister listers.RevisionLister, routeLister listers.RouteLister) *Reconciler { + revisionLister listers.RevisionLister, routeLister listers.RouteLister, +) *Reconciler { return &Reconciler{ client: client, configurationLister: configurationLister, diff --git a/pkg/reconciler/service/service_test.go b/pkg/reconciler/service/service_test.go index 2863c4506f33..b5927f8a531e 100644 --- a/pkg/reconciler/service/service_test.go +++ b/pkg/reconciler/service/service_test.go @@ -341,8 +341,10 @@ func TestReconcile(t *testing.T) { WantUpdates: []clientgotesting.UpdateActionImpl{{ Object: config("update-route-and-config-labels", "foo", WithRunLatestRollout, WithConfigLabel("new-label", "new-value")), }, { - Object: route("update-route-and-config-labels", "foo", WithRunLatestRollout, WithRouteLabel(map[string]string{"new-label": "new-value", - "serving.knative.dev/service": "update-route-and-config-labels"})), + Object: route("update-route-and-config-labels", "foo", WithRunLatestRollout, WithRouteLabel(map[string]string{ + "new-label": "new-value", + "serving.knative.dev/service": "update-route-and-config-labels", + })), }}, }, { Name: "update route config labels ignoring serving.knative.dev/route", @@ -357,8 +359,10 @@ func TestReconcile(t *testing.T) { WantUpdates: []clientgotesting.UpdateActionImpl{{ Object: config("update-child-labels-ignore-route-label", "foo", WithRunLatestRollout, WithConfigLabel("new-label", "new-value")), }, { - Object: route("update-child-labels-ignore-route-label", "foo", WithRunLatestRollout, WithRouteLabel(map[string]string{"new-label": "new-value", - "serving.knative.dev/service": "update-child-labels-ignore-route-label"})), + Object: route("update-child-labels-ignore-route-label", "foo", WithRunLatestRollout, WithRouteLabel(map[string]string{ + "new-label": "new-value", + "serving.knative.dev/service": "update-child-labels-ignore-route-label", + })), }}, }, { Name: "bad configuration update", diff --git a/pkg/reconciler/testing/v1/factory.go b/pkg/reconciler/testing/v1/factory.go index ad51cdfdbbad..a5f22a3d6b62 100644 --- a/pkg/reconciler/testing/v1/factory.go +++ b/pkg/reconciler/testing/v1/factory.go @@ -57,7 +57,8 @@ type Ctor func(context.Context, *Listers, configmap.Watcher) controller.Reconcil // MakeFactory creates a reconciler factory with fake clients and controller created by `ctor`. func MakeFactory(ctor Ctor) rtesting.Factory { return func(t *testing.T, r *rtesting.TableRow) ( - controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList) { + controller.Reconciler, rtesting.ActionRecorderList, rtesting.EventList, + ) { ls := NewListers(r.Objects) ctx := r.Ctx diff --git a/pkg/testing/v1/revision.go b/pkg/testing/v1/revision.go index a3cd452fd9ef..a475bad0aa40 100644 --- a/pkg/testing/v1/revision.go +++ b/pkg/testing/v1/revision.go @@ -245,8 +245,8 @@ func WithRevisionPVC() RevisionOption { VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ ClaimName: "myclaim", ReadOnly: false, - }}}, - } + }}, + }} r.Spec.Containers[0].VolumeMounts = []corev1.VolumeMount{{ Name: "claimvolume", MountPath: "/data", diff --git a/pkg/testing/v1/service.go b/pkg/testing/v1/service.go index c84ea5298ac0..ddcfc8184ea5 100644 --- a/pkg/testing/v1/service.go +++ b/pkg/testing/v1/service.go @@ -502,21 +502,19 @@ func WithFailedConfig(name, reason, message string) ServiceOption { } } -var ( - // configSpec is the spec used for the different styles of Service rollout. - configSpec = v1.ConfigurationSpec{ - Template: v1.RevisionTemplateSpec{ - Spec: v1.RevisionSpec{ - TimeoutSeconds: ptr.Int64(60), - PodSpec: corev1.PodSpec{ - Containers: []corev1.Container{{ - Image: "busybox", - }}, - }, +// configSpec is the spec used for the different styles of Service rollout. +var configSpec = v1.ConfigurationSpec{ + Template: v1.RevisionTemplateSpec{ + Spec: v1.RevisionSpec{ + TimeoutSeconds: ptr.Int64(60), + PodSpec: corev1.PodSpec{ + Containers: []corev1.Container{{ + Image: "busybox", + }}, }, }, - } -) + }, +} // WithInitContainer adds init container to a service. func WithInitContainer(p corev1.Container) ServiceOption { diff --git a/pkg/webhook/validate_unstructured_test.go b/pkg/webhook/validate_unstructured_test.go index 11d64cc7d4fc..0fe36868266e 100644 --- a/pkg/webhook/validate_unstructured_test.go +++ b/pkg/webhook/validate_unstructured_test.go @@ -34,15 +34,13 @@ import ( v1 "knative.dev/serving/pkg/apis/serving/v1" ) -var ( - validMetadata = map[string]interface{}{ - "name": "valid", - "namespace": "foo", - "annotations": map[string]interface{}{ - config.DryRunFeatureKey: "enabled", - }, - } -) +var validMetadata = map[string]interface{}{ + "name": "valid", + "namespace": "foo", + "annotations": map[string]interface{}{ + config.DryRunFeatureKey: "enabled", + }, +} func TestUnstructuredValidation(t *testing.T) { tests := []struct { diff --git a/test/conformance/api/v1/configuration_test.go b/test/conformance/api/v1/configuration_test.go index 5d4fe9f8a8dd..fa3ddf3db852 100644 --- a/test/conformance/api/v1/configuration_test.go +++ b/test/conformance/api/v1/configuration_test.go @@ -60,7 +60,7 @@ func TestConfigurationGetAndList(t *testing.T) { if len(list.Items) < 1 { t.Fatal("Listing should return at least one Configuration") } - var configurationFound = false + configurationFound := false for _, configuration := range list.Items { t.Logf("Configuration Returned: %s", configuration.Name) if configuration.Name == config.Name { diff --git a/test/conformance/api/v1/errorcondition_test.go b/test/conformance/api/v1/errorcondition_test.go index 4202e3e90961..57c7adaf2212 100644 --- a/test/conformance/api/v1/errorcondition_test.go +++ b/test/conformance/api/v1/errorcondition_test.go @@ -80,7 +80,6 @@ func TestContainerErrorMsg(t *testing.T) { } return false, nil }) - if err != nil { t.Fatal("Failed to validate configuration state:", err) } diff --git a/test/conformance/api/v1/revision_test.go b/test/conformance/api/v1/revision_test.go index f875bbcb4532..3afc616d921a 100644 --- a/test/conformance/api/v1/revision_test.go +++ b/test/conformance/api/v1/revision_test.go @@ -55,7 +55,7 @@ func TestRevisionGetAndList(t *testing.T) { if err != nil { t.Fatal("Getting revisions failed") } - var revisionFound = false + revisionFound := false for _, revisionItem := range revisions.Items { t.Logf("Revision Returned: %s", revisionItem.Name) if revisionItem.Name == revision.Name { diff --git a/test/conformance/api/v1/revision_timeout_test.go b/test/conformance/api/v1/revision_timeout_test.go index 29e1bbf61eb8..8eedfba02871 100644 --- a/test/conformance/api/v1/revision_timeout_test.go +++ b/test/conformance/api/v1/revision_timeout_test.go @@ -38,7 +38,8 @@ import ( // sendRequest send a request to "endpoint", returns error if unexpected response code, nil otherwise. func sendRequest(t *testing.T, clients *test.Clients, endpoint *url.URL, - initialSleep, sleep time.Duration, expectedResponseCode int) error { + initialSleep, sleep time.Duration, expectedResponseCode int, +) error { client, err := pkgtest.NewSpoofingClient(context.Background(), clients.KubeClient, t.Logf, endpoint.Hostname(), test.ServingFlags.ResolvableDomain, test.AddRootCAtoTransport(context.Background(), t.Logf, clients, test.ServingFlags.HTTPS)) if err != nil { return fmt.Errorf("error creating Spoofing client: %w", err) diff --git a/test/conformance/api/v1/route_test.go b/test/conformance/api/v1/route_test.go index d1d823365350..9733f2f145a8 100644 --- a/test/conformance/api/v1/route_test.go +++ b/test/conformance/api/v1/route_test.go @@ -123,7 +123,7 @@ func TestRouteGetAndList(t *testing.T) { if err != nil { t.Fatal("Getting routes failed") } - var routeFound = false + routeFound := false for _, routeItem := range routes.Items { t.Logf("Route Returned: %s", routeItem.Name) if routeItem.Name == route.Name { diff --git a/test/conformance/api/v1/service_test.go b/test/conformance/api/v1/service_test.go index c9f7609fd54e..714977731764 100644 --- a/test/conformance/api/v1/service_test.go +++ b/test/conformance/api/v1/service_test.go @@ -71,7 +71,7 @@ func TestServiceCreateListAndDelete(t *testing.T) { if len(list.Items) < 1 { t.Fatal("Listing should return at least one Service") } - var serviceFound = false + serviceFound := false for _, service := range list.Items { t.Logf("Service Returned: %s", service.Name) if service.Name == names.Service { diff --git a/test/conformance/api/v1/util.go b/test/conformance/api/v1/util.go index dfa6c7d6416f..48fafabe1d71 100644 --- a/test/conformance/api/v1/util.go +++ b/test/conformance/api/v1/util.go @@ -56,7 +56,8 @@ func checkForExpectedResponses(ctx context.Context, t testing.TB, clients *test. } func validateDomains(t testing.TB, clients *test.Clients, serviceName string, - baseExpected []string, tagExpectationPairs []tagExpectation) error { + baseExpected []string, tagExpectationPairs []tagExpectation, +) error { service, err := clients.ServingClient.Services.Get(context.Background(), serviceName, metav1.GetOptions{}) if err != nil { return fmt.Errorf("could not query service traffic status: %w", err) diff --git a/test/conformance/api/v1/volumes_test.go b/test/conformance/api/v1/volumes_test.go index db3f541b50f6..4117b9238c7e 100644 --- a/test/conformance/api/v1/volumes_test.go +++ b/test/conformance/api/v1/volumes_test.go @@ -450,7 +450,7 @@ func TestProjectedServiceAccountToken(t *testing.T) { Path: tokenPath, }, }}, - DefaultMode: ptr.Int32(0444), // Ensure everybody can read the mounted files. + DefaultMode: ptr.Int32(0o444), // Ensure everybody can read the mounted files. }, }) withSubpath := func(svc *v1.Service) { diff --git a/test/conformance/runtime/cgroup_test.go b/test/conformance/runtime/cgroup_test.go index ff41d34acb07..5934473244f9 100644 --- a/test/conformance/runtime/cgroup_test.go +++ b/test/conformance/runtime/cgroup_test.go @@ -72,11 +72,12 @@ func TestMustHaveCgroupConfigured(t *testing.T) { // It's important to make sure that the memory limit is divisible by common page // size (4k, 8k, 16k, 64k) as some environments apply rounding to the closest page // size multiple, see https://github.com/kubernetes/kubernetes/issues/82230. - var expectedCgroupsV1 = map[string]string{ + expectedCgroupsV1 := map[string]string{ "/sys/fs/cgroup/memory/memory.limit_in_bytes": strconv.FormatInt(resources.Limits.Memory().Value()&^4095, 10), // floor() to 4K pages - "/sys/fs/cgroup/cpu/cpu.shares": strconv.FormatInt(resources.Requests.Cpu().MilliValue()*1024/1000, 10)} + "/sys/fs/cgroup/cpu/cpu.shares": strconv.FormatInt(resources.Requests.Cpu().MilliValue()*1024/1000, 10), + } - var expectedCgroupsV2 = map[string]string{ + expectedCgroupsV2 := map[string]string{ "/sys/fs/cgroup/memory.max": strconv.FormatInt(resources.Limits.Memory().Value()&^4095, 10), // floor() to 4K pages // Convert cgroup v1 cpu.shares value to cgroup v2 cpu.weight // https://github.com/kubernetes/enhancements/tree/master/keps/sig-node/2254-cgroup-v2#phase-1-convert-from-cgroups-v1-settings-to-v2 @@ -199,7 +200,8 @@ func createResources() corev1.ResourceRequirements { resources := corev1.ResourceRequirements{ Limits: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse(toMilliValue(cpuLimit)), - corev1.ResourceMemory: resource.MustParse(strconv.Itoa(memoryLimit) + "Mi")}, + corev1.ResourceMemory: resource.MustParse(strconv.Itoa(memoryLimit) + "Mi"), + }, Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse(toMilliValue(cpuRequest)), }, diff --git a/test/conformance/runtime/liveness_probe_test.go b/test/conformance/runtime/liveness_probe_test.go index 6ac0a0013a14..74cd379decd2 100644 --- a/test/conformance/runtime/liveness_probe_test.go +++ b/test/conformance/runtime/liveness_probe_test.go @@ -69,7 +69,6 @@ func TestLivenessWithFail(t *testing.T) { PeriodSeconds: 1, FailureThreshold: 3, })) - if err != nil { t.Fatalf("Failed to create initial Service: %v: %v", names.Service, err) } diff --git a/test/conformance/runtime/readiness_probe_test.go b/test/conformance/runtime/readiness_probe_test.go index 18a1558082f0..047e680500b7 100644 --- a/test/conformance/runtime/readiness_probe_test.go +++ b/test/conformance/runtime/readiness_probe_test.go @@ -60,7 +60,7 @@ func TestProbeRuntime(t *testing.T) { } clients := test.Setup(t) - var testCases = []struct { + testCases := []struct { // name of the test case, which will be inserted in names of routes, configurations, etc. // Use a short name here to avoid hitting the 63-character limit in names // (e.g., "service-to-service-call-svc-cluster-local-uagkdshh-frkml-service" is too long.) diff --git a/test/conformance/runtime/user_test.go b/test/conformance/runtime/user_test.go index bee39b553800..5d68a0a34a73 100644 --- a/test/conformance/runtime/user_test.go +++ b/test/conformance/runtime/user_test.go @@ -85,7 +85,6 @@ func TestShouldRunAsUserContainerDefault(t *testing.T) { t.Parallel() clients := test.Setup(t) _, ri, err := fetchRuntimeInfo(t, clients) - if err != nil { t.Fatal("Error fetching runtime info:", err) } diff --git a/test/conformance/runtime/util.go b/test/conformance/runtime/util.go index a65d77369a2d..fd3461215969 100644 --- a/test/conformance/runtime/util.go +++ b/test/conformance/runtime/util.go @@ -36,7 +36,8 @@ import ( func fetchRuntimeInfo( t *testing.T, clients *test.Clients, - opts ...interface{}) (*test.ResourceNames, *types.RuntimeInfo, error) { + opts ...interface{}, +) (*test.ResourceNames, *types.RuntimeInfo, error) { names := &test.ResourceNames{Image: test.Runtime} t.Helper() names.Service = test.ObjectNameForTest(t) diff --git a/test/e2e/autoscale.go b/test/e2e/autoscale.go index 930d75be905c..4421736d44d4 100644 --- a/test/e2e/autoscale.go +++ b/test/e2e/autoscale.go @@ -114,7 +114,8 @@ func generateTraffic( attacker *vegeta.Attacker, pacer vegeta.Pacer, stopChan chan struct{}, - target vegeta.Target) error { + target vegeta.Target, +) error { // The 0 duration means that the attack will only be controlled by the `Stop` function. results := attacker.Attack(vegeta.NewStaticTargeter(target), pacer, 0, "load-test") defer attacker.Stop() @@ -165,7 +166,6 @@ func newVegetaHTTPClient(ctx *TestContext, url *url.URL) *http.Client { test.AddRootCAtoTransport(context.Background(), ctx.t.Logf, ctx.Clients(), test.ServingFlags.HTTPS), vegetaTransportDefaults, ) - if err != nil { ctx.t.Fatal("Error creating spoofing client:", err) } diff --git a/test/e2e/autoscale_test.go b/test/e2e/autoscale_test.go index 5df556d3faf9..619e726080fa 100644 --- a/test/e2e/autoscale_test.go +++ b/test/e2e/autoscale_test.go @@ -298,7 +298,6 @@ func TestTargetBurstCapacityZero(t *testing.T) { test.ServingFlags.TestNamespace, time.Minute, ) - if err != nil { t.Error(err) } @@ -359,7 +358,8 @@ func TestActivationScale(t *testing.T) { Class: autoscaling.KPA, Metric: autoscaling.Concurrency, Target: 6, - TargetUtilization: 0.7}, + TargetUtilization: 0.7, + }, test.Options{}, rtesting.WithConfigAnnotations(map[string]string{ autoscaling.ActivationScaleKey: strconv.Itoa(activationScale), diff --git a/test/e2e/domainmapping/domain_mapping_test.go b/test/e2e/domainmapping/domain_mapping_test.go index 2469726510fe..767d5ee8a54a 100644 --- a/test/e2e/domainmapping/domain_mapping_test.go +++ b/test/e2e/domainmapping/domain_mapping_test.go @@ -90,7 +90,6 @@ func TestBYOCertificate(t *testing.T) { corev1.TLSPrivateKeyKey: key, }, }, metav1.CreateOptions{}) - if err != nil { t.Fatalf("Secret creation could not be completed: %v", err) } @@ -117,7 +116,8 @@ func TestBYOCertificate(t *testing.T) { }, TLS: &v1beta1.SecretTLS{ SecretName: secret.Name, - }}, + }, + }, Status: v1beta1.DomainMappingStatus{}, } diff --git a/test/e2e/egress_traffic_test.go b/test/e2e/egress_traffic_test.go index b68151bc6432..92129fda589c 100644 --- a/test/e2e/egress_traffic_test.go +++ b/test/e2e/egress_traffic_test.go @@ -51,7 +51,6 @@ func TestEgressTraffic(t *testing.T) { Name: targetHostEnvName, Value: targetHostDomain, })) - if err != nil { t.Fatal("Failed to create a service:", err) } diff --git a/test/e2e/externaldomaintls/auto_tls_test.go b/test/e2e/externaldomaintls/auto_tls_test.go index 5bec8823985f..1493ade7c7c7 100644 --- a/test/e2e/externaldomaintls/auto_tls_test.go +++ b/test/e2e/externaldomaintls/auto_tls_test.go @@ -190,7 +190,7 @@ func routeURLHTTP(route *servingv1.Route) (bool, error) { } func routeTLSDisabled(route *servingv1.Route) (bool, error) { - var cond = route.Status.GetCondition("CertificateProvisioned") + cond := route.Status.GetCondition("CertificateProvisioned") return cond.Status == "True" && cond.Reason == "TLSNotEnabled", nil } @@ -235,7 +235,8 @@ func createHTTPSClient(t *testing.T, clients *test.Clients, objects *v1test.Reso Transport: &http.Transport{ DialContext: dialer, TLSClientConfig: tlsConfig, - }} + }, + } } func createHTTPClient(t *testing.T, clients *test.Clients, objects *v1test.ResourceObjects) *http.Client { @@ -249,5 +250,6 @@ func createHTTPClient(t *testing.T, clients *test.Clients, objects *v1test.Resou Transport: &http.Transport{ DialContext: dialer, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }} + }, + } } diff --git a/test/e2e/externaldomaintls/util_test.go b/test/e2e/externaldomaintls/util_test.go index f80cb18229e9..660c791ab048 100644 --- a/test/e2e/externaldomaintls/util_test.go +++ b/test/e2e/externaldomaintls/util_test.go @@ -45,8 +45,10 @@ import ( "knative.dev/serving/test/types" ) -type RequestOption func(*http.Request) -type ResponseExpectation func(response *http.Response) error +type ( + RequestOption func(*http.Request) + ResponseExpectation func(response *http.Response) error +) func RuntimeRequest(ctx context.Context, t *testing.T, client *http.Client, url string, opts ...RequestOption) *types.RuntimeInfo { return RuntimeRequestWithExpectations(ctx, t, client, url, @@ -61,7 +63,8 @@ func RuntimeRequest(ctx context.Context, t *testing.T, client *http.Client, url func RuntimeRequestWithExpectations(ctx context.Context, t *testing.T, client *http.Client, url string, responseExpectations []ResponseExpectation, allowDialError bool, - opts ...RequestOption) *types.RuntimeInfo { + opts ...RequestOption, +) *types.RuntimeInfo { t.Helper() req, err := http.NewRequest(http.MethodGet, url, nil) @@ -75,7 +78,6 @@ func RuntimeRequestWithExpectations(ctx context.Context, t *testing.T, client *h } resp, err := client.Do(req) - if err != nil { if !allowDialError || !IsDialError(err) { t.Error("Error making GET request:", err) @@ -173,7 +175,7 @@ func CreateDialContext(ctx context.Context, t *testing.T, ing *v1alpha1.Ingress, t.Fatalf("Unable to retrieve Kubernetes service %s/%s: %v", namespace, name, err) } - var dialBackoff = wait.Backoff{ + dialBackoff := wait.Backoff{ Duration: 50 * time.Millisecond, Factor: 1.4, Jitter: 0.1, // At most 10% jitter. diff --git a/test/e2e/grpc_test.go b/test/e2e/grpc_test.go index 25a6d4118e50..270fd32c8988 100644 --- a/test/e2e/grpc_test.go +++ b/test/e2e/grpc_test.go @@ -206,7 +206,6 @@ func generateGRPCTraffic(ctx *TestContext, concurrentRequests int, host, domain default: want := fmt.Sprintf("Hello! stream:%d request: %d", i, j) got, err := pingGRPC(ctx, host, domain, want) - if err != nil { return fmt.Errorf("ping gRPC error: %w", err) } diff --git a/test/e2e/httpproxy.go b/test/e2e/httpproxy.go index b80857708851..cdc3d629917a 100644 --- a/test/e2e/httpproxy.go +++ b/test/e2e/httpproxy.go @@ -83,7 +83,6 @@ func TestProxyToHelloworld(t *testing.T, clients *test.Clients, helloworldURL *u } resources, err := v1test.CreateServiceReady(t, clients, &names, serviceOptions...) - if err != nil { t.Fatalf("Failed to create initial Service: %v: %v", names.Service, err) } diff --git a/test/e2e/logging_test.go b/test/e2e/logging_test.go index 7413546308a3..0042f7024733 100644 --- a/test/e2e/logging_test.go +++ b/test/e2e/logging_test.go @@ -81,7 +81,8 @@ func TestRequestLogs(t *testing.T) { rtesting.WithConfigAnnotations(map[string]string{ autoscaling.MinScaleAnnotationKey: "1", autoscaling.MaxScaleAnnotationKey: "1", - })}...) + }), + }...) if err != nil { t.Fatalf("Failed to create initial Service: %q: %v", names.Service, err) } @@ -135,7 +136,6 @@ func theOnlyPod(clients *test.Clients, ns, rev string) (corev1.Pod, error) { pods, err := clients.KubeClient.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{ LabelSelector: labels.Set{"app": rev}.String(), }) - if err != nil { return corev1.Pod{}, err } diff --git a/test/e2e/multicontainerprobing/multicontainer_readiness_test.go b/test/e2e/multicontainerprobing/multicontainer_readiness_test.go index a9d5cc2b55f2..94ef552ce906 100644 --- a/test/e2e/multicontainerprobing/multicontainer_readiness_test.go +++ b/test/e2e/multicontainerprobing/multicontainer_readiness_test.go @@ -55,73 +55,76 @@ func TestMultiContainerReadiness(t *testing.T) { }, } - containers := []corev1.Container{ - { - Image: pkgTest.ImagePath(names.Image), - Ports: []corev1.ContainerPort{{ - ContainerPort: 8881, - }}, - Env: []corev1.EnvVar{ - // A port in the next container to forward requests to. - {Name: "FORWARD_PORT", Value: "8882"}, - }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(8881), - }}, - }, - }, { // Sidecar with readiness probe. - Image: pkgTest.ImagePath(names.Sidecars[0]), - Env: []corev1.EnvVar{ - {Name: "PORT", Value: "8882"}, - {Name: "FORWARD_PORT", Value: "8883"}, - }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(8882), - }}, - }, - }, { // Sidecar with liveness probe. - Image: pkgTest.ImagePath(names.Sidecars[1]), - Env: []corev1.EnvVar{ - {Name: "PORT", Value: "8883"}, - {Name: "FORWARD_PORT", Value: "8884"}, + containers := []corev1.Container{{ + Image: pkgTest.ImagePath(names.Image), + Ports: []corev1.ContainerPort{{ + ContainerPort: 8881, + }}, + Env: []corev1.EnvVar{ + // A port in the next container to forward requests to. + {Name: "FORWARD_PORT", Value: "8882"}, + }, + ReadinessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(8881), + }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/", - Port: intstr.FromInt32(8883), - }}, + }, + }, { // Sidecar with readiness probe. + Image: pkgTest.ImagePath(names.Sidecars[0]), + Env: []corev1.EnvVar{ + {Name: "PORT", Value: "8882"}, + {Name: "FORWARD_PORT", Value: "8883"}, + }, + ReadinessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(8882), + }, }, - }, { // Sidecar with both readiness and liveness probes. - Image: pkgTest.ImagePath(names.Sidecars[2]), - Env: []corev1.EnvVar{ - {Name: "PORT", Value: "8884"}, - // Delay readiness. The Knative service should be ready only after all containers - // are ready and the subsequent request should pass. - {Name: "READY_DELAY", Value: "10s"}, + }, + }, { // Sidecar with liveness probe. + Image: pkgTest.ImagePath(names.Sidecars[1]), + Env: []corev1.EnvVar{ + {Name: "PORT", Value: "8883"}, + {Name: "FORWARD_PORT", Value: "8884"}, + }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/", + Port: intstr.FromInt32(8883), + }, }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/healthz", - Port: intstr.FromInt32(8884), - }}, + }, + }, { // Sidecar with both readiness and liveness probes. + Image: pkgTest.ImagePath(names.Sidecars[2]), + Env: []corev1.EnvVar{ + {Name: "PORT", Value: "8884"}, + // Delay readiness. The Knative service should be ready only after all containers + // are ready and the subsequent request should pass. + {Name: "READY_DELAY", Value: "10s"}, + }, + ReadinessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/healthz", + Port: intstr.FromInt32(8884), + }, }, - LivenessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/healthz", - Port: intstr.FromInt32(8884), - }}, + }, + LivenessProbe: &corev1.Probe{ + ProbeHandler: corev1.ProbeHandler{ + HTTPGet: &corev1.HTTPGetAction{ + Path: "/healthz", + Port: intstr.FromInt32(8884), + }, }, }, - } + }} test.EnsureTearDown(t, clients, &names) @@ -311,7 +314,8 @@ func TestMultiContainerProbeStartFailingAfterReady(t *testing.T) { HTTPGet: &corev1.HTTPGetAction{ Path: "/healthz/readiness", Port: intstr.FromInt32(8080), - }}, + }, + }, }, }, { Image: pkgTest.ImagePath(names.Sidecars[0]), @@ -323,7 +327,8 @@ func TestMultiContainerProbeStartFailingAfterReady(t *testing.T) { HTTPGet: &corev1.HTTPGetAction{ Path: "/healthz/readiness", Port: intstr.FromInt32(8881), - }}, + }, + }, }, }, } diff --git a/test/e2e/pod_schedule_error_test.go b/test/e2e/pod_schedule_error_test.go index 53fd896469a8..80d6f4845045 100644 --- a/test/e2e/pod_schedule_error_test.go +++ b/test/e2e/pod_schedule_error_test.go @@ -80,7 +80,6 @@ func TestPodScheduleError(t *testing.T) { } return false, nil }, "ContainerUnscheduleable") - if err != nil { t.Fatal("Failed to validate service state:", err) } @@ -102,7 +101,6 @@ func TestPodScheduleError(t *testing.T) { } return false, nil }) - if err != nil { t.Fatal("Failed to validate revision state:", err) } diff --git a/test/e2e/readiness_test.go b/test/e2e/readiness_test.go index 62c7ce18fa42..f2e85639eb8c 100644 --- a/test/e2e/readiness_test.go +++ b/test/e2e/readiness_test.go @@ -220,7 +220,6 @@ func TestLivenessProbeAwareOfStartupProbe(t *testing.T) { FailureThreshold: 3, }), ) - if err != nil { t.Fatalf("Failed to create initial Service: %v: %v", names.Service, err) } diff --git a/test/e2e/resource_quota_error_test.go b/test/e2e/resource_quota_error_test.go index 6c433ba02b12..4a8bfa8ea7f4 100644 --- a/test/e2e/resource_quota_error_test.go +++ b/test/e2e/resource_quota_error_test.go @@ -126,7 +126,6 @@ func TestResourceQuotaError(t *testing.T) { } return false, nil }) - if err != nil { t.Fatal("Failed to validate revision state:", err) } diff --git a/test/e2e/scale.go b/test/e2e/scale.go index 5e6d553ad4b8..09afc7539738 100644 --- a/test/e2e/scale.go +++ b/test/e2e/scale.go @@ -174,7 +174,6 @@ func ScaleToWithin(t *testing.T, scale int, duration time.Duration, latencies La url = s.Status.URL.URL() return v1test.IsServiceReady(s) }, "ServiceUpdatedWithURL") - if err != nil { t.Error("WaitForServiceState(w/ Domain) =", err) return fmt.Errorf("WaitForServiceState(w/ Domain) failed: %w", err) diff --git a/test/e2e/timeout_test.go b/test/e2e/timeout_test.go index e00b254259b0..8b157c605b88 100644 --- a/test/e2e/timeout_test.go +++ b/test/e2e/timeout_test.go @@ -38,7 +38,8 @@ import ( // sendRequestWithTimeout send a request to "endpoint", returns error if unexpected response code, nil otherwise. func sendRequestWithTimeout(t *testing.T, clients *test.Clients, endpoint *url.URL, - initialSleep, sleep time.Duration, expectedResponseCode int) error { + initialSleep, sleep time.Duration, expectedResponseCode int, +) error { client, err := pkgtest.NewSpoofingClient(context.Background(), clients.KubeClient, t.Logf, endpoint.Hostname(), test.ServingFlags.ResolvableDomain, test.AddRootCAtoTransport(context.Background(), t.Logf, clients, test.ServingFlags.HTTPS)) if err != nil { return fmt.Errorf("error creating Spoofing client: %w", err) diff --git a/test/ha/activator_test.go b/test/ha/activator_test.go index adec5620943b..800345bc00e8 100644 --- a/test/ha/activator_test.go +++ b/test/ha/activator_test.go @@ -163,7 +163,6 @@ func gatherBackingActivators(ctx context.Context, client kubernetes.Interface, n for _, rev := range revs { endpoints := client.CoreV1().Endpoints(namespace) e, err := endpoints.Get(ctx, rev, metav1.GetOptions{}) - if err != nil { return nil, fmt.Errorf("failed to gather %s endpoints: %w", rev, err) } diff --git a/test/performance/benchmarks/dataplane-probe/main.go b/test/performance/benchmarks/dataplane-probe/main.go index 2825e9ac32e2..e73d0dbd8c91 100644 --- a/test/performance/benchmarks/dataplane-probe/main.go +++ b/test/performance/benchmarks/dataplane-probe/main.go @@ -43,46 +43,44 @@ var ( minDefault = 100 * time.Millisecond ) -var ( - // Map the above to our benchmark targets. - targets = map[string]struct { - target vegeta.Target - slaMin time.Duration - slaMax time.Duration - }{ - "deployment": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://deployment.default.svc.cluster.local?sleep=100", - }, - // vanilla deployment falls in the +5ms range. This does not have Knative or Istio components - // on the dataplane, and so it is intended as a canary to flag environmental - // problems that might be causing contemporaneous Knative or Istio runs to fall out of SLA. - slaMin: minDefault, - slaMax: 105 * time.Millisecond, +// Map the above to our benchmark targets. +var targets = map[string]struct { + target vegeta.Target + slaMin time.Duration + slaMax time.Duration +}{ + "deployment": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://deployment.default.svc.cluster.local?sleep=100", }, - "queue": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://queue-proxy.default.svc.cluster.local?sleep=100", - }, - // hitting a Knative Service - // going through JUST the queue-proxy falls in the +10ms range. - slaMin: minDefault, - slaMax: 110 * time.Millisecond, + // vanilla deployment falls in the +5ms range. This does not have Knative or Istio components + // on the dataplane, and so it is intended as a canary to flag environmental + // problems that might be causing contemporaneous Knative or Istio runs to fall out of SLA. + slaMin: minDefault, + slaMax: 105 * time.Millisecond, + }, + "queue": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://queue-proxy.default.svc.cluster.local?sleep=100", }, - "activator": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://activator.default.svc.cluster.local?sleep=100", - }, - // hitting a Knative Service - // going through BOTH the activator and queue-proxy falls in the +10ms range. - slaMin: minDefault, - slaMax: 110 * time.Millisecond, + // hitting a Knative Service + // going through JUST the queue-proxy falls in the +10ms range. + slaMin: minDefault, + slaMax: 110 * time.Millisecond, + }, + "activator": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://activator.default.svc.cluster.local?sleep=100", }, - } -) + // hitting a Knative Service + // going through BOTH the activator and queue-proxy falls in the +10ms range. + slaMin: minDefault, + slaMax: 110 * time.Millisecond, + }, +} func main() { ctx := signals.NewContext() diff --git a/test/performance/benchmarks/load-test/main.go b/test/performance/benchmarks/load-test/main.go index 7ff1244447e3..62798ade48a1 100644 --- a/test/performance/benchmarks/load-test/main.go +++ b/test/performance/benchmarks/load-test/main.go @@ -41,9 +41,7 @@ const ( benchmarkName = "Knative Serving load test" ) -var ( - flavor = flag.String("flavor", "", "The flavor of the benchmark to run.") -) +var flavor = flag.String("flavor", "", "The flavor of the benchmark to run.") func main() { ctx := signals.NewContext() diff --git a/test/performance/benchmarks/reconciliation-delay/main.go b/test/performance/benchmarks/reconciliation-delay/main.go index 1c7f600b4574..1e3f1dc3f3c0 100644 --- a/test/performance/benchmarks/reconciliation-delay/main.go +++ b/test/performance/benchmarks/reconciliation-delay/main.go @@ -272,7 +272,8 @@ func getService() *v1.Service { } func handleEvent(influxReporter *performance.InfluxReporter, metricResults *vegeta.Metrics, svc kmeta.Accessor, - status duckv1.Status, seen sets.Set[string], metric string) { + status duckv1.Status, seen sets.Set[string], metric string, +) { if seen.Has(svc.GetName()) { return } diff --git a/test/performance/benchmarks/rollout-probe/main.go b/test/performance/benchmarks/rollout-probe/main.go index 960ee6c8a09d..225165058d95 100644 --- a/test/performance/benchmarks/rollout-probe/main.go +++ b/test/performance/benchmarks/rollout-probe/main.go @@ -46,29 +46,27 @@ var ( duration = flag.Duration("duration", 5*time.Minute, "The duration of the probe") ) -var ( - // Map the above to our benchmark targets. - targets = map[string]struct{ target vegeta.Target }{ - "queue-proxy-with-cc": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://queue-proxy-with-cc.default.svc.cluster.local?sleep=100", - }, +// Map the above to our benchmark targets. +var targets = map[string]struct{ target vegeta.Target }{ + "queue-proxy-with-cc": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://queue-proxy-with-cc.default.svc.cluster.local?sleep=100", }, - "activator-with-cc": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://activator-with-cc.default.svc.cluster.local?sleep=100", - }, + }, + "activator-with-cc": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://activator-with-cc.default.svc.cluster.local?sleep=100", }, - "activator-with-cc-lin": { - target: vegeta.Target{ - Method: http.MethodGet, - URL: "http://activator-with-cc-lin.default.svc.cluster.local?sleep=100", - }, + }, + "activator-with-cc-lin": { + target: vegeta.Target{ + Method: http.MethodGet, + URL: "http://activator-with-cc-lin.default.svc.cluster.local?sleep=100", }, - } -) + }, +} const ( namespace = "default" diff --git a/test/performance/benchmarks/scale-from-zero/main.go b/test/performance/benchmarks/scale-from-zero/main.go index cfa1b2b653c2..42d802f3319e 100644 --- a/test/performance/benchmarks/scale-from-zero/main.go +++ b/test/performance/benchmarks/scale-from-zero/main.go @@ -279,7 +279,8 @@ func parallelScaleFromZero(ctx context.Context, clients *test.Clients, objs []*v } func runScaleFromZero(ctx context.Context, clients *test.Clients, idx int, ro *v1test.ResourceObjects) ( - time.Duration, time.Duration, error) { + time.Duration, time.Duration, error, +) { selector := labels.SelectorFromSet(labels.Set{ serving.ServiceLabelKey: ro.Service.Name, }) diff --git a/test/performance/performance/runtime.go b/test/performance/performance/runtime.go index 699dd69736a2..b2543be0d189 100644 --- a/test/performance/performance/runtime.go +++ b/test/performance/performance/runtime.go @@ -99,7 +99,8 @@ func FetchRouteStatus(ctx context.Context, namespace, name string, duration time } func fetchStatusInternal(ctx context.Context, duration time.Duration, - f func() ([]*appsv1.Deployment, error)) <-chan DeploymentStatus { + f func() ([]*appsv1.Deployment, error), +) <-chan DeploymentStatus { ch := make(chan DeploymentStatus) startTick(duration, ctx.Done(), func(t time.Time) error { // Overlay the desired and ready pod counts. diff --git a/test/test_images/httpproxy/httpproxy.go b/test/test_images/httpproxy/httpproxy.go index e36e9cdfd4d2..869db0c1b133 100644 --- a/test/test_images/httpproxy/httpproxy.go +++ b/test/test_images/httpproxy/httpproxy.go @@ -22,11 +22,10 @@ import ( "errors" "flag" "log" - "os" - "net/http" "net/http/httputil" "net/url" + "os" "knative.dev/serving/test" ) diff --git a/test/test_images/runtime/handlers/cgroup.go b/test/test_images/runtime/handlers/cgroup.go index a360b9e8c977..d8bb80c1e0e8 100644 --- a/test/test_images/runtime/handlers/cgroup.go +++ b/test/test_images/runtime/handlers/cgroup.go @@ -30,12 +30,14 @@ var cgroupV1Paths = []string{ "/sys/fs/cgroup/memory/memory.limit_in_bytes", "/sys/fs/cgroup/cpu/cpu.cfs_period_us", "/sys/fs/cgroup/cpu/cpu.cfs_quota_us", - "/sys/fs/cgroup/cpu/cpu.shares"} + "/sys/fs/cgroup/cpu/cpu.shares", +} var cgroupV2Paths = []string{ "/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/cpu.max", - "/sys/fs/cgroup/cpu.weight"} + "/sys/fs/cgroup/cpu.weight", +} var ( yes = true @@ -73,7 +75,7 @@ func cgroups(paths ...string) []*types.Cgroup { // method for read-only validation newValue := []byte{'9'} // #nosec G306 - err = os.WriteFile(path, newValue, 0644) + err = os.WriteFile(path, newValue, 0o644) if err != nil { cgroups = append(cgroups, &types.Cgroup{Name: path, Value: &cs, ReadOnly: &yes}) } else { diff --git a/test/test_images/runtime/handlers/file.go b/test/test_images/runtime/handlers/file.go index 6e0b0f137834..4de8c41b8341 100644 --- a/test/test_images/runtime/handlers/file.go +++ b/test/test_images/runtime/handlers/file.go @@ -44,7 +44,8 @@ func fileInfo(paths ...string) map[string]types.FileInfo { Perm: perm, ModTime: file.ModTime(), SourceFile: source, - IsDir: &dir} + IsDir: &dir, + } } return files } diff --git a/test/test_images/runtime/handlers/mount.go b/test/test_images/runtime/handlers/mount.go index 8c5081ff05fa..81065d8c48a4 100644 --- a/test/test_images/runtime/handlers/mount.go +++ b/test/test_images/runtime/handlers/mount.go @@ -46,7 +46,8 @@ func mounts() []*types.Mount { Device: ms[0], Path: ms[1], Type: ms[2], - Options: strings.Split(ms[3], ",")}) + Options: strings.Split(ms[3], ","), + }) } if err := sc.Err(); err != nil { diff --git a/test/test_images/runtime/handlers/runtime.go b/test/test_images/runtime/handlers/runtime.go index 203160de7ba3..791f7f017fbb 100644 --- a/test/test_images/runtime/handlers/runtime.go +++ b/test/test_images/runtime/handlers/runtime.go @@ -45,7 +45,8 @@ func runtimeHandler(w http.ResponseWriter, r *http.Request) { k := &types.RuntimeInfo{ Request: requestInfo(r), - Host: &types.HostInfo{EnvVars: env(), + Host: &types.HostInfo{ + EnvVars: env(), Files: fileInfo(filePaths...), FileAccess: fileAccessAttempt(excludeFilePaths(filePaths, fileAccessExclusions)...), Cgroups: cgroups(cgroupPaths()...), diff --git a/test/test_images/volumes/emptydir.go b/test/test_images/volumes/emptydir.go index 96ce4ac72c3d..5db3c30f6039 100644 --- a/test/test_images/volumes/emptydir.go +++ b/test/test_images/volumes/emptydir.go @@ -41,7 +41,7 @@ func main() { if !shouldSkipDataWrite { log.Printf("Writing test content to %s.", testfilePath) // #nosec G306 - if err := os.WriteFile(testfilePath, []byte(test.EmptyDirText), 0644); err != nil { + if err := os.WriteFile(testfilePath, []byte(test.EmptyDirText), 0o644); err != nil { panic(err) } } diff --git a/test/upgrade/deployment_failure.go b/test/upgrade/deployment_failure.go index 9d70094816fb..38410e3dd43b 100644 --- a/test/upgrade/deployment_failure.go +++ b/test/upgrade/deployment_failure.go @@ -84,7 +84,6 @@ func DeploymentFailurePreUpgrade() pkgupgrade.Operation { autoscaling.MaxScaleAnnotation.Key(): "1", } }) - if err != nil { c.T.Fatal("Failed to create Service:", err) } @@ -137,7 +136,6 @@ func DeploymentFailurePreUpgrade() pkgupgrade.Operation { }, metav1.CreateOptions{}, ) - if err != nil { c.T.Fatal("Failed to create bad webhook:", err) }