From c0c9cb6052d439647659f0a2251b164e30081404 Mon Sep 17 00:00:00 2001 From: rokatyy Date: Tue, 1 Jul 2025 13:21:04 +0100 Subject: [PATCH 1/4] [CI] Migrate to v2 of golangci --- .golangci.yml | 152 ++++++++---------- Makefile | 4 +- hack/examples/golang/image/main.go | 5 +- hack/scripts/releaser/releaser.go | 8 +- pkg/auth/iguazio/auth.go | 2 +- pkg/cmdrunner/shellrunner.go | 2 +- pkg/common/helper.go | 5 +- pkg/common/url.go | 4 +- pkg/containerimagebuilderpusher/kaniko.go | 8 +- pkg/dashboard/resource/apigateway.go | 2 +- pkg/dashboard/resource/externalipaddresses.go | 2 +- pkg/dashboard/resource/frontendspec.go | 26 +-- pkg/dashboard/resource/function.go | 2 +- pkg/dashboard/resource/functionevent.go | 2 +- pkg/dashboard/resource/functiontemplate.go | 2 +- pkg/dashboard/resource/invocation.go | 2 +- pkg/dashboard/resource/namespaces.go | 2 +- pkg/dashboard/resource/project.go | 2 +- pkg/dashboard/resource/v3iostream.go | 2 +- pkg/dashboard/server.go | 5 +- pkg/dockerclient/shell.go | 2 +- pkg/functionconfig/handler.go | 2 +- pkg/functionconfig/scrubber_test.go | 4 +- pkg/functionconfig/types.go | 3 +- pkg/loggersink/appinsights/types.go | 2 +- pkg/loggersink/stdout/types.go | 2 +- pkg/nuctl/command/invoke.go | 2 +- .../abstract/project/external/client_test.go | 14 +- pkg/platform/kube/client/deployer.go | 2 +- .../kube/controller/nucliofunction.go | 8 +- .../kube/controller/test/controller_test.go | 6 +- pkg/platform/kube/functionres/lazy.go | 55 ++++--- pkg/platform/kube/functionres/lazy_test.go | 2 +- pkg/platform/kube/functionres/types.go | 2 +- pkg/platform/kube/ingress/ingress.go | 5 +- .../kube/monitoring/test/function_test.go | 2 +- pkg/platform/kube/platform.go | 24 +-- pkg/platform/kube/platform_test.go | 5 +- pkg/platform/local/platform.go | 20 +-- pkg/platform/local/test/platform_test.go | 4 +- .../dotnetcore/test/dotnetcore_test.go | 4 +- .../build/runtime/golang/test/golang_test.go | 4 +- .../build/runtime/java/test/java_test.go | 8 +- .../build/runtime/nodejs/test/nodejs_test.go | 4 +- .../build/runtime/python/test/python_test.go | 4 +- .../build/runtime/ruby/test/ruby_test.go | 4 +- .../build/runtime/shell/test/shell_test.go | 4 +- pkg/processor/build/test/build_test.go | 16 +- pkg/processor/build/util/copy.go | 3 +- pkg/processor/databinding/eventhub/types.go | 2 +- pkg/processor/databinding/v3io/types.go | 2 +- pkg/processor/eventprocessor/singleton.go | 2 +- pkg/processor/metricsink/appinsights/types.go | 2 +- .../metricsink/prometheus/pull/metricsink.go | 4 +- .../metricsink/prometheus/pull/types.go | 2 +- .../metricsink/prometheus/push/types.go | 7 +- pkg/processor/runtime/dotnetcore/runtime.go | 5 +- pkg/processor/runtime/golang/runtime.go | 7 +- pkg/processor/runtime/java/runtime.go | 3 +- pkg/processor/runtime/nodejs/runtime.go | 7 +- pkg/processor/runtime/python/runtime.go | 2 +- pkg/processor/runtime/rpc/abstract_test.go | 2 +- .../runtime/rpc/connection/abstract.go | 2 +- .../rpc/connection/connectionallocator.go | 2 +- .../connection/connectionallocator_test.go | 2 - .../runtime/rpc/connection/socketallocator.go | 2 +- pkg/processor/runtime/rpc/result/result.go | 4 +- pkg/processor/runtime/ruby/runtime.go | 3 +- pkg/processor/runtime/shell/runtime.go | 4 +- pkg/processor/runtime/shell/types.go | 2 +- .../readinesstimeout/readinesstimeout_test.go | 4 +- pkg/processor/trigger/cron/trigger.go | 2 +- pkg/processor/trigger/cron/types.go | 2 +- pkg/processor/trigger/http/trigger.go | 10 +- pkg/processor/trigger/http/types.go | 2 +- pkg/processor/trigger/kafka/scram/xdg.go | 4 +- .../kafka/test/kafka_confluent_test.go | 4 +- .../trigger/kafka/test/kafka_test.go | 13 +- pkg/processor/trigger/kafka/trigger.go | 4 +- pkg/processor/trigger/kafka/types.go | 2 +- pkg/processor/trigger/kickstart/trigger.go | 2 +- pkg/processor/trigger/kickstart/types.go | 2 +- .../trigger/kinesis/test/kinesis_test.go | 2 +- pkg/processor/trigger/kinesis/trigger.go | 2 +- pkg/processor/trigger/kinesis/types.go | 2 +- .../trigger/mqtt/basic/test/mqtt_test.go | 2 +- pkg/processor/trigger/mqtt/basic/trigger.go | 2 +- pkg/processor/trigger/mqtt/iotcore/trigger.go | 2 +- pkg/processor/trigger/mqtt/iotcore/types.go | 2 +- pkg/processor/trigger/mqtt/types.go | 2 +- .../trigger/nats/core/test/nats_test.go | 2 +- pkg/processor/trigger/nats/core/trigger.go | 2 +- pkg/processor/trigger/nats/core/types.go | 2 +- .../nats/jetstream/test/natsjetstream_test.go | 2 +- .../trigger/nats/jetstream/trigger.go | 2 +- pkg/processor/trigger/nats/jetstream/types.go | 2 +- .../eventhub/test/eventhub_test.go | 2 +- .../trigger/partitioned/eventhub/types.go | 2 +- pkg/processor/trigger/partitioned/trigger.go | 2 +- pkg/processor/trigger/poller/types.go | 2 +- .../trigger/poller/v3ioitempoller/trigger.go | 2 +- .../trigger/pubsub/test/pubsub_test.go | 2 +- pkg/processor/trigger/pubsub/trigger.go | 2 +- pkg/processor/trigger/pubsub/types.go | 2 +- .../trigger/rabbitmq/test/rabbitmq_test.go | 6 +- pkg/processor/trigger/rabbitmq/trigger.go | 2 +- pkg/processor/trigger/rabbitmq/types.go | 2 +- pkg/processor/trigger/test/broker.go | 2 +- pkg/processor/trigger/trigger.go | 2 + pkg/processor/trigger/types.go | 6 +- .../v3iostream/test/v3iostream_test.go | 4 +- pkg/processor/trigger/v3iostream/trigger.go | 10 +- pkg/processor/trigger/v3iostream/types.go | 2 +- pkg/processor/util/v3io/v3ioutil.go | 5 +- pkg/processwaiter/processwaiter.go | 3 +- 115 files changed, 319 insertions(+), 344 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7cf1c798181..87e8127b2ec 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,39 +1,5 @@ -# Copyright 2023 The Nuclio Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -linters: - disable-all: true - enable: - - goconst - - gofmt - - revive - - gosimple - - ineffassign - - misspell - - staticcheck - - unconvert - - errcheck - - govet - - typecheck - - gocritic - - unused - - gci - +version: "2" run: - - # timeout for analysis - timeout: 5m build-tags: - test_unit - test_integration @@ -43,53 +9,71 @@ run: - test_iguazio - test_broken - test_benchmark - -linters-settings: - revive: +linters: + default: none + enable: + - errcheck + - goconst + - gocritic + - govet + - ineffassign + - misspell + - revive + - staticcheck + - unconvert + - unused + settings: + gocritic: + disabled-checks: + - commentFormatting + revive: + rules: + - name: errorf + disabled: true + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling rules: - - # avoid errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) messages - - name: errorf - disabled: true - - gocritic: - disabled-checks: - # we don't want to enforce space before the comment text - - commentFormatting - - gci: - sections: - - standard - - prefix(github.com/nuclio/nuclio/) - - default - - blank - - dot - - custom-order: true - -issues: - - # List of regexps of issue texts to exclude - exclude: - - "comment on" - - "error should be the last" - - exclude-dirs: - - docs - - vendor - - exclude-rules: - - # Auto generated files for kubernetes - - path: pkg/platform/kube/client - linters: - - errcheck - - # list of excluded linters applied on test files - - path: _test\.go - linters: - - goconst - - # false positive - - path: pkg/common/k8s.go - text: "deprecatedComment: the proper format is `Deprecated: `" + - linters: + - errcheck + path: pkg/platform/kube/client + - linters: + - goconst + path: _test\.go + - path: pkg/common/k8s.go + text: 'deprecatedComment: the proper format is `Deprecated: `' + - path: (.+)\.go$ + text: comment on + - path: (.+)\.go$ + text: error should be the last + paths: + - docs + - vendor + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gci + - gofmt + settings: + gci: + sections: + - standard + - prefix(github.com/nuclio/nuclio/) + - default + - blank + - dot + custom-order: true + exclusions: + generated: lax + paths: + - docs + - vendor + - third_party$ + - builtin$ + - examples$ diff --git a/Makefile b/Makefile index f61f10a3eae..8dfe1899f82 100644 --- a/Makefile +++ b/Makefile @@ -692,9 +692,9 @@ ensure-test-files-annotated: @echo "All go test files have //go:build test_X annotation" @exit $(.SHELLSTATUS) -GOLANGCI_LINT_VERSION := v1.64.6 +GOLANGCI_LINT_VERSION := 2.2.0 GOLANGCI_LINT_BIN := $(GOPATH)/bin/golangci-lint -GOLANGCI_LINT_INSTALL_COMMAND := GOBIN=$(GOPATH)/bin go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION) +GOLANGCI_LINT_INSTALL_COMMAND := GOBIN=$(GOPATH)/bin go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v$(GOLANGCI_LINT_VERSION) .PHONY: ensure-golangci-linter ensure-golangci-linter: diff --git a/hack/examples/golang/image/main.go b/hack/examples/golang/image/main.go index 6b70cc70900..9656d57ac02 100644 --- a/hack/examples/golang/image/main.go +++ b/hack/examples/golang/image/main.go @@ -57,8 +57,9 @@ func Handler(context *nuclio.Context, event nuclio.Event) (interface{}, error) { var img image.Image var err error if strings.HasPrefix(event.GetContentType(), "text/plain") { + var response *http.Response // if the body is text assume its a URL and read the image from the URL (in the text) - response, err := http.Get(string(event.GetBody())) + response, err = http.Get(string(event.GetBody())) if err != nil { return nil, err } @@ -92,6 +93,6 @@ func Handler(context *nuclio.Context, event nuclio.Event) (interface{}, error) { StatusCode: 200, ContentType: respType, Body: buf.Bytes(), - }, nil + }, err } diff --git a/hack/scripts/releaser/releaser.go b/hack/scripts/releaser/releaser.go index 3b6f167a653..9dcc8804515 100644 --- a/hack/scripts/releaser/releaser.go +++ b/hack/scripts/releaser/releaser.go @@ -211,17 +211,17 @@ func (r *Release) saveReleaseInfo() error { defer file.Close() // Write the version information with specific labels to the file - _, err = file.WriteString(fmt.Sprintf("CURRENT_VERSION: %s\n", r.currentVersion.String())) + _, err = fmt.Fprintf(file, "CURRENT_VERSION: %s\n", r.currentVersion.String()) if err != nil { return errors.Wrap(err, "Failed to write current version") } - _, err = file.WriteString(fmt.Sprintf("TARGET_VERSION: %s\n", r.targetVersion.String())) + _, err = fmt.Fprintf(file, "TARGET_VERSION: %s\n", r.targetVersion.String()) if err != nil { return errors.Wrap(err, "Failed to write target version") } - _, err = file.WriteString(fmt.Sprintf("HELM_CHARTS_TARGET_VERSION: %s\n", r.helmChartsTargetVersion.String())) + _, err = fmt.Fprintf(file, "HELM_CHARTS_TARGET_VERSION: %s\n", r.helmChartsTargetVersion.String()) if err != nil { return errors.Wrap(err, "Failed to write helm charts target version") } @@ -285,7 +285,7 @@ func (r *Release) bumpHelmChartVersion() error { } func (r *Release) populateBumpedVersions() error { - if !(r.bumpPatch || r.bumpMinor || r.bumpMajor) { + if !r.bumpPatch && !r.bumpMinor && !r.bumpMajor { return nil } diff --git a/pkg/auth/iguazio/auth.go b/pkg/auth/iguazio/auth.go index 9d248a6ccc9..8cb23102f06 100644 --- a/pkg/auth/iguazio/auth.go +++ b/pkg/auth/iguazio/auth.go @@ -128,7 +128,7 @@ func (a *Auth) Authenticate(request *http.Request, options *authpkg.Options) (au } // not within range of 200 - if !(response.StatusCode >= http.StatusOK && response.StatusCode < 300) { + if response.StatusCode < http.StatusOK || response.StatusCode >= 300 { a.logger.WarnWithCtx(ctx, "Unexpected authentication status code", "authorizationHeaderLength", len(authHeaders["authorization"]), diff --git a/pkg/cmdrunner/shellrunner.go b/pkg/cmdrunner/shellrunner.go index 1753d20b27d..3863264eff0 100644 --- a/pkg/cmdrunner/shellrunner.go +++ b/pkg/cmdrunner/shellrunner.go @@ -223,7 +223,7 @@ func (sr *ShellRunner) runAndCaptureOutput(cmd *exec.Cmd, return err } - return fmt.Errorf("Invalid output capture mode: %d", runOptions.CaptureOutputMode) + return errors.Errorf("Invalid output capture mode: %d", runOptions.CaptureOutputMode) } func Redact(redactions []string, runOutput string) string { diff --git a/pkg/common/helper.go b/pkg/common/helper.go index 1104d073cf6..e9433645086 100644 --- a/pkg/common/helper.go +++ b/pkg/common/helper.go @@ -359,9 +359,10 @@ func FixEscapeChars(s string) string { func GetEnvOrDefaultString(key string, defaultValue string) string { value := os.Getenv(key) - if value == "" { + switch value { + case "": return defaultValue - } else if value == "nil" || value == "none" { + case "nil", "none": return "" } return value diff --git a/pkg/common/url.go b/pkg/common/url.go index e204ec168d3..e8d9f0b3f93 100644 --- a/pkg/common/url.go +++ b/pkg/common/url.go @@ -54,7 +54,7 @@ func DownloadFile(url string, out *os.File, headers http.Header) error { } if response.StatusCode != http.StatusOK { - return fmt.Errorf( + return errors.Errorf( "Failed to download file. Received an unexpected status code: %d", response.StatusCode) } @@ -72,7 +72,7 @@ func DownloadFile(url string, out *os.File, headers http.Header) error { } if response.ContentLength != -1 && written != response.ContentLength { - return fmt.Errorf( + return errors.Errorf( "Downloaded file length (%d) is different than URL content length (%d)", written, response.ContentLength) diff --git a/pkg/containerimagebuilderpusher/kaniko.go b/pkg/containerimagebuilderpusher/kaniko.go index aa5b633c119..ccedf002936 100644 --- a/pkg/containerimagebuilderpusher/kaniko.go +++ b/pkg/containerimagebuilderpusher/kaniko.go @@ -577,7 +577,7 @@ func (k *Kaniko) waitForJobCompletion(ctx context.Context, "Failed to get job logs", "err", err.Error()) return errors.Wrap(err, "Failed to retrieve kaniko job logs") } - return fmt.Errorf("Job failed. Job logs:\n%s", jobLogs) + return errors.Errorf("Job failed. Job logs:\n%s", jobLogs) } k.logger.DebugWithCtx(ctx, @@ -606,7 +606,7 @@ func (k *Kaniko) waitForJobCompletion(ctx context.Context, if err != nil { return errors.Wrap(err, "Job failed and was unable to retrieve job logs") } - return fmt.Errorf("Job has timed out. Job logs:\n%s", jobLogs) + return errors.Errorf("Job has timed out. Job logs:\n%s", jobLogs) } func (k *Kaniko) resolveFailFast(ctx context.Context, @@ -632,10 +632,10 @@ func (k *Kaniko) resolveFailFast(ctx context.Context, "failFastTimeoutDuration", readinessTimout.String()) if lastError != "" { - return fmt.Errorf("Job was not completed in time, job name: %s. Error: %s ", jobName, + return errors.Errorf("Job was not completed in time, job name: %s. Error: %s ", jobName, lastError) } else { - return fmt.Errorf("Job was not completed in time, job name: %s", jobName) + return errors.Errorf("Job was not completed in time, job name: %s", jobName) } default: jobPod, err := k.getJobPod(ctx, jobName, namespace, true) diff --git a/pkg/dashboard/resource/apigateway.go b/pkg/dashboard/resource/apigateway.go index 53ed4008abf..e8c6f495e65 100644 --- a/pkg/dashboard/resource/apigateway.go +++ b/pkg/dashboard/resource/apigateway.go @@ -46,7 +46,7 @@ type apiGatewayInfo struct { } func (agr *apiGatewayResource) ExtendMiddlewares() error { - agr.resource.addAuthMiddleware(nil) + agr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/externalipaddresses.go b/pkg/dashboard/resource/externalipaddresses.go index f29d7d53961..021d313a893 100644 --- a/pkg/dashboard/resource/externalipaddresses.go +++ b/pkg/dashboard/resource/externalipaddresses.go @@ -30,7 +30,7 @@ type externalIPAddressesResource struct { } func (eiar *externalIPAddressesResource) ExtendMiddlewares() error { - eiar.resource.addAuthMiddleware(nil) + eiar.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/frontendspec.go b/pkg/dashboard/resource/frontendspec.go index a7133617f6b..7fc0d5e97bb 100644 --- a/pkg/dashboard/resource/frontendspec.go +++ b/pkg/dashboard/resource/frontendspec.go @@ -35,7 +35,7 @@ type frontendSpecResource struct { } func (fsr *frontendSpecResource) ExtendMiddlewares() error { - fsr.resource.addAuthMiddleware(nil) + fsr.addAuthMiddleware(nil) return nil } @@ -52,7 +52,7 @@ func (fsr *frontendSpecResource) getFrontendSpec(request *http.Request) (*restfu // try to get platform kind platformKind := "" - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { platformConfiguration := dashboardServer.GetPlatformConfiguration() if platformConfiguration != nil { platformKind = platformConfiguration.Kind @@ -174,7 +174,7 @@ func (fsr *frontendSpecResource) GetCustomRoutes() ([]restful.CustomRoute, error func (fsr *frontendSpecResource) resolveDefaultServiceType() v1.ServiceType { var defaultServiceType v1.ServiceType - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultServiceType = dashboardServer.GetPlatformConfiguration().Kube.DefaultServiceType } return defaultServiceType @@ -182,7 +182,7 @@ func (fsr *frontendSpecResource) resolveDefaultServiceType() v1.ServiceType { func (fsr *frontendSpecResource) resolveDefaultFunctionPreemptionMode() functionconfig.RunOnPreemptibleNodeMode { var defaultPreemptionMode functionconfig.RunOnPreemptibleNodeMode - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { if dashboardServer.GetPlatformConfiguration().Kube.PreemptibleNodes != nil { defaultPreemptionMode = dashboardServer.GetPlatformConfiguration().Kube.PreemptibleNodes.DefaultMode } @@ -192,7 +192,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionPreemptionMode() function func (fsr *frontendSpecResource) resolveFunctionReadinessTimeoutSeconds() int { readinessTimeoutSeconds := platformconfig.DefaultFunctionReadinessTimeoutSeconds - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { return int(dashboardServer.GetPlatformConfiguration().GetDefaultFunctionReadinessTimeout().Seconds()) } return readinessTimeoutSeconds @@ -200,7 +200,7 @@ func (fsr *frontendSpecResource) resolveFunctionReadinessTimeoutSeconds() int { func (fsr *frontendSpecResource) resolveDefaultFunctionNodeSelector() map[string]string { var defaultFunctionNodeSelector map[string]string - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultFunctionNodeSelector = dashboardServer.GetPlatformConfiguration().Kube.DefaultFunctionNodeSelector } return defaultFunctionNodeSelector @@ -208,7 +208,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionNodeSelector() map[string func (fsr *frontendSpecResource) resolveDefaultFunctionTolerations() []v1.Toleration { var defaultFunctionTolerations []v1.Toleration - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultFunctionTolerations = dashboardServer.GetPlatformConfiguration().Kube.DefaultFunctionTolerations } return defaultFunctionTolerations @@ -216,7 +216,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionTolerations() []v1.Tolera func (fsr *frontendSpecResource) resolveDefaultFunctionPriorityClassName() string { var defaultFunctionPriorityClassName string - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultFunctionPriorityClassName = dashboardServer.GetPlatformConfiguration().Kube.DefaultFunctionPriorityClassName } return defaultFunctionPriorityClassName @@ -224,7 +224,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionPriorityClassName() strin func (fsr *frontendSpecResource) resolveDefaultFunctionServiceAccount() string { var defaultFunctionServiceAccount string - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultFunctionServiceAccount = dashboardServer.GetPlatformConfiguration().Kube.DefaultFunctionServiceAccount } return defaultFunctionServiceAccount @@ -232,7 +232,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionServiceAccount() string { func (fsr *frontendSpecResource) resolveDefaultFunctionPodResources() platformconfig.PodResourceRequirements { var defaultFunctionPodResources platformconfig.PodResourceRequirements - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultFunctionPodResources = dashboardServer.GetPlatformConfiguration().Kube.DefaultFunctionPodResources } return defaultFunctionPodResources @@ -240,7 +240,7 @@ func (fsr *frontendSpecResource) resolveDefaultFunctionPodResources() platformco func (fsr *frontendSpecResource) resolveValidFunctionPriorityClassNames() []string { var validFunctionPriorityClassNames []string - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { validFunctionPriorityClassNames = dashboardServer.GetPlatformConfiguration().Kube.ValidFunctionPriorityClassNames } return validFunctionPriorityClassNames @@ -250,7 +250,7 @@ func (fsr *frontendSpecResource) resolveAutoScaleMetrics(inactivityWindowPresets var supportedAutoScaleMetrics []functionconfig.AutoScaleMetric windowSizePresets := inactivityWindowPresets customMetricsEnabled := false - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { supportedAutoScaleMetrics = dashboardServer.GetPlatformConfiguration().SupportedAutoScaleMetrics if len(supportedAutoScaleMetrics) == 0 { supportedAutoScaleMetrics = dashboardServer.GetPlatformConfiguration().GetDefaultSupportedAutoScaleMetrics() @@ -273,7 +273,7 @@ func (fsr *frontendSpecResource) getDefaultHTTPIngressHostTemplate() string { // try read from platform configuration first, if set use that, otherwise // fallback reading from envvar for backwards compatibility with old helm charts - if dashboardServer, ok := fsr.resource.GetServer().(*dashboard.Server); ok { + if dashboardServer, ok := fsr.GetServer().(*dashboard.Server); ok { defaultHTTPIngressHostTemplate := dashboardServer.GetPlatformConfiguration().Kube.DefaultHTTPIngressHostTemplate if defaultHTTPIngressHostTemplate != "" { return defaultHTTPIngressHostTemplate diff --git a/pkg/dashboard/resource/function.go b/pkg/dashboard/resource/function.go index d723ef29392..4a929768ac3 100644 --- a/pkg/dashboard/resource/function.go +++ b/pkg/dashboard/resource/function.go @@ -56,7 +56,7 @@ type PatchOptions struct { } func (fr *functionResource) ExtendMiddlewares() error { - fr.resource.addAuthMiddleware(nil) + fr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/functionevent.go b/pkg/dashboard/resource/functionevent.go index 2d6c0e77457..3190b877b1b 100644 --- a/pkg/dashboard/resource/functionevent.go +++ b/pkg/dashboard/resource/functionevent.go @@ -43,7 +43,7 @@ type functionEventInfo struct { } func (fer *functionEventResource) ExtendMiddlewares() error { - fer.resource.addAuthMiddleware(nil) + fer.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/functiontemplate.go b/pkg/dashboard/resource/functiontemplate.go index 093148fa132..3ade4fbda2e 100644 --- a/pkg/dashboard/resource/functiontemplate.go +++ b/pkg/dashboard/resource/functiontemplate.go @@ -44,7 +44,7 @@ func (ftr *functionTemplateResource) OnAfterInitialize() error { } func (ftr *functionTemplateResource) ExtendMiddlewares() error { - ftr.resource.addAuthMiddleware(nil) + ftr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/invocation.go b/pkg/dashboard/resource/invocation.go index c111c8dc740..8aaa463afb7 100644 --- a/pkg/dashboard/resource/invocation.go +++ b/pkg/dashboard/resource/invocation.go @@ -39,7 +39,7 @@ type invocationResource struct { } func (tr *invocationResource) ExtendMiddlewares() error { - tr.resource.addAuthMiddleware(nil) + tr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/namespaces.go b/pkg/dashboard/resource/namespaces.go index 89b010fadcd..0ea56ca8189 100644 --- a/pkg/dashboard/resource/namespaces.go +++ b/pkg/dashboard/resource/namespaces.go @@ -28,7 +28,7 @@ type namespaceResource struct { } func (nr *namespaceResource) ExtendMiddlewares() error { - nr.resource.addAuthMiddleware(nil) + nr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/project.go b/pkg/dashboard/resource/project.go index 1648ac6c0be..20ea6162ddd 100644 --- a/pkg/dashboard/resource/project.go +++ b/pkg/dashboard/resource/project.go @@ -63,7 +63,7 @@ type ProjectImportOptions struct { } func (pr *projectResource) ExtendMiddlewares() error { - pr.resource.addAuthMiddleware(nil) + pr.addAuthMiddleware(nil) return nil } diff --git a/pkg/dashboard/resource/v3iostream.go b/pkg/dashboard/resource/v3iostream.go index be89b81bb30..13965ad1c00 100644 --- a/pkg/dashboard/resource/v3iostream.go +++ b/pkg/dashboard/resource/v3iostream.go @@ -41,7 +41,7 @@ type v3ioStreamResource struct { } func (vsr *v3ioStreamResource) ExtendMiddlewares() error { - vsr.resource.addAuthMiddleware(&auth.Options{ + vsr.addAuthMiddleware(&auth.Options{ // we need a data plane session for accessing the v3io stream container EnrichDataPlane: true, diff --git a/pkg/dashboard/server.go b/pkg/dashboard/server.go index 2cf98b4e5b5..2cf11f053e8 100644 --- a/pkg/dashboard/server.go +++ b/pkg/dashboard/server.go @@ -134,11 +134,12 @@ func NewServer(parentLogger logger.Logger, } // try to load docker keys, ignoring errors - if containerBuilderKind == "docker" { + switch containerBuilderKind { + case "docker": if err := newServer.loadDockerKeys(newServer.dockerKeyDir); err != nil { newServer.Logger.WarnWith("Failed to login with docker keys", "err", err.Error()) } - } else if containerBuilderKind == "kaniko" { + case "kaniko": if common.GetEnvOrDefaultString("NUCLIO_DASHBOARD_SERVE_KANIKO_ARTIFACTS_MODE", "local") == common.LocalPlatformName { diff --git a/pkg/dockerclient/shell.go b/pkg/dockerclient/shell.go index 35fed910adf..755aa15c67a 100644 --- a/pkg/dockerclient/shell.go +++ b/pkg/dockerclient/shell.go @@ -398,7 +398,7 @@ func (c *ShellClient) RunContainer(imageName string, runOptions *RunOptions) (st // cause additional information to be outputted. if runOptions.ImageMayNotExist is false, // this will result in an error. if !runOptions.ImageMayNotExist { - return "", fmt.Errorf("Output from docker command includes more than just ID: %s", lastStdoutLine) + return "", errors.Errorf("Output from docker command includes more than just ID: %s", lastStdoutLine) } // if the implicit image pull was allowed and actually happened, the container ID will appear in the diff --git a/pkg/functionconfig/handler.go b/pkg/functionconfig/handler.go index a18eac02cab..7f9b14d7f6a 100644 --- a/pkg/functionconfig/handler.go +++ b/pkg/functionconfig/handler.go @@ -36,6 +36,6 @@ func ParseHandler(handler string) (string, string, error) { return moduleAndEntrypoint[0], moduleAndEntrypoint[1], nil default: - return "", "", fmt.Errorf("Invalid handler name %s", handler) + return "", "", fmt.Errorf("invalid handler name %s", handler) } } diff --git a/pkg/functionconfig/scrubber_test.go b/pkg/functionconfig/scrubber_test.go index f1b94f9c363..09c5444e20e 100644 --- a/pkg/functionconfig/scrubber_test.go +++ b/pkg/functionconfig/scrubber_test.go @@ -130,8 +130,8 @@ func (suite *ScrubberTestSuite) TestScrubBasics() { scrubbedFunctionConfig.Spec.Triggers["secret-trigger"].Attributes["password"]) suite.Require().Equal(functionConfig.Spec.Triggers["non-secret-trigger"].Attributes["not-a-password"], scrubbedFunctionConfig.Spec.Triggers["non-secret-trigger"].Attributes["not-a-password"]) - suite.Require().NotEqual(functionConfig.Spec.Volumes[0].Volume.VolumeSource.FlexVolume.Options["accesskey"], - scrubbedFunctionConfig.Spec.Volumes[0].Volume.VolumeSource.FlexVolume.Options["accesskey"]) + suite.Require().NotEqual(functionConfig.Spec.Volumes[0].Volume.FlexVolume.Options["accesskey"], + scrubbedFunctionConfig.Spec.Volumes[0].Volume.FlexVolume.Options["accesskey"]) suite.Require().NotEqual(functionConfig.Meta.Annotations["nuclio.io/kafka-ca-cert"], scrubbedFunctionConfig.Meta.Annotations["nuclio.io/kafka-ca-cert"]) diff --git a/pkg/functionconfig/types.go b/pkg/functionconfig/types.go index e546871ea98..71a171880c6 100644 --- a/pkg/functionconfig/types.go +++ b/pkg/functionconfig/types.go @@ -17,7 +17,6 @@ limitations under the License. package functionconfig import ( - "fmt" "reflect" "strconv" "strings" @@ -620,7 +619,7 @@ func (s *Spec) GetHTTPPort() int { func (s *Spec) GetEventTimeout() (time.Duration, error) { timeout, err := time.ParseDuration(s.EventTimeout) if err == nil && timeout <= 0 { - err = fmt.Errorf("eventTimeout <= 0 (%s)", timeout) + err = errors.Errorf("eventTimeout <= 0 (%s)", timeout) } return timeout, err diff --git a/pkg/loggersink/appinsights/types.go b/pkg/loggersink/appinsights/types.go index 87cbec5f6ae..ed58e364965 100644 --- a/pkg/loggersink/appinsights/types.go +++ b/pkg/loggersink/appinsights/types.go @@ -41,7 +41,7 @@ func NewConfiguration(name string, loggerSinkConfiguration *platformconfig.Logge newConfiguration.Configuration = *loggersink.NewConfiguration(name, loggerSinkConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Sink.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Sink.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/loggersink/stdout/types.go b/pkg/loggersink/stdout/types.go index ff59cb2d467..38f23227ad7 100644 --- a/pkg/loggersink/stdout/types.go +++ b/pkg/loggersink/stdout/types.go @@ -41,7 +41,7 @@ func NewConfiguration(name string, loggerSinkConfiguration *platformconfig.Logge newConfiguration.Configuration = *loggersink.NewConfiguration(name, loggerSinkConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/nuctl/command/invoke.go b/pkg/nuctl/command/invoke.go index 8cc114202b4..66900ad328e 100644 --- a/pkg/nuctl/command/invoke.go +++ b/pkg/nuctl/command/invoke.go @@ -268,7 +268,7 @@ func (i *invokeCommandeer) outputInvokeResult(createFunctionInvocationOptions *p } // if the flag is set - fail in case function invocation returns non-200 status code - if !(invokeResult.StatusCode >= http.StatusOK && invokeResult.StatusCode < 300) && i.raiseOnStatus { + if (invokeResult.StatusCode < http.StatusOK || invokeResult.StatusCode >= 300) && i.raiseOnStatus { return errors.New("Function invocation failed") } diff --git a/pkg/platform/abstract/project/external/client_test.go b/pkg/platform/abstract/project/external/client_test.go index 9b86e3ad6e7..343473c54c2 100644 --- a/pkg/platform/abstract/project/external/client_test.go +++ b/pkg/platform/abstract/project/external/client_test.go @@ -90,7 +90,7 @@ func (suite *ExternalProjectClientTestSuite) TestLeaderCreate() { Return(&platform.AbstractProject{}, nil). Once() - _, err := suite.Client.Create(suite.ctx, &createProjectOptions) + _, err := suite.Create(suite.ctx, &createProjectOptions) suite.Require().NoError(err) } @@ -109,7 +109,7 @@ func (suite *ExternalProjectClientTestSuite) TestLeaderUpdate() { Return(&platform.AbstractProject{}, nil). Once() - _, err := suite.Client.Update(suite.ctx, &updateProjectOptions) + _, err := suite.Update(suite.ctx, &updateProjectOptions) suite.Require().NoError(err) } @@ -126,7 +126,7 @@ func (suite *ExternalProjectClientTestSuite) TestLeaderDelete() { Return(nil). Once() - err := suite.Client.Delete(suite.ctx, &deleteProjectOptions) + err := suite.Delete(suite.ctx, &deleteProjectOptions) suite.Require().NoError(err) } @@ -145,7 +145,7 @@ func (suite *ExternalProjectClientTestSuite) TestNotLeaderCreate() { Return(nil, nil). Once() - _, err := suite.Client.Create(suite.ctx, &createProjectOptions) + _, err := suite.Create(suite.ctx, &createProjectOptions) suite.Require().Error(err) suite.Require().Equal(err, platform.ErrSuccessfulCreateProjectLeader) } @@ -165,7 +165,7 @@ func (suite *ExternalProjectClientTestSuite) TestNotLeaderUpdate() { Return(nil, nil). Once() - _, err := suite.Client.Update(suite.ctx, &updateProjectOptions) + _, err := suite.Update(suite.ctx, &updateProjectOptions) suite.Require().Error(err) suite.Require().Equal(err, platform.ErrSuccessfulUpdateProjectLeader) } @@ -183,7 +183,7 @@ func (suite *ExternalProjectClientTestSuite) TestNotLeaderDelete() { Return(nil). Once() - err := suite.Client.Delete(suite.ctx, &deleteProjectOptions) + err := suite.Delete(suite.ctx, &deleteProjectOptions) suite.Require().Error(err) suite.Require().Equal(err, platform.ErrSuccessfulDeleteProjectLeader) } @@ -200,7 +200,7 @@ func (suite *ExternalProjectClientTestSuite) TestGet() { Return([]platform.Project{}, nil). Once() - _, err := suite.Client.Get(suite.ctx, &getProjectOptions) + _, err := suite.Get(suite.ctx, &getProjectOptions) suite.Require().NoError(err) } diff --git a/pkg/platform/kube/client/deployer.go b/pkg/platform/kube/client/deployer.go index f502e490af4..f6a1c22d819 100644 --- a/pkg/platform/kube/client/deployer.go +++ b/pkg/platform/kube/client/deployer.go @@ -295,7 +295,7 @@ func (d *Deployer) getLastCreatedPod(pods []v1.Pod) v1.Pod { // get the latest pod for _, pod := range pods { - if latestPod.ObjectMeta.CreationTimestamp.Before(&pod.ObjectMeta.CreationTimestamp) { + if latestPod.CreationTimestamp.Before(&pod.CreationTimestamp) { latestPod = pod } } diff --git a/pkg/platform/kube/controller/nucliofunction.go b/pkg/platform/kube/controller/nucliofunction.go index dd6b1c8c43c..1366aed7367 100644 --- a/pkg/platform/kube/controller/nucliofunction.go +++ b/pkg/platform/kube/controller/nucliofunction.go @@ -160,15 +160,15 @@ func (fo *functionOperator) CreateOrUpdate(ctx context.Context, object runtime.O var prevState string // clean the irrelevant annotations from the CRD before adding resources - if function.ObjectMeta.Annotations != nil { - prevState = function.ObjectMeta.Annotations[functionconfig.FunctionAnnotationPrevState] + if function.Annotations != nil { + prevState = function.Annotations[functionconfig.FunctionAnnotationPrevState] annotationsToClean := []string{ functionconfig.FunctionAnnotationForceUpdate, functionconfig.FunctionAnnotationPrevState, functionconfig.FunctionAnnotationSkipDeploy, } for _, annotation := range annotationsToClean { - delete(function.ObjectMeta.Annotations, annotation) + delete(function.Annotations, annotation) } } @@ -262,7 +262,7 @@ func (fo *functionOperator) CreateOrUpdate(ctx context.Context, object runtime.O defer cancel() // wait until the function resources are ready - if err, functionState := fo.functionresClient.WaitAvailable(waitContext, + if functionState, err := fo.functionresClient.WaitAvailable(waitContext, function, functionResourcesCreateOrUpdateTimestamp); err != nil { diff --git a/pkg/platform/kube/controller/test/controller_test.go b/pkg/platform/kube/controller/test/controller_test.go index e93992487ed..60ded4015cc 100644 --- a/pkg/platform/kube/controller/test/controller_test.go +++ b/pkg/platform/kube/controller/test/controller_test.go @@ -37,7 +37,7 @@ type ControllerTestSuite struct { } func (suite *ControllerTestSuite) SetupSuite() { - suite.KubeTestSuite.DisableControllerStart = true + suite.DisableControllerStart = true suite.KubeTestSuite.SetupSuite() } @@ -71,7 +71,7 @@ func (suite *ControllerTestSuite) TestStaleResourceVersion() { suite.Require().Equal(0, int(suite.Controller.GetResyncInterval())) // start controller - err = suite.Controller.Start(suite.KubeTestSuite.Ctx) + err = suite.Controller.Start(suite.Ctx) suite.Require().NoError(err) suite.WaitForFunctionState(&platform.GetFunctionsOptions{ @@ -90,7 +90,7 @@ func (suite *ControllerTestSuite) buildTestFunction() *functionconfig.Config { suite.Require().NoError(err) // enrich with defaults - err = suite.Platform.EnrichFunctionConfig(suite.KubeTestSuite.Ctx, &createFunctionOptions.FunctionConfig) + err = suite.Platform.EnrichFunctionConfig(suite.Ctx, &createFunctionOptions.FunctionConfig) suite.Require().NoError(err) // build function diff --git a/pkg/platform/kube/functionres/lazy.go b/pkg/platform/kube/functionres/lazy.go index dda399f9879..5cf1b7384ee 100644 --- a/pkg/platform/kube/functionres/lazy.go +++ b/pkg/platform/kube/functionres/lazy.go @@ -270,7 +270,7 @@ func (lc *lazyClient) UpdatedServiceSelectorWhenScaledFromZero(ctx context.Conte func (lc *lazyClient) WaitAvailable(ctx context.Context, function *nuclioio.NuclioFunction, - functionResourcesCreateOrUpdateTimestamp time.Time) (error, functionconfig.FunctionState) { + functionResourcesCreateOrUpdateTimestamp time.Time) (functionconfig.FunctionState, error) { lc.logger.DebugWithCtx(ctx, "Waiting for function resources to be available", @@ -313,7 +313,7 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, "err", ctx.Err(), "namespace", function.Namespace, "functionName", function.Name) - return nil, functionconfig.FunctionStateReady + return functionconfig.FunctionStateReady, nil } if !initContainersDone { lc.logger.WarnWithCtx(ctx, @@ -322,8 +322,8 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, "err", ctx.Err(), "namespace", function.Namespace, "functionName", function.Name) - return errors.New(fmt.Sprintf("Init containers are not done yet. Reason: %s. Increasing readiness timeout may help", reasonInitContainersNotDone)), - functionconfig.FunctionStateUnhealthy + return functionconfig.FunctionStateUnhealthy, errors.New(fmt.Sprintf("Init containers are not done yet. Reason: %s. Increasing readiness timeout may help", reasonInitContainersNotDone)) + } else { // create a new context with timeout to get the last warning events k8sCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -345,16 +345,15 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, if warningEvents != "" { // return k8s events in the error message // later this error is used as a status.message - return errors.Wrap(ctx.Err(), - "Function available wait is cancelled due to context timeout when function wasn't ready yet. Last k8s events: "+warningEvents), - functionconfig.FunctionStateUnhealthy + return functionconfig.FunctionStateUnhealthy, errors.Wrap(ctx.Err(), + "Function available wait is cancelled due to context timeout when function wasn't ready yet. Last k8s events: "+warningEvents) } - return ctx.Err(), functionconfig.FunctionStateUnhealthy + return functionconfig.FunctionStateUnhealthy, ctx.Err() // verify availability case <-availableTicker.C: if deploymentReady && ingressReady { - return nil, functionconfig.FunctionStateReady + return functionconfig.FunctionStateReady, nil } // verify function resources readiness @@ -374,7 +373,7 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, initContainersDone, reasonInitContainersNotDone, err = lc.checkFunctionInitContainersDone(ctx, function) if err != nil { - return errors.Wrap(err, "Function init containers check failed"), functionconfig.FunctionStateUnhealthy + return functionconfig.FunctionStateUnhealthy, errors.Wrap(err, "Function init containers check failed") } if !initContainersDone { lc.logger.DebugWithCtx(ctx, @@ -412,12 +411,12 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, if lastEvent := lc.getFunctionIngressLastWarningEvent(ctx, function); lastEvent != "" { errMessage += " Last warning event:" + lastEvent } - return errors.New(errMessage), functionconfig.FunctionStateUnhealthy + return functionconfig.FunctionStateUnhealthy, errors.New(errMessage) } // check deployment readiness if !deploymentReady { - err, functionState := lc.waitFunctionDeploymentReadiness(ctx, + functionState, err := lc.waitFunctionDeploymentReadiness(ctx, function, functionResourcesCreateOrUpdateTimestamp) @@ -442,7 +441,7 @@ func (lc *lazyClient) WaitAvailable(ctx context.Context, if lastEvent := lc.getFunctionDeploymentOrPodLastWarningEvent(ctx, function); lastEvent != "" { errMessage += " Last warning event:" + lastEvent } - return errors.Wrap(err, errMessage), functionState + return functionState, errors.Wrap(err, errMessage) } deploymentReady = true @@ -600,13 +599,13 @@ func (lc *lazyClient) waitFunctionIngressReadiness(ctx context.Context, func (lc *lazyClient) waitFunctionDeploymentReadiness(ctx context.Context, function *nuclioio.NuclioFunction, - functionResourcesCreateOrUpdateTimestamp time.Time) (error, functionconfig.FunctionState) { + functionResourcesCreateOrUpdateTimestamp time.Time) (functionconfig.FunctionState, error) { // get the deployment. if it doesn't exist yet, retry a bit later functionDeployment, err := lc.getFunctionDeployment(ctx, function) if err != nil { - return errors.Wrap(err, "Failed to get function deployment"), "" + return "", errors.Wrap(err, "Failed to get function deployment") } // find the condition whose type is Available - that's the one we want to examine @@ -622,7 +621,7 @@ func (lc *lazyClient) waitFunctionDeploymentReadiness(ctx context.Context, "Deployment is available", "reason", deploymentCondition.Reason, "functionName", function.Name) - return nil, functionconfig.FunctionStateReady + return functionconfig.FunctionStateReady, nil } lc.logger.DebugWithCtx(ctx, @@ -647,18 +646,18 @@ func (lc *lazyClient) waitFunctionDeploymentReadiness(ctx context.Context, LabelSelector: common.CompileListFunctionPodsLabelSelector(function.Name), }) if err != nil { - return errors.Wrap(err, "Failed to list function pods"), "" + return "", errors.Wrap(err, "Failed to list function pods") } // fail-fast mechanism if failedStatus, err := lc.resolveFailFast(ctx, podsList, functionResourcesCreateOrUpdateTimestamp); err != nil { - return errors.Wrapf(err, "NuclioFunction deployment failed"), failedStatus + return failedStatus, errors.Wrapf(err, "NuclioFunction deployment failed") } } - return errors.New("Function deployment is not ready yet"), "" + return "", errors.New("Function deployment is not ready yet") } // getFunctionDeployment returns function's deployment @@ -1072,7 +1071,7 @@ func (lc *lazyClient) createOrUpdateConfigMap(ctx context.Context, } configMapIsDeleting := func(resource interface{}) bool { - return (resource).(*v1.ConfigMap).ObjectMeta.DeletionTimestamp != nil + return (resource).(*v1.ConfigMap).DeletionTimestamp != nil } createConfigMap := func() (interface{}, error) { @@ -1120,7 +1119,7 @@ func (lc *lazyClient) createOrUpdateService(ctx context.Context, } serviceIsDeleting := func(resource interface{}) bool { - return (resource).(*v1.Service).ObjectMeta.DeletionTimestamp != nil + return (resource).(*v1.Service).DeletionTimestamp != nil } createService := func() (interface{}, error) { @@ -1211,7 +1210,7 @@ func (lc *lazyClient) createOrUpdateDeployment(ctx context.Context, } deploymentIsDeleting := func(resource interface{}) bool { - return (resource).(*appsv1.Deployment).ObjectMeta.DeletionTimestamp != nil + return (resource).(*appsv1.Deployment).DeletionTimestamp != nil } if function.Spec.ImagePullSecrets != "" { @@ -1531,7 +1530,7 @@ func (lc *lazyClient) createOrUpdateHorizontalPodAutoscaler(ctx context.Context, } horizontalPodAutoscalerIsDeleting := func(resource interface{}) bool { - return (resource).(*autosv2.HorizontalPodAutoscaler).ObjectMeta.DeletionTimestamp != nil + return (resource).(*autosv2.HorizontalPodAutoscaler).DeletionTimestamp != nil } createHorizontalPodAutoscaler := func() (interface{}, error) { @@ -1628,7 +1627,7 @@ func (lc *lazyClient) createOrUpdateIngress(ctx context.Context, } ingressIsDeleting := func(resource interface{}) bool { - return (resource).(*networkingv1.Ingress).ObjectMeta.DeletionTimestamp != nil + return (resource).(*networkingv1.Ingress).DeletionTimestamp != nil } createIngress := func() (interface{}, error) { @@ -1760,7 +1759,7 @@ func (lc *lazyClient) createOrUpdateCronJob(ctx context.Context, } cronJobIsDeleting := func(resource interface{}) bool { - return (resource).(*batchv1.CronJob).ObjectMeta.DeletionTimestamp != nil + return (resource).(*batchv1.CronJob).DeletionTimestamp != nil } // Prepare the new cron job object @@ -2003,7 +2002,7 @@ func (lc *lazyClient) populateServiceSpec(ctx context.Context, // 3. this is an existing service (spec.Ports is not an empty list) and node port was previously configured, but // the trigger type has been updated to ClusterIP(or any other type which isn't NodePort). if len(spec.Ports) == 0 || - !(spec.Ports[0].NodePort != 0 && function.Spec.GetHTTPPort() == 0) || + (spec.Ports[0].NodePort == 0 || function.Spec.GetHTTPPort() != 0) || (spec.Ports[0].NodePort != 0 && !serviceTypeIsNodePort) { spec.Ports = []v1.ServicePort{ @@ -2410,7 +2409,7 @@ func (lc *lazyClient) addIngressToSpec(ctx context.Context, spec.IngressClassName = &ingress.IngressClassName } - ingressRule.IngressRuleValue.HTTP = &networkingv1.HTTPIngressRuleValue{} + ingressRule.HTTP = &networkingv1.HTTPIngressRuleValue{} // populate the ingress rule value for _, path := range ingress.Paths { @@ -2438,7 +2437,7 @@ func (lc *lazyClient) addIngressToSpec(ctx context.Context, } // add path - ingressRule.IngressRuleValue.HTTP.Paths = append(ingressRule.IngressRuleValue.HTTP.Paths, httpIngressPath) + ingressRule.HTTP.Paths = append(ingressRule.HTTP.Paths, httpIngressPath) // add TLS if such exists if ingress.TLS.SecretName != "" { diff --git a/pkg/platform/kube/functionres/lazy_test.go b/pkg/platform/kube/functionres/lazy_test.go index 4c88b28b7c5..6c72893ce02 100644 --- a/pkg/platform/kube/functionres/lazy_test.go +++ b/pkg/platform/kube/functionres/lazy_test.go @@ -430,7 +430,7 @@ func (suite *lazyTestSuite) TestNoChanges() { suite.Require().NotNil(updatedDeploymentInstance) // make sure access key is still present in the function spec volume options - suite.Require().Contains(function.Spec.Volumes[0].Volume.VolumeSource.FlexVolume.Options, "accessKey") + suite.Require().Contains(function.Spec.Volumes[0].Volume.FlexVolume.Options, "accessKey") // make sure flex volume doesn't contain access key for _, volume := range updatedDeploymentInstance.Spec.Template.Spec.Volumes { diff --git a/pkg/platform/kube/functionres/types.go b/pkg/platform/kube/functionres/types.go index 7bce715c228..fea57049fb9 100644 --- a/pkg/platform/kube/functionres/types.go +++ b/pkg/platform/kube/functionres/types.go @@ -52,7 +52,7 @@ type Client interface { CreateOrUpdate(context.Context, *nuclioio.NuclioFunction, string) (Resources, error) // WaitAvailable waits until the resources are ready - WaitAvailable(context.Context, *nuclioio.NuclioFunction, time.Time) (error, functionconfig.FunctionState) + WaitAvailable(context.Context, *nuclioio.NuclioFunction, time.Time) (functionconfig.FunctionState, error) // Delete deletes resources Delete(context.Context, string, string) error diff --git a/pkg/platform/kube/ingress/ingress.go b/pkg/platform/kube/ingress/ingress.go index a06b469fd7c..7d925436424 100644 --- a/pkg/platform/kube/ingress/ingress.go +++ b/pkg/platform/kube/ingress/ingress.go @@ -405,10 +405,7 @@ func (m *Manager) compileDexAuthAnnotations(spec Spec) (map[string]string, error oauth2ProxyURL = spec.Authentication.DexAuth.Oauth2ProxyURL } - addSignInAnnotation := false - if spec.Authentication != nil && spec.Authentication.DexAuth != nil && spec.Authentication.DexAuth.RedirectUnauthorizedToSignIn { - addSignInAnnotation = true - } + addSignInAnnotation := spec.Authentication != nil && spec.Authentication.DexAuth != nil && spec.Authentication.DexAuth.RedirectUnauthorizedToSignIn if oauth2ProxyURL == "" { return nil, errors.New("Oauth2 proxy URL is missing") diff --git a/pkg/platform/kube/monitoring/test/function_test.go b/pkg/platform/kube/monitoring/test/function_test.go index 7eea14bc1ea..9d4df47e5f1 100644 --- a/pkg/platform/kube/monitoring/test/function_test.go +++ b/pkg/platform/kube/monitoring/test/function_test.go @@ -46,7 +46,7 @@ type FunctionMonitoringTestSuite struct { func (suite *FunctionMonitoringTestSuite) SetupSuite() { suite.KubeTestSuite.SetupSuite() - suite.KubeTestSuite.Ctx = context.Background() + suite.Ctx = context.Background() // keep it for suite teardown suite.oldPostDeploymentMonitoringBlockingInterval = monitoring.PostDeploymentMonitoringBlockingInterval diff --git a/pkg/platform/kube/platform.go b/pkg/platform/kube/platform.go index a9245467e0b..f2f4d94b9fd 100644 --- a/pkg/platform/kube/platform.go +++ b/pkg/platform/kube/platform.go @@ -510,12 +510,12 @@ func (p *Platform) EnrichFunctionConfig(ctx context.Context, functionConfig *fun // GetFunctions will return deployed functions func (p *Platform) GetFunctions(ctx context.Context, getFunctionsOptions *platform.GetFunctionsOptions) ([]platform.Function, error) { - projectName, err := p.Platform.ResolveProjectNameFromLabelsStr(getFunctionsOptions.Labels) + projectName, err := p.ResolveProjectNameFromLabelsStr(getFunctionsOptions.Labels) if err != nil { return nil, errors.Wrap(err, "") } - if err := p.Platform.EnsureProjectRead(projectName, &getFunctionsOptions.PermissionOptions); err != nil { + if err := p.EnsureProjectRead(projectName, &getFunctionsOptions.PermissionOptions); err != nil { return nil, errors.Wrap(err, "Failed to ensure project read permission") } @@ -524,7 +524,7 @@ func (p *Platform) GetFunctions(ctx context.Context, getFunctionsOptions *platfo return nil, errors.Wrap(err, "Failed to get functions") } - functions, err = p.Platform.FilterFunctionsByPermissions(ctx, &getFunctionsOptions.PermissionOptions, functions) + functions, err = p.FilterFunctionsByPermissions(ctx, &getFunctionsOptions.PermissionOptions, functions) if err != nil { return nil, errors.Wrap(err, "Failed to filter functions by permissions") } @@ -682,7 +682,7 @@ func (p *Platform) ProxyFunctionLogs(ctx context.Context, func (p *Platform) GetFunctionActiveReplicaNames(ctx context.Context, function platform.Function, permissionOptions opa.PermissionOptions) ([]string, error) { - functions, err := p.Platform.FilterFunctionsByPermissions(ctx, &permissionOptions, []platform.Function{function}) + functions, err := p.FilterFunctionsByPermissions(ctx, &permissionOptions, []platform.Function{function}) if err != nil { return nil, errors.Wrap(err, "Failed to filter functions by permissions") } @@ -709,7 +709,7 @@ func (p *Platform) GetFunctionActiveReplicaNames(ctx context.Context, func (p *Platform) GetFunctionAllReplicaNames(ctx context.Context, function platform.Function, permissionOptions opa.PermissionOptions, timeFilter *platform.TimeFilter) ([]string, error) { - functions, err := p.Platform.FilterFunctionsByPermissions(ctx, &permissionOptions, []platform.Function{function}) + functions, err := p.FilterFunctionsByPermissions(ctx, &permissionOptions, []platform.Function{function}) if err != nil { return nil, errors.Wrap(err, "Failed to filter functions by permissions") } @@ -805,7 +805,7 @@ func (p *Platform) DeleteProject(ctx context.Context, deleteProjectOptions *plat deleteProjectOptions.AuthSession = &auth.NopSession{} } - if err := p.Platform.ValidateDeleteProjectOptions(ctx, deleteProjectOptions); err != nil { + if err := p.ValidateDeleteProjectOptions(ctx, deleteProjectOptions); err != nil { return errors.Wrap(err, "Failed to validate delete project options") } @@ -825,7 +825,7 @@ func (p *Platform) DeleteProject(ctx context.Context, deleteProjectOptions *plat } if deleteProjectOptions.WaitForResourcesDeletionCompletion { - if err := p.Platform.WaitForProjectResourcesDeletion(ctx, + if err := p.WaitForProjectResourcesDeletion(ctx, &deleteProjectOptions.Meta, deleteProjectOptions.WaitForResourcesDeletionCompletionDuration); err != nil { return errors.Wrap(err, "Failed waiting for project resources deletion") @@ -852,7 +852,7 @@ func (p *Platform) GetProjects(ctx context.Context, return nil, errors.Wrap(err, "Failed getting projects") } - filteredProjectList, err := p.Platform.FilterProjectsByPermissions( + filteredProjectList, err := p.FilterProjectsByPermissions( ctx, &getProjectsOptions.PermissionOptions, projects) @@ -1091,7 +1091,7 @@ func (p *Platform) GetAPIGateways(ctx context.Context, getAPIGatewaysOptions *pl // which to invoke functions func (p *Platform) CreateFunctionEvent(ctx context.Context, createFunctionEventOptions *platform.CreateFunctionEventOptions) error { - if err := p.Platform.EnrichFunctionEvent(ctx, &createFunctionEventOptions.FunctionEventConfig); err != nil { + if err := p.EnrichFunctionEvent(ctx, &createFunctionEventOptions.FunctionEventConfig); err != nil { return errors.Wrap(err, "Failed to enrich function event") } @@ -1132,7 +1132,7 @@ func (p *Platform) UpdateFunctionEvent(ctx context.Context, updateFunctionEventO return errors.Wrap(err, "Failed to get a function event") } - if err := p.Platform.EnrichFunctionEvent(ctx, &updateFunctionEventOptions.FunctionEventConfig); err != nil { + if err := p.EnrichFunctionEvent(ctx, &updateFunctionEventOptions.FunctionEventConfig); err != nil { return errors.Wrap(err, "Failed to enrich function event") } @@ -1269,7 +1269,7 @@ func (p *Platform) GetFunctionEvents(ctx context.Context, getFunctionEventsOptio platformFunctionEvents = append(platformFunctionEvents, newFunctionEvent) } - return p.Platform.FilterFunctionEventsByPermissions(ctx, + return p.FilterFunctionEventsByPermissions(ctx, &getFunctionEventsOptions.PermissionOptions, platformFunctionEvents) } @@ -1928,7 +1928,7 @@ func (p *Platform) enrichAndValidateFunctionConfig(ctx context.Context, function if err := p.EnrichFunctionConfig(ctx, functionConfig); err != nil { return errors.Wrap(err, "Failed to enrich a function configuration") } - return p.Platform.ValidateFunctionConfigWithRetry(ctx, functionConfig, autofix) + return p.ValidateFunctionConfigWithRetry(ctx, functionConfig, autofix) } func (p *Platform) validateServiceType(functionConfig *functionconfig.Config) error { diff --git a/pkg/platform/kube/platform_test.go b/pkg/platform/kube/platform_test.go index 61fa2af958a..9f1d6ad7fb5 100644 --- a/pkg/platform/kube/platform_test.go +++ b/pkg/platform/kube/platform_test.go @@ -33,7 +33,6 @@ import ( "github.com/nuclio/nuclio/pkg/platform" "github.com/nuclio/nuclio/pkg/platform/abstract" "github.com/nuclio/nuclio/pkg/platform/kube/apis/nuclio.io/v1beta1" - nuclioio "github.com/nuclio/nuclio/pkg/platform/kube/apis/nuclio.io/v1beta1" "github.com/nuclio/nuclio/pkg/platform/kube/client" "github.com/nuclio/nuclio/pkg/platform/kube/client/clientset/mocks" "github.com/nuclio/nuclio/pkg/platform/kube/ingress" @@ -165,7 +164,7 @@ func (suite *ProjectKubePlatformTestSuite) TestGetProjectsCache() { suite.ctx, mock.Anything, mock.Anything). - Return(&nuclioio.NuclioProject{}, nil). + Return(&v1beta1.NuclioProject{}, nil). Once() defer suite.nuclioProjectInterfaceMock.AssertExpectations(suite.T()) @@ -205,7 +204,7 @@ func (suite *ProjectKubePlatformTestSuite) TestGetProjectsCache() { mock.Anything, mock.Anything). Return(&v1beta1.NuclioProjectList{ - Items: []nuclioio.NuclioProject{ + Items: []v1beta1.NuclioProject{ { ObjectMeta: metav1.ObjectMeta{ Namespace: suite.Namespace, diff --git a/pkg/platform/local/platform.go b/pkg/platform/local/platform.go index 80aa1878e10..d86941c2f28 100644 --- a/pkg/platform/local/platform.go +++ b/pkg/platform/local/platform.go @@ -363,12 +363,12 @@ func (p *Platform) CreateFunction(ctx context.Context, createFunctionOptions *pl func (p *Platform) GetFunctions(ctx context.Context, getFunctionsOptions *platform.GetFunctionsOptions) ([]platform.Function, error) { - projectName, err := p.Platform.ResolveProjectNameFromLabelsStr(getFunctionsOptions.Labels) + projectName, err := p.ResolveProjectNameFromLabelsStr(getFunctionsOptions.Labels) if err != nil { return nil, errors.Wrap(err, "") } - if err := p.Platform.EnsureProjectRead(projectName, &getFunctionsOptions.PermissionOptions); err != nil { + if err := p.EnsureProjectRead(projectName, &getFunctionsOptions.PermissionOptions); err != nil { return nil, errors.Wrap(err, "Failed to ensure project read permission") } @@ -377,7 +377,7 @@ func (p *Platform) GetFunctions(ctx context.Context, return nil, errors.Wrap(err, "Failed to read functions from a local store") } - functions, err = p.Platform.FilterFunctionsByPermissions(ctx, &getFunctionsOptions.PermissionOptions, functions) + functions, err = p.FilterFunctionsByPermissions(ctx, &getFunctionsOptions.PermissionOptions, functions) if err != nil { return nil, errors.Wrap(err, "Failed to filter functions by permissions") } @@ -587,7 +587,7 @@ func (p *Platform) UpdateProject(ctx context.Context, updateProjectOptions *plat // DeleteProject will delete an existing project func (p *Platform) DeleteProject(ctx context.Context, deleteProjectOptions *platform.DeleteProjectOptions) error { - if err := p.Platform.ValidateDeleteProjectOptions(ctx, deleteProjectOptions); err != nil { + if err := p.ValidateDeleteProjectOptions(ctx, deleteProjectOptions); err != nil { return errors.Wrap(err, "Failed to validate delete project options") } @@ -611,7 +611,7 @@ func (p *Platform) GetProjects(ctx context.Context, getProjectsOptions *platform return nil, errors.Wrap(err, "Failed getting projects") } - return p.Platform.FilterProjectsByPermissions(ctx, + return p.FilterProjectsByPermissions(ctx, &getProjectsOptions.PermissionOptions, projects) } @@ -619,7 +619,7 @@ func (p *Platform) GetProjects(ctx context.Context, getProjectsOptions *platform // CreateFunctionEvent will create a new function event that can later be used as a template from // which to invoke functions func (p *Platform) CreateFunctionEvent(ctx context.Context, createFunctionEventOptions *platform.CreateFunctionEventOptions) error { - if err := p.Platform.EnrichFunctionEvent(ctx, &createFunctionEventOptions.FunctionEventConfig); err != nil { + if err := p.EnrichFunctionEvent(ctx, &createFunctionEventOptions.FunctionEventConfig); err != nil { return errors.Wrap(err, "Failed to enrich function event") } @@ -642,7 +642,7 @@ func (p *Platform) CreateFunctionEvent(ctx context.Context, createFunctionEventO // UpdateFunctionEvent will update a previously existing function event func (p *Platform) UpdateFunctionEvent(ctx context.Context, updateFunctionEventOptions *platform.UpdateFunctionEventOptions) error { - if err := p.Platform.EnrichFunctionEvent(ctx, &updateFunctionEventOptions.FunctionEventConfig); err != nil { + if err := p.EnrichFunctionEvent(ctx, &updateFunctionEventOptions.FunctionEventConfig); err != nil { return errors.Wrap(err, "Failed to enrich function event") } @@ -715,7 +715,7 @@ func (p *Platform) GetFunctionEvents(ctx context.Context, getFunctionEventsOptio return nil, errors.Wrap(err, "Failed to read function events from a local store") } - return p.Platform.FilterFunctionEventsByPermissions(ctx, + return p.FilterFunctionEventsByPermissions(ctx, &getFunctionEventsOptions.PermissionOptions, functionEvents) } @@ -855,7 +855,7 @@ func (p *Platform) ValidateFunctionContainersHealthiness(ctx context.Context) { functionconfig.FunctionStateError, functionconfig.FunctionStateUnhealthy, }) && functionStatus.Message == string(common.FunctionStateMessageUnhealthy) - if !(functionIsReady || functionWasSetAsUnhealthy) || functionConfig.Spec.Disable { + if (!functionIsReady && !functionWasSetAsUnhealthy) || functionConfig.Spec.Disable { // cannot be monitored continue @@ -1402,7 +1402,7 @@ func (p *Platform) enrichAndValidateFunctionConfig(ctx context.Context, function return errors.Wrap(err, "Failed to enrich a function configuration") } - return p.Platform.ValidateFunctionConfigWithRetry(ctx, functionConfig, autofix) + return p.ValidateFunctionConfigWithRetry(ctx, functionConfig, autofix) } func (p *Platform) populateFunctionInvocationStatus(functionInvocation *functionconfig.Status, diff --git a/pkg/platform/local/test/platform_test.go b/pkg/platform/local/test/platform_test.go index 10744bce602..b7922f6f974 100644 --- a/pkg/platform/local/test/platform_test.go +++ b/pkg/platform/local/test/platform_test.go @@ -64,7 +64,7 @@ func (suite *TestSuite) TestRunFunctionContainerWithCustomRestartPolicy() { restartEventsFrom := time.Now() functionContainerMaximumRetryCount := 1 functionPath := []string{suite.GetTestFunctionsDir(), "common", "context-init-fail", "python", "contextinitfail.py"} - createFunctionOptions := suite.TestSuite.GetDeployOptions("restartable", filepath.Join(functionPath...)) + createFunctionOptions := suite.GetDeployOptions("restartable", filepath.Join(functionPath...)) createFunctionOptions.FunctionConfig.Spec.ReadinessTimeoutSeconds = 10 createFunctionOptions.FunctionConfig.Meta.Namespace = suite.namespace @@ -372,7 +372,7 @@ func (suite *TestSuite) TestDeployFunctionDisablePublishingPorts() { func (suite *TestSuite) getDeployOptions(functionName string) *platform.CreateFunctionOptions { functionPath := []string{suite.GetTestFunctionsDir(), "common", "reverser", "python", "reverser.py"} - createFunctionOptions := suite.TestSuite.GetDeployOptions(functionName, filepath.Join(functionPath...)) + createFunctionOptions := suite.GetDeployOptions(functionName, filepath.Join(functionPath...)) createFunctionOptions.FunctionConfig.Spec.Build.NoBaseImagesPull = true return createFunctionOptions } diff --git a/pkg/processor/build/runtime/dotnetcore/test/dotnetcore_test.go b/pkg/processor/build/runtime/dotnetcore/test/dotnetcore_test.go index 5bb91cd5464..29d64c8a38c 100644 --- a/pkg/processor/build/runtime/dotnetcore/test/dotnetcore_test.go +++ b/pkg/processor/build/runtime/dotnetcore/test/dotnetcore_test.go @@ -33,8 +33,8 @@ type TestSuite struct { func (suite *TestSuite) SetupSuite() { suite.TestSuite.SetupSuite() - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "dotnetcore" + suite.RuntimeSuite = suite + suite.ArchivePattern = "dotnetcore" } func (suite *TestSuite) GetFunctionInfo(functionName string) buildsuite.FunctionInfo { diff --git a/pkg/processor/build/runtime/golang/test/golang_test.go b/pkg/processor/build/runtime/golang/test/golang_test.go index 571fa47553a..1c4712287e9 100644 --- a/pkg/processor/build/runtime/golang/test/golang_test.go +++ b/pkg/processor/build/runtime/golang/test/golang_test.go @@ -39,8 +39,8 @@ func (suite *testSuite) SetupSuite() { suite.TestSuite.SetupSuite() suite.Runtime = "golang" - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "golang" + suite.RuntimeSuite = suite + suite.ArchivePattern = "golang" } func (suite *testSuite) TestBuildWithCompilationError() { diff --git a/pkg/processor/build/runtime/java/test/java_test.go b/pkg/processor/build/runtime/java/test/java_test.go index 7fb03ed22f8..7c14f0d8694 100644 --- a/pkg/processor/build/runtime/java/test/java_test.go +++ b/pkg/processor/build/runtime/java/test/java_test.go @@ -33,15 +33,15 @@ type TestSuite struct { func (suite *TestSuite) SetupSuite() { suite.TestSuite.SetupSuite() - suite.TestSuite.Runtime = "java" + suite.Runtime = "java" - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "java" + suite.RuntimeSuite = suite + suite.ArchivePattern = "java" } func (suite *TestSuite) GetFunctionInfo(functionName string) buildsuite.FunctionInfo { functionInfo := buildsuite.FunctionInfo{ - Runtime: suite.TestSuite.Runtime, + Runtime: suite.Runtime, } switch functionName { diff --git a/pkg/processor/build/runtime/nodejs/test/nodejs_test.go b/pkg/processor/build/runtime/nodejs/test/nodejs_test.go index fff07dd62ee..3768c286881 100644 --- a/pkg/processor/build/runtime/nodejs/test/nodejs_test.go +++ b/pkg/processor/build/runtime/nodejs/test/nodejs_test.go @@ -34,8 +34,8 @@ type TestSuite struct { func (suite *TestSuite) SetupSuite() { suite.TestSuite.SetupSuite() - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "nodejs" + suite.RuntimeSuite = suite + suite.ArchivePattern = "nodejs" } func (suite *TestSuite) GetFunctionInfo(functionName string) buildsuite.FunctionInfo { diff --git a/pkg/processor/build/runtime/python/test/python_test.go b/pkg/processor/build/runtime/python/test/python_test.go index 0a56fbfa7cc..cba8e14deeb 100644 --- a/pkg/processor/build/runtime/python/test/python_test.go +++ b/pkg/processor/build/runtime/python/test/python_test.go @@ -46,8 +46,8 @@ func (suite *TestSuite) SetupSuite() { suite.ctx = context.Background() - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "python" + suite.RuntimeSuite = suite + suite.ArchivePattern = "python" suite.Runtime = suite.runtime } diff --git a/pkg/processor/build/runtime/ruby/test/ruby_test.go b/pkg/processor/build/runtime/ruby/test/ruby_test.go index 0e2fe768acf..cfe3d92cb22 100644 --- a/pkg/processor/build/runtime/ruby/test/ruby_test.go +++ b/pkg/processor/build/runtime/ruby/test/ruby_test.go @@ -33,8 +33,8 @@ type TestSuite struct { func (suite *TestSuite) SetupSuite() { suite.TestSuite.SetupSuite() - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "ruby" + suite.RuntimeSuite = suite + suite.ArchivePattern = "ruby" } func (suite *TestSuite) GetFunctionInfo(functionName string) buildsuite.FunctionInfo { diff --git a/pkg/processor/build/runtime/shell/test/shell_test.go b/pkg/processor/build/runtime/shell/test/shell_test.go index 3c64f69ccb1..298ec80f690 100644 --- a/pkg/processor/build/runtime/shell/test/shell_test.go +++ b/pkg/processor/build/runtime/shell/test/shell_test.go @@ -35,8 +35,8 @@ type TestSuite struct { func (suite *TestSuite) SetupSuite() { suite.TestSuite.SetupSuite() - suite.TestSuite.RuntimeSuite = suite - suite.TestSuite.ArchivePattern = "shell" + suite.RuntimeSuite = suite + suite.ArchivePattern = "shell" } func (suite *TestSuite) TestBuildBinaryWithStdin() { diff --git a/pkg/processor/build/test/build_test.go b/pkg/processor/build/test/build_test.go index b8ca8d1a527..52ecaef2ef9 100644 --- a/pkg/processor/build/test/build_test.go +++ b/pkg/processor/build/test/build_test.go @@ -114,7 +114,7 @@ func (suite *testSuite) TestBuildFunctionFromSourceCodeMaintainsSource() { suite.DeployFunction(createFunctionOptions, func(deployResult *platform.CreateFunctionResult) bool { // get the function - functions, err := suite.Platform.GetFunctions(suite.TestSuite.Ctx, &platform.GetFunctionsOptions{ + functions, err := suite.Platform.GetFunctions(suite.Ctx, &platform.GetFunctionsOptions{ Name: createFunctionOptions.FunctionConfig.Meta.Name, Namespace: createFunctionOptions.FunctionConfig.Meta.Namespace, }) @@ -150,7 +150,7 @@ func (suite *testSuite) TestBuildFunctionFromSourceCodeDeployOnceNeverBuild() { suite.DeployFunctionExpectError(createFunctionOptions, func(deployResult *platform.CreateFunctionResult) bool { // nolint: errcheck // get the function - functions, err := suite.Platform.GetFunctions(suite.TestSuite.Ctx, &platform.GetFunctionsOptions{ + functions, err := suite.Platform.GetFunctions(suite.Ctx, &platform.GetFunctionsOptions{ Name: createFunctionOptions.FunctionConfig.Meta.Name, Namespace: createFunctionOptions.FunctionConfig.Meta.Namespace, }) @@ -188,7 +188,7 @@ func (suite *testSuite) TestBuildFunctionFromSourceCodeNeverBuildRedeploy() { afterFirstDeploy := func(deployResult *platform.CreateFunctionResult) bool { // get the function - functions, err := suite.Platform.GetFunctions(suite.TestSuite.Ctx, &platform.GetFunctionsOptions{ + functions, err := suite.Platform.GetFunctions(suite.Ctx, &platform.GetFunctionsOptions{ Name: createFunctionOptions.FunctionConfig.Meta.Name, Namespace: createFunctionOptions.FunctionConfig.Meta.Namespace, }) @@ -208,7 +208,7 @@ func (suite *testSuite) TestBuildFunctionFromSourceCodeNeverBuildRedeploy() { afterSecondDeploy := func(deployResult *platform.CreateFunctionResult) bool { // get the function - functions, err := suite.Platform.GetFunctions(suite.TestSuite.Ctx, &platform.GetFunctionsOptions{ + functions, err := suite.Platform.GetFunctions(suite.Ctx, &platform.GetFunctionsOptions{ Name: createFunctionOptions.FunctionConfig.Meta.Name, Namespace: createFunctionOptions.FunctionConfig.Meta.Namespace, }) @@ -240,7 +240,7 @@ func (suite *testSuite) TestBuildFunctionFromFileExpectSourceCodePopulated() { suite.DeployFunction(createFunctionOptions, func(deployResult *platform.CreateFunctionResult) bool { // get the function - functions, err := suite.Platform.GetFunctions(suite.TestSuite.Ctx, &platform.GetFunctionsOptions{ + functions, err := suite.Platform.GetFunctions(suite.Ctx, &platform.GetFunctionsOptions{ Name: createFunctionOptions.FunctionConfig.Meta.Name, Namespace: createFunctionOptions.FunctionConfig.Meta.Namespace, }) @@ -528,7 +528,7 @@ func (suite *testSuite) TestBuildFuncFromRemoteArchiveRedeploy() { ExpectedResponseBody: "dcba", }) - suite.Equal(deployResult.CreateFunctionBuildResult.UpdatedFunctionConfig.Spec.Build.CodeEntryType, "archive") + suite.Equal(deployResult.UpdatedFunctionConfig.Spec.Build.CodeEntryType, "archive") // validate that when redeploying it works and the function uses another image than before redeployFunctionOptions := &platform.CreateFunctionOptions{ @@ -571,7 +571,7 @@ func (suite *testSuite) TestBuildFuncFromLocalArchiveRedeployUsesSameImage() { ExpectedResponseBody: "hello world", }) - suite.Equal(deployResult.CreateFunctionBuildResult.UpdatedFunctionConfig.Spec.Build.CodeEntryType, "image") + suite.Equal(deployResult.UpdatedFunctionConfig.Spec.Build.CodeEntryType, "image") // validate that when redeploying it works and the function uses the same image as before redeployFunctionOptions := &platform.CreateFunctionOptions{ @@ -647,7 +647,7 @@ func (suite *testSuite) TestBuildWithFlags() { } func (suite *testSuite) TestGenerateProcessorDockerfile() { - newPlatform, err := local.NewPlatform(suite.TestSuite.Ctx, suite.Logger, &platformconfig.Config{}, "") + newPlatform, err := local.NewPlatform(suite.Ctx, suite.Logger, &platformconfig.Config{}, "") suite.Require().NoErrorf(err, "Instantiating Platform failed: %s", err) builder, err := build.NewBuilder(suite.Logger, newPlatform, nil) diff --git a/pkg/processor/build/util/copy.go b/pkg/processor/build/util/copy.go index 42b9e6a730c..c94d9807de3 100644 --- a/pkg/processor/build/util/copy.go +++ b/pkg/processor/build/util/copy.go @@ -17,7 +17,6 @@ limitations under the License. package util import ( - "fmt" "io" "os" "path" @@ -112,7 +111,7 @@ func CopyDir(source string, dest string) (bool, error) { } if !fi.IsDir() { - return false, fmt.Errorf("Source (%q) is not a directory", source) + return false, errors.Errorf("Source (%q) is not a directory", source) } // create dest dir diff --git a/pkg/processor/databinding/eventhub/types.go b/pkg/processor/databinding/eventhub/types.go index 9514ecee61c..a2cffb333ea 100644 --- a/pkg/processor/databinding/eventhub/types.go +++ b/pkg/processor/databinding/eventhub/types.go @@ -39,7 +39,7 @@ func NewConfiguration(id string, databindingConfiguration *functionconfig.DataBi newConfiguration.Configuration = *databinding.NewConfiguration(id, databindingConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/databinding/v3io/types.go b/pkg/processor/databinding/v3io/types.go index 5a5f44fd256..791654920ac 100644 --- a/pkg/processor/databinding/v3io/types.go +++ b/pkg/processor/databinding/v3io/types.go @@ -38,7 +38,7 @@ func NewConfiguration(id string, databindingConfiguration *functionconfig.DataBi newConfiguration.Configuration = *databinding.NewConfiguration(id, databindingConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/eventprocessor/singleton.go b/pkg/processor/eventprocessor/singleton.go index 5db32cc479c..61f110291f5 100644 --- a/pkg/processor/eventprocessor/singleton.go +++ b/pkg/processor/eventprocessor/singleton.go @@ -17,11 +17,11 @@ limitations under the License. package eventprocessor import ( - "errors" "time" "github.com/nuclio/nuclio/pkg/processor/statistics" + "github.com/nuclio/errors" "github.com/nuclio/logger" ) diff --git a/pkg/processor/metricsink/appinsights/types.go b/pkg/processor/metricsink/appinsights/types.go index 2fe432aa63f..200a4fa931b 100644 --- a/pkg/processor/metricsink/appinsights/types.go +++ b/pkg/processor/metricsink/appinsights/types.go @@ -43,7 +43,7 @@ func NewConfiguration(name string, metricSinkConfiguration *platformconfig.Metri newConfiguration.Configuration = *metricsink.NewConfiguration(name, metricSinkConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/metricsink/prometheus/pull/metricsink.go b/pkg/processor/metricsink/prometheus/pull/metricsink.go index 07afb67434a..300d8af6885 100644 --- a/pkg/processor/metricsink/prometheus/pull/metricsink.go +++ b/pkg/processor/metricsink/prometheus/pull/metricsink.go @@ -202,8 +202,8 @@ func (ms *MetricSink) getInstanceName(processorConfiguration *processor.Configur var instanceNameTemplateBuffer bytes.Buffer if err := instanceNameTemplate.Execute(&instanceNameTemplateBuffer, &map[string]interface{}{ - "Namespace": processorConfiguration.Config.Meta.Namespace, - "Name": processorConfiguration.Config.Meta.Name, + "Namespace": processorConfiguration.Meta.Namespace, + "Name": processorConfiguration.Meta.Name, }); err != nil { return "", errors.Wrap(err, "Failed to execute instanceName template") } diff --git a/pkg/processor/metricsink/prometheus/pull/types.go b/pkg/processor/metricsink/prometheus/pull/types.go index 1018373f31d..2222f221008 100644 --- a/pkg/processor/metricsink/prometheus/pull/types.go +++ b/pkg/processor/metricsink/prometheus/pull/types.go @@ -38,7 +38,7 @@ func NewConfiguration(name string, metricSinkConfiguration *platformconfig.Metri newConfiguration.Configuration = *metricsink.NewConfiguration(name, metricSinkConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/metricsink/prometheus/push/types.go b/pkg/processor/metricsink/prometheus/push/types.go index 040683965dc..36274c4ae60 100644 --- a/pkg/processor/metricsink/prometheus/push/types.go +++ b/pkg/processor/metricsink/prometheus/push/types.go @@ -17,7 +17,6 @@ limitations under the License. package prometheuspush import ( - "fmt" "time" "github.com/nuclio/nuclio/pkg/platformconfig" @@ -42,7 +41,7 @@ func NewConfiguration(name string, metricSinkConfiguration *platformconfig.Metri newConfiguration.Configuration = *metricsink.NewConfiguration(name, metricSinkConfiguration) // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } @@ -55,12 +54,12 @@ func NewConfiguration(name string, metricSinkConfiguration *platformconfig.Metri // verify job name passed if newConfiguration.JobName == "" { - return nil, fmt.Errorf("Job name is required for metric sink %s", name) + return nil, errors.Errorf("Job name is required for metric sink %s", name) } // verify instance name passed if newConfiguration.InstanceName == "" { - return nil, fmt.Errorf("Instance name is required for metric sink %s", name) + return nil, errors.Errorf("Instance name is required for metric sink %s", name) } return &newConfiguration, nil diff --git a/pkg/processor/runtime/dotnetcore/runtime.go b/pkg/processor/runtime/dotnetcore/runtime.go index 8f52a47cac6..7db3f697ef0 100644 --- a/pkg/processor/runtime/dotnetcore/runtime.go +++ b/pkg/processor/runtime/dotnetcore/runtime.go @@ -17,7 +17,6 @@ limitations under the License. package dotnetcore import ( - "fmt" "io" "os" "os/exec" @@ -59,12 +58,12 @@ func NewRuntime(parentLogger logger.Logger, configuration *runtime.Configuration func (d *dotnetcore) RunWrapper(socketPaths []string, controlSocketPath string) (*os.Process, error) { if len(socketPaths) != 1 { - return nil, fmt.Errorf("Dotnet runtime doesn't support multiple socket processing") + return nil, errors.Errorf("Dotnet runtime doesn't support multiple socket processing") } wrapperDLLPath := d.getWrapperDLLPath() d.Logger.DebugWith("Using dotnet core wrapper dll path", "path", wrapperDLLPath) if !common.IsFile(wrapperDLLPath) { - return nil, fmt.Errorf("Can't find wrapper at %q", wrapperDLLPath) + return nil, errors.Errorf("Can't find wrapper at %q", wrapperDLLPath) } handler := d.getHandler() diff --git a/pkg/processor/runtime/golang/runtime.go b/pkg/processor/runtime/golang/runtime.go index 1b8814c706a..6e1959dfd1a 100644 --- a/pkg/processor/runtime/golang/runtime.go +++ b/pkg/processor/runtime/golang/runtime.go @@ -18,7 +18,6 @@ package golang import ( "context" - "fmt" "runtime/debug" "sync" "time" @@ -66,7 +65,7 @@ func NewRuntime(parentLogger logger.Logger, return nil, errors.Wrap(err, "Failed to load handler") } - timeout, _ := configuration.Configuration.Spec.GetEventTimeout() + timeout, _ := configuration.Spec.GetEventTimeout() // create the runtime newGoRuntime := &golang{ @@ -80,7 +79,7 @@ func NewRuntime(parentLogger logger.Logger, // try to initialize the context, if applicable contextInitializer := handler.getContextInitializer() if contextInitializer != nil { - newGoRuntime.AbstractRuntime.Logger.DebugWith("Calling context initializer") + newGoRuntime.Logger.DebugWith("Calling context initializer") if err := contextInitializer(newGoRuntime.Context); err != nil { return nil, errors.Wrap(err, "Failed to initialize context") @@ -194,7 +193,7 @@ func (g *golang) callEntrypoint(event nuclio.Event, functionLogger logger.Logger "err", err, "stack", string(callStack)) - processingResult.responseErr = fmt.Errorf("Caught panic: %s", err) + processingResult.responseErr = errors.Errorf("Caught panic: %s", err) // try to write response to the channel if it wasn't yet select { // if the reader is waiting, then it means that runtime wasn't stopped and waits for a response diff --git a/pkg/processor/runtime/java/runtime.go b/pkg/processor/runtime/java/runtime.go index 004e8e8d0f0..f525e20d494 100644 --- a/pkg/processor/runtime/java/runtime.go +++ b/pkg/processor/runtime/java/runtime.go @@ -17,7 +17,6 @@ limitations under the License. package java import ( - "fmt" "io" "os" "os/exec" @@ -62,7 +61,7 @@ func NewRuntime(parentLogger logger.Logger, configuration *runtime.Configuration func (j *java) RunWrapper(ports []string, controlPort string) (*os.Process, error) { if len(ports) != 1 { - return nil, fmt.Errorf("Java runtime doesn't support multiple ports processing") + return nil, errors.Errorf("Java runtime doesn't support multiple ports processing") } jvmOptions, err := j.getJVMOptions() diff --git a/pkg/processor/runtime/nodejs/runtime.go b/pkg/processor/runtime/nodejs/runtime.go index 91203df3ed0..06bbca68ec4 100644 --- a/pkg/processor/runtime/nodejs/runtime.go +++ b/pkg/processor/runtime/nodejs/runtime.go @@ -17,7 +17,6 @@ limitations under the License. package nodejs import ( - "fmt" "io" "os" "os/exec" @@ -62,12 +61,12 @@ func NewRuntime(parentLogger logger.Logger, configuration *runtime.Configuration // We can't use n.Logger since it's not initialized func (n *nodejs) RunWrapper(socketPaths []string, controlSocketPath string) (*os.Process, error) { if len(socketPaths) != 1 { - return nil, fmt.Errorf("Nodejs runtime doesn't support multiple socket processing") + return nil, errors.Errorf("Nodejs runtime doesn't support multiple socket processing") } wrapperScriptPath := n.getWrapperScriptPath() n.Logger.DebugWith("Using nodejs wrapper script path", "path", wrapperScriptPath) if !common.IsFile(wrapperScriptPath) { - return nil, fmt.Errorf("Can't find wrapper at %q", wrapperScriptPath) + return nil, errors.Errorf("Can't find wrapper at %q", wrapperScriptPath) } nodeExePath, err := n.getNodeExePath() @@ -113,7 +112,7 @@ func (n *nodejs) getHandler() (string, string, error) { handlerFileName = parts[0] handlerName = parts[1] default: - return "", "", fmt.Errorf("Bad handler - %q", n.configuration.Spec.Handler) + return "", "", errors.Errorf("Bad handler - %q", n.configuration.Spec.Handler) } return path.Join(n.getHandlerDir(), handlerFileName), handlerName, nil diff --git a/pkg/processor/runtime/python/runtime.go b/pkg/processor/runtime/python/runtime.go index 59824953c35..a6fd5bad142 100644 --- a/pkg/processor/runtime/python/runtime.go +++ b/pkg/processor/runtime/python/runtime.go @@ -148,7 +148,7 @@ func (py *python) Drain() error { // wait for process to finish event handling or timeout // TODO: replace the following function with one that waits for a control communication message or timeout - py.AbstractRuntime.WaitForProcessTermination(py.configuration.WorkerTerminationTimeout) + py.WaitForProcessTermination(py.configuration.WorkerTerminationTimeout) return nil } diff --git a/pkg/processor/runtime/rpc/abstract_test.go b/pkg/processor/runtime/rpc/abstract_test.go index f432b5a29d0..142f0858c7a 100644 --- a/pkg/processor/runtime/rpc/abstract_test.go +++ b/pkg/processor/runtime/rpc/abstract_test.go @@ -65,7 +65,7 @@ func newTestRuntime(parentLogger logger.Logger, configuration *runtime.Configura return nil, errors.Wrap(err, "Failed to create runtime") } - newTestRuntime.AbstractRuntime.configuration.ControlMessageBroker = controlmessagebroker.NewRpcControlMessageBroker(nil, parentLogger, nil).AbstractControlMessageBroker + newTestRuntime.configuration.ControlMessageBroker = controlmessagebroker.NewRpcControlMessageBroker(nil, parentLogger, nil).AbstractControlMessageBroker return newTestRuntime, nil } diff --git a/pkg/processor/runtime/rpc/connection/abstract.go b/pkg/processor/runtime/rpc/connection/abstract.go index bc25b4d1b5e..9008d4047d2 100644 --- a/pkg/processor/runtime/rpc/connection/abstract.go +++ b/pkg/processor/runtime/rpc/connection/abstract.go @@ -197,7 +197,7 @@ func (bc *AbstractConnectionManager) createUnixListener() (net.Listener, string, unixListener, ok := listener.(*net.UnixListener) if !ok { - return nil, "", fmt.Errorf("Can't get underlying Unix listener") + return nil, "", errors.Errorf("Can't get underlying Unix listener") } if err = unixListener.SetDeadline(time.Now().Add(connectionTimeout)); err != nil { diff --git a/pkg/processor/runtime/rpc/connection/connectionallocator.go b/pkg/processor/runtime/rpc/connection/connectionallocator.go index d7f21e2284e..afd472b84c2 100644 --- a/pkg/processor/runtime/rpc/connection/connectionallocator.go +++ b/pkg/processor/runtime/rpc/connection/connectionallocator.go @@ -225,7 +225,7 @@ func (ca *ConnectionAllocator) createConnections(connectionsNumber int) ([]*Conn // start event processing for _, eventConnection := range eventConnections { eventConnection.SetEncoder(ca.Configuration.GetEventEncoderFunc(eventConnection.Conn)) - go eventConnection.AbstractEventConnection.RunHandler() + go eventConnection.RunHandler() } // wait for start if required to diff --git a/pkg/processor/runtime/rpc/connection/connectionallocator_test.go b/pkg/processor/runtime/rpc/connection/connectionallocator_test.go index 9706c4f14fa..81dc26f4091 100644 --- a/pkg/processor/runtime/rpc/connection/connectionallocator_test.go +++ b/pkg/processor/runtime/rpc/connection/connectionallocator_test.go @@ -35,8 +35,6 @@ import ( "github.com/nuclio/nuclio-sdk-go" nucliozap "github.com/nuclio/zap" "github.com/stretchr/testify/suite" - - _ "net/http" ) type TestConnectionAllocatorSuite struct { diff --git a/pkg/processor/runtime/rpc/connection/socketallocator.go b/pkg/processor/runtime/rpc/connection/socketallocator.go index ac5a91eaf8e..8a70b37dd73 100644 --- a/pkg/processor/runtime/rpc/connection/socketallocator.go +++ b/pkg/processor/runtime/rpc/connection/socketallocator.go @@ -150,7 +150,7 @@ func (sa *SocketAllocator) startSockets(eventSockets []eventprocessor.EventProce return errors.Wrap(err, "Can't get connection from wrapper") } eventSocketInstance.SetEncoder(sa.Configuration.GetEventEncoderFunc(eventSocketInstance.Conn)) - go eventSocketInstance.AbstractEventConnection.RunHandler() + go eventSocketInstance.RunHandler() } sa.Logger.Debug("Successfully established connection for event sockets") diff --git a/pkg/processor/runtime/rpc/result/result.go b/pkg/processor/runtime/rpc/result/result.go index b5b761d0c6c..503b5a423c4 100644 --- a/pkg/processor/runtime/rpc/result/result.go +++ b/pkg/processor/runtime/rpc/result/result.go @@ -19,8 +19,8 @@ package result import ( "encoding/base64" "encoding/json" - "fmt" + "github.com/nuclio/errors" "github.com/nuclio/logger" ) @@ -67,7 +67,7 @@ func (br *BatchedResults) UnmarshalResponseData(logger logger.Logger, data []byt case "base64": unmarshalledResult.DecodedBody, br.Err = base64.StdEncoding.DecodeString(unmarshalledResult.Body) default: - unmarshalledResult.Err = fmt.Errorf("Unknown body encoding - %q", unmarshalledResult.BodyEncoding) + unmarshalledResult.Err = errors.Errorf("Unknown body encoding - %q", unmarshalledResult.BodyEncoding) } } diff --git a/pkg/processor/runtime/ruby/runtime.go b/pkg/processor/runtime/ruby/runtime.go index 1177c4400fe..60e8f318e08 100644 --- a/pkg/processor/runtime/ruby/runtime.go +++ b/pkg/processor/runtime/ruby/runtime.go @@ -17,7 +17,6 @@ limitations under the License. package ruby import ( - "fmt" "io" "os" "os/exec" @@ -60,7 +59,7 @@ func NewRuntime(parentLogger logger.Logger, configuration *runtime.Configuration func (r *ruby) RunWrapper(socketPaths []string, controlSocketPath string) (*os.Process, error) { if len(socketPaths) != 1 { - return nil, fmt.Errorf("Ruby runtime doesn't support multiple socket processing") + return nil, errors.Errorf("Ruby runtime doesn't support multiple socket processing") } wrapperPath := common.GetEnvOrDefaultString("NUCLIO_WRAPPER_PATH", "/opt/nuclio/wrapper.rb") args := []string{ diff --git a/pkg/processor/runtime/shell/runtime.go b/pkg/processor/runtime/shell/runtime.go index a54da8287e9..a0d82e1cc3b 100644 --- a/pkg/processor/runtime/shell/runtime.go +++ b/pkg/processor/runtime/shell/runtime.go @@ -61,7 +61,7 @@ func NewRuntime(parentLogger logger.Logger, configuration *Configuration) (runti if err != nil { return nil, errors.Wrap(err, "Failed to create abstract runtime") } - timeout, _ := configuration.Configuration.Spec.GetEventTimeout() + timeout, _ := configuration.Spec.GetEventTimeout() // create the command string newShellRuntime := &shell{ @@ -296,7 +296,7 @@ func (s *shell) getCommandArguments(event nuclio.Event) []string { } func (s *shell) getEnvFromConfiguration() []string { - envs := s.AbstractRuntime.GetEnvFromConfiguration() + envs := s.GetEnvFromConfiguration() // inject all environment variables passed in configuration for _, configEnv := range s.configuration.Spec.Env { diff --git a/pkg/processor/runtime/shell/types.go b/pkg/processor/runtime/shell/types.go index 0e8c8bb4eda..ecd124d3475 100644 --- a/pkg/processor/runtime/shell/types.go +++ b/pkg/processor/runtime/shell/types.go @@ -37,7 +37,7 @@ func NewConfiguration(runtimeConfiguration *runtime.Configuration) (*Configurati } // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Spec.RuntimeAttributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Spec.RuntimeAttributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/test/readinesstimeout/readinesstimeout_test.go b/pkg/processor/test/readinesstimeout/readinesstimeout_test.go index 18d00725dd6..24109a38564 100644 --- a/pkg/processor/test/readinesstimeout/readinesstimeout_test.go +++ b/pkg/processor/test/readinesstimeout/readinesstimeout_test.go @@ -73,11 +73,11 @@ func (suite *readinessTimeoutTestSuite) deployFailingPythonFunction(readinessTim suite.PopulateDeployOptions(createFunctionOptions) // deploy the function - it's OK for it to time out - _, err := suite.Platform.CreateFunction(suite.TestSuite.Ctx, createFunctionOptions) + _, err := suite.Platform.CreateFunction(suite.Ctx, createFunctionOptions) suite.Require().Error(err) // delete the function when done - defer suite.Platform.DeleteFunction(suite.TestSuite.Ctx, &platform.DeleteFunctionOptions{ // nolint: errcheck + defer suite.Platform.DeleteFunction(suite.Ctx, &platform.DeleteFunctionOptions{ // nolint: errcheck FunctionConfig: createFunctionOptions.FunctionConfig, }) } diff --git a/pkg/processor/trigger/cron/trigger.go b/pkg/processor/trigger/cron/trigger.go index d73c93d66b7..44bc1a5b6d3 100644 --- a/pkg/processor/trigger/cron/trigger.go +++ b/pkg/processor/trigger/cron/trigger.go @@ -65,7 +65,7 @@ func newTrigger(logger logger.Logger, stop: make(chan int), } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger switch { case configuration.Interval != "": diff --git a/pkg/processor/trigger/cron/types.go b/pkg/processor/trigger/cron/types.go index a6898e209af..d8d927df152 100644 --- a/pkg/processor/trigger/cron/types.go +++ b/pkg/processor/trigger/cron/types.go @@ -45,7 +45,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/http/trigger.go b/pkg/processor/trigger/http/trigger.go index dbbd8baab81..762a5d401bc 100644 --- a/pkg/processor/trigger/http/trigger.go +++ b/pkg/processor/trigger/http/trigger.go @@ -91,7 +91,7 @@ func newTrigger(logger logger.Logger, internalHealthPath: []byte(InternalHealthPath), } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger newTrigger.allocateEvents(numWorkers) if functionconfig.BatchModeEnabled(configuration.Batch) { @@ -163,19 +163,19 @@ func (h *http) PrepareEventAndSubmitToBatch(ctx *fasthttp.RequestCtx) (chan inte func (h *http) AllocateWorkerAndSubmitEvent(ctx *fasthttp.RequestCtx, functionLogger logger.Logger, - timeout time.Duration) (response nuclio.ProcessingResult, submitError error, processError error, workerInstance eventprocessor.EventProcessor) { + timeout time.Duration) (response nuclio.ProcessingResult, workerInstance eventprocessor.EventProcessor, submitError error, processError error) { defer h.HandleSubmitPanic(workerInstance, &submitError) // allocate a worker workerInstance, _, err := h.allocateWorker(timeout) if err != nil { - return nil, err, nil, workerInstance + return nil, workerInstance, err, nil } // submit to worker response, processError = h.SubmitEventToWorker(functionLogger, workerInstance, &Event{ctx: ctx}) - return response, nil, processError, workerInstance + return response, workerInstance, nil, processError } func (h *http) flushIfTimeout(ctx *fasthttp.RequestCtx, processError error) bool { @@ -477,7 +477,7 @@ func (h *http) handleRequest(ctx *fasthttp.RequestCtx) { } } else { // TODO: change to return runtime.ResponseWithErrors - response, submitError, processError, workerInstance = h.AllocateWorkerAndSubmitEvent(ctx, + response, workerInstance, submitError, processError = h.AllocateWorkerAndSubmitEvent(ctx, functionLogger, time.Duration(*h.configuration.WorkerAvailabilityTimeoutMilliseconds)*time.Millisecond) } diff --git a/pkg/processor/trigger/http/types.go b/pkg/processor/trigger/http/types.go index 53c6fcc7d5d..c2fc6211a1a 100644 --- a/pkg/processor/trigger/http/types.go +++ b/pkg/processor/trigger/http/types.go @@ -69,7 +69,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/kafka/scram/xdg.go b/pkg/processor/trigger/kafka/scram/xdg.go index 6b65ad76d57..2855f39c44b 100644 --- a/pkg/processor/trigger/kafka/scram/xdg.go +++ b/pkg/processor/trigger/kafka/scram/xdg.go @@ -49,11 +49,11 @@ func NewClient(saslMechanism sarama.SASLMechanism) sarama.SCRAMClient { } func (sc *Client) Begin(userName, password, authzID string) (err error) { - sc.Client, err = sc.HashGeneratorFcn.NewClient(userName, password, authzID) + sc.Client, err = sc.NewClient(userName, password, authzID) if err != nil { return errors.Wrap(err, "Failed to create new client") } - sc.ClientConversation = sc.Client.NewConversation() + sc.ClientConversation = sc.NewConversation() return nil } diff --git a/pkg/processor/trigger/kafka/test/kafka_confluent_test.go b/pkg/processor/trigger/kafka/test/kafka_confluent_test.go index 566694d64e9..a93c698d1f4 100644 --- a/pkg/processor/trigger/kafka/test/kafka_confluent_test.go +++ b/pkg/processor/trigger/kafka/test/kafka_confluent_test.go @@ -57,7 +57,7 @@ func (suite *testConfluentSuite) SetupSuite() { suite.password = "" // start broker and zookeeper containers explicitly - suite.AbstractBrokerSuite.SkipStartBrokerContainer = true + suite.SkipStartBrokerContainer = true suite.AbstractBrokerSuite.SetupSuite() // create broker @@ -126,7 +126,7 @@ func (suite *testConfluentSuite) TestReceiveRecords() { }, } - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/kafka/test/kafka_test.go b/pkg/processor/trigger/kafka/test/kafka_test.go index 16f4a71a40e..f6c982ccd9d 100644 --- a/pkg/processor/trigger/kafka/test/kafka_test.go +++ b/pkg/processor/trigger/kafka/test/kafka_test.go @@ -36,6 +36,7 @@ import ( "github.com/nuclio/nuclio/pkg/processor/util/partitionworker" "github.com/IBM/sarama" + "github.com/nuclio/errors" "github.com/stretchr/testify/suite" "k8s.io/api/core/v1" ) @@ -86,8 +87,8 @@ func (suite *testSuite) SetupSuite() { suite.brokerURL = fmt.Sprintf("%s:%d", suite.BrokerHost, suite.brokerPort) // start broker and zookeeper containers explicitly - suite.AbstractBrokerSuite.SkipStartBrokerContainer = true - suite.AbstractBrokerSuite.BrokerContainerNetworkName = "nuclio-kafka-test" + suite.SkipStartBrokerContainer = true + suite.BrokerContainerNetworkName = "nuclio-kafka-test" suite.AbstractBrokerSuite.SetupSuite() // start zoo keeper container @@ -197,7 +198,7 @@ func (suite *testSuite) TestReceiveRecords() { expectedNumberOfCommittedMessages += int(suite.NumPartitions) - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{ @@ -764,7 +765,7 @@ func (suite *testSuite) getNumberOfCommittedOffsetsFromBroker(consumerGroup, top // Send the request to the broker response, err := suite.broker.FetchOffset(request) if err != nil { - return -1, fmt.Errorf("Failed to fetch offsets: %w", err) + return -1, errors.Errorf("failed to fetch offsets: %s", err.Error()) } // Sum committed offsets across all partitions @@ -772,10 +773,10 @@ func (suite *testSuite) getNumberOfCommittedOffsetsFromBroker(consumerGroup, top for partition := 0; partition < partitions; partition++ { block := response.GetBlock(topic, int32(partition)) if block == nil { - return -1, fmt.Errorf("No offset block returned for topic %s partition %d", topic, partition) + return -1, errors.Errorf("No offset block returned for topic %s partition %d", topic, partition) } if block.Err != sarama.ErrNoError { - return -1, fmt.Errorf("Error in offset block for partition %d: %v", partition, block.Err) + return -1, errors.Errorf("Error in offset block for partition %d: %v", partition, block.Err) } if block.Offset != -1 { totalOffset += block.Offset diff --git a/pkg/processor/trigger/kafka/trigger.go b/pkg/processor/trigger/kafka/trigger.go index 47958d00f28..81bc767d2da 100644 --- a/pkg/processor/trigger/kafka/trigger.go +++ b/pkg/processor/trigger/kafka/trigger.go @@ -88,7 +88,7 @@ func newTrigger(parentLogger logger.Logger, return nil, errors.New("Failed to create abstract trigger") } - kafkaTrigger.AbstractTrigger.Trigger = kafkaTrigger + kafkaTrigger.Trigger = kafkaTrigger kafkaTrigger.Logger.DebugWith("Creating consumer", "brokers", configuration.brokers, @@ -681,7 +681,7 @@ func (k *kafka) explicitAckHandler( } // skip the message if it is not for this topic and partition - if !(explicitAckAttributes.Partition == partitionNumber && explicitAckAttributes.Topic == topic) { + if explicitAckAttributes.Partition != partitionNumber || explicitAckAttributes.Topic != topic { continue } diff --git a/pkg/processor/trigger/kafka/types.go b/pkg/processor/trigger/kafka/types.go index abdc0256e84..603afe47513 100644 --- a/pkg/processor/trigger/kafka/types.go +++ b/pkg/processor/trigger/kafka/types.go @@ -135,7 +135,7 @@ func NewConfiguration(id string, explicitAckModeValue := "" // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/kickstart/trigger.go b/pkg/processor/trigger/kickstart/trigger.go index 49ff376677a..69219533e1e 100644 --- a/pkg/processor/trigger/kickstart/trigger.go +++ b/pkg/processor/trigger/kickstart/trigger.go @@ -53,7 +53,7 @@ func newTrigger(logger logger.Logger, AbstractTrigger: abstractTrigger, configuration: configuration, } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger return &newTrigger, nil } diff --git a/pkg/processor/trigger/kickstart/types.go b/pkg/processor/trigger/kickstart/types.go index 88f0165f04e..8e60de8e7ba 100644 --- a/pkg/processor/trigger/kickstart/types.go +++ b/pkg/processor/trigger/kickstart/types.go @@ -44,7 +44,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/kinesis/test/kinesis_test.go b/pkg/processor/trigger/kinesis/test/kinesis_test.go index 0b149468aff..a1afdeb12fb 100644 --- a/pkg/processor/trigger/kinesis/test/kinesis_test.go +++ b/pkg/processor/trigger/kinesis/test/kinesis_test.go @@ -87,7 +87,7 @@ func (suite *testSuite) SetupSuite() { func (suite *testSuite) TestReceiveRecords() { createFunctionOptions := suite.getDeployOptions("kinesis-event-recorder") - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{suite.streamName: {NumMessages: suite.shardCount}}, diff --git a/pkg/processor/trigger/kinesis/trigger.go b/pkg/processor/trigger/kinesis/trigger.go index 5e304bd6389..da53fd863b6 100644 --- a/pkg/processor/trigger/kinesis/trigger.go +++ b/pkg/processor/trigger/kinesis/trigger.go @@ -56,7 +56,7 @@ func newTrigger(parentLogger logger.Logger, AbstractTrigger: abstractTrigger, configuration: configuration, } - newTrigger.AbstractTrigger.Trigger = newTrigger + newTrigger.Trigger = newTrigger newTrigger.kinesisAuth = kinesisclient.NewAuth(configuration.AccessKeyID, configuration.SecretAccessKey, "") diff --git a/pkg/processor/trigger/kinesis/types.go b/pkg/processor/trigger/kinesis/types.go index 0b9192c0a3e..67a77e00728 100644 --- a/pkg/processor/trigger/kinesis/types.go +++ b/pkg/processor/trigger/kinesis/types.go @@ -53,7 +53,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/mqtt/basic/test/mqtt_test.go b/pkg/processor/trigger/mqtt/basic/test/mqtt_test.go index f988e2f2f63..b0d9a8424d6 100644 --- a/pkg/processor/trigger/mqtt/basic/test/mqtt_test.go +++ b/pkg/processor/trigger/mqtt/basic/test/mqtt_test.go @@ -120,7 +120,7 @@ func (suite *testSuite) TestMultipleTopics() { }) // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getCreateFunctionOptionsWithMQTTTrigger(triggerConfiguration), map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/mqtt/basic/trigger.go b/pkg/processor/trigger/mqtt/basic/trigger.go index ca40a103420..d0397213245 100644 --- a/pkg/processor/trigger/mqtt/basic/trigger.go +++ b/pkg/processor/trigger/mqtt/basic/trigger.go @@ -45,7 +45,7 @@ func newTrigger(parentLogger logger.Logger, newTrigger := basicmqtt{ AbstractTrigger: newAbstractTrigger, } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger return newTrigger, nil } diff --git a/pkg/processor/trigger/mqtt/iotcore/trigger.go b/pkg/processor/trigger/mqtt/iotcore/trigger.go index e4d97b2f173..86f61e6a8b3 100644 --- a/pkg/processor/trigger/mqtt/iotcore/trigger.go +++ b/pkg/processor/trigger/mqtt/iotcore/trigger.go @@ -53,7 +53,7 @@ func newTrigger(parentLogger logger.Logger, configuration: configuration, } - newIOTCoreMQTT.AbstractTrigger.Trigger = &newIOTCoreMQTT + newIOTCoreMQTT.Trigger = &newIOTCoreMQTT // set username to something so that client will send it newIOTCoreMQTT.configuration.Username = "ignored" diff --git a/pkg/processor/trigger/mqtt/iotcore/types.go b/pkg/processor/trigger/mqtt/iotcore/types.go index 7a58a20e198..ffe97d46c1f 100644 --- a/pkg/processor/trigger/mqtt/iotcore/types.go +++ b/pkg/processor/trigger/mqtt/iotcore/types.go @@ -54,7 +54,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *mqttConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/mqtt/types.go b/pkg/processor/trigger/mqtt/types.go index 47098263c26..4b9d5bf37ef 100644 --- a/pkg/processor/trigger/mqtt/types.go +++ b/pkg/processor/trigger/mqtt/types.go @@ -50,7 +50,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/nats/core/test/nats_test.go b/pkg/processor/trigger/nats/core/test/nats_test.go index 313cefe7ed9..03a733506db 100644 --- a/pkg/processor/trigger/nats/core/test/nats_test.go +++ b/pkg/processor/trigger/nats/core/test/nats_test.go @@ -63,7 +63,7 @@ func (suite *testSuite) TestPostEvent() { suite.Require().NoError(err, "Failed to create NATS connection") // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getDeployOptions(), map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/nats/core/trigger.go b/pkg/processor/trigger/nats/core/trigger.go index d242f6d2259..d8a6c9ccad0 100644 --- a/pkg/processor/trigger/nats/core/trigger.go +++ b/pkg/processor/trigger/nats/core/trigger.go @@ -59,7 +59,7 @@ func newTrigger(parentLogger logger.Logger, configuration: configuration, stop: make(chan bool), } - newTrigger.AbstractTrigger.Trigger = newTrigger + newTrigger.Trigger = newTrigger if err := newTrigger.validateConfiguration(); err != nil { return nil, errors.Wrap(err, "Failed to validate NATS trigger configuration") diff --git a/pkg/processor/trigger/nats/core/types.go b/pkg/processor/trigger/nats/core/types.go index 7c21f625221..17278f1d15c 100644 --- a/pkg/processor/trigger/nats/core/types.go +++ b/pkg/processor/trigger/nats/core/types.go @@ -44,7 +44,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/nats/jetstream/test/natsjetstream_test.go b/pkg/processor/trigger/nats/jetstream/test/natsjetstream_test.go index 4bcfc2fa9f5..e5b6f4df907 100644 --- a/pkg/processor/trigger/nats/jetstream/test/natsjetstream_test.go +++ b/pkg/processor/trigger/nats/jetstream/test/natsjetstream_test.go @@ -72,7 +72,7 @@ func (suite *testSuite) TestPostEvent() { suite.Require().NoError(err, "Failed to create Jetstream consumer") // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getDeployOptions(), map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/nats/jetstream/trigger.go b/pkg/processor/trigger/nats/jetstream/trigger.go index df2e2601c70..33d85011a56 100644 --- a/pkg/processor/trigger/nats/jetstream/trigger.go +++ b/pkg/processor/trigger/nats/jetstream/trigger.go @@ -59,7 +59,7 @@ func newTrigger(parentLogger logger.Logger, configuration: configuration, stop: make(chan bool), } - newTrigger.AbstractTrigger.Trigger = newTrigger + newTrigger.Trigger = newTrigger if err := newTrigger.validateConfiguration(); err != nil { return nil, errors.Wrap(err, "Failed to validate NATS JetStream trigger configuration") diff --git a/pkg/processor/trigger/nats/jetstream/types.go b/pkg/processor/trigger/nats/jetstream/types.go index bd1a4370e8b..02cae0c2dd1 100644 --- a/pkg/processor/trigger/nats/jetstream/types.go +++ b/pkg/processor/trigger/nats/jetstream/types.go @@ -44,7 +44,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/partitioned/eventhub/test/eventhub_test.go b/pkg/processor/trigger/partitioned/eventhub/test/eventhub_test.go index ba88374b2b9..f2306aca840 100644 --- a/pkg/processor/trigger/partitioned/eventhub/test/eventhub_test.go +++ b/pkg/processor/trigger/partitioned/eventhub/test/eventhub_test.go @@ -79,7 +79,7 @@ func (suite *testSuite) TestReceiveRecords() { }, } - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{"": {NumMessages: 3}}, diff --git a/pkg/processor/trigger/partitioned/eventhub/types.go b/pkg/processor/trigger/partitioned/eventhub/types.go index 6569d52d0a8..2c4811e9a3f 100644 --- a/pkg/processor/trigger/partitioned/eventhub/types.go +++ b/pkg/processor/trigger/partitioned/eventhub/types.go @@ -48,7 +48,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/partitioned/trigger.go b/pkg/processor/trigger/partitioned/trigger.go index c19d0aba934..e0696fc3135 100644 --- a/pkg/processor/trigger/partitioned/trigger.go +++ b/pkg/processor/trigger/partitioned/trigger.go @@ -72,7 +72,7 @@ func NewAbstractStream(parentLogger logger.Logger, configuration: configuration, stream: stream, } - newAbstractStream.AbstractTrigger.Trigger = newAbstractStream + newAbstractStream.Trigger = newAbstractStream return newAbstractStream, nil } diff --git a/pkg/processor/trigger/poller/types.go b/pkg/processor/trigger/poller/types.go index 2ed022632aa..eb79b6f4dfa 100644 --- a/pkg/processor/trigger/poller/types.go +++ b/pkg/processor/trigger/poller/types.go @@ -46,7 +46,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/poller/v3ioitempoller/trigger.go b/pkg/processor/trigger/poller/v3ioitempoller/trigger.go index c108b62e6f8..7477ae7eb51 100644 --- a/pkg/processor/trigger/poller/v3ioitempoller/trigger.go +++ b/pkg/processor/trigger/poller/v3ioitempoller/trigger.go @@ -55,7 +55,7 @@ func newTrigger(logger logger.Logger, configuration: configuration, firstPoll: true, } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger // register self as the poller (to allow parent to call child functions) newTrigger.SetPoller(&newTrigger) diff --git a/pkg/processor/trigger/pubsub/test/pubsub_test.go b/pkg/processor/trigger/pubsub/test/pubsub_test.go index 105b8666cfa..3d56229e50a 100644 --- a/pkg/processor/trigger/pubsub/test/pubsub_test.go +++ b/pkg/processor/trigger/pubsub/test/pubsub_test.go @@ -126,7 +126,7 @@ func (suite *testSuite) TestReceiveRecords() { }, } - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/pubsub/trigger.go b/pkg/processor/trigger/pubsub/trigger.go index 6cb4ec773eb..a45076080ad 100644 --- a/pkg/processor/trigger/pubsub/trigger.go +++ b/pkg/processor/trigger/pubsub/trigger.go @@ -60,7 +60,7 @@ func newTrigger(parentLogger logger.Logger, configuration: configuration, stop: make(chan bool), } - newTrigger.AbstractTrigger.Trigger = newTrigger + newTrigger.Trigger = newTrigger return newTrigger, nil } diff --git a/pkg/processor/trigger/pubsub/types.go b/pkg/processor/trigger/pubsub/types.go index 6dd2e22ac8a..ffc79a5c989 100644 --- a/pkg/processor/trigger/pubsub/types.go +++ b/pkg/processor/trigger/pubsub/types.go @@ -61,7 +61,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/rabbitmq/test/rabbitmq_test.go b/pkg/processor/trigger/rabbitmq/test/rabbitmq_test.go index 62061c0a1c1..9658a39b064 100644 --- a/pkg/processor/trigger/rabbitmq/test/rabbitmq_test.go +++ b/pkg/processor/trigger/rabbitmq/test/rabbitmq_test.go @@ -100,7 +100,7 @@ func (suite *testSuite) TestReconnect() { suite.createBrokerResources([]string{"t1", "t2", "t3"}) // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getCreateFunctionOptionsWithRmqTrigger(triggerConfig), map[string]triggertest.TopicMessages{ @@ -154,7 +154,7 @@ func (suite *testSuite) TestPreexistingResources() { suite.createBrokerResources([]string{"t1", "t2", "t3"}) // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getCreateFunctionOptionsWithRmqTrigger(triggerConfig), map[string]triggertest.TopicMessages{ @@ -181,7 +181,7 @@ func (suite *testSuite) TestResourcesCreatedByFunction() { } // invoke the event recorder - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, suite.getCreateFunctionOptionsWithRmqTrigger(triggerConfig), map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/rabbitmq/trigger.go b/pkg/processor/trigger/rabbitmq/trigger.go index 3528b8ca404..e22ec05960c 100644 --- a/pkg/processor/trigger/rabbitmq/trigger.go +++ b/pkg/processor/trigger/rabbitmq/trigger.go @@ -66,7 +66,7 @@ func newTrigger(parentLogger logger.Logger, AbstractTrigger: abstractTrigger, configuration: configuration, } - newTrigger.AbstractTrigger.Trigger = &newTrigger + newTrigger.Trigger = &newTrigger return &newTrigger, nil } diff --git a/pkg/processor/trigger/rabbitmq/types.go b/pkg/processor/trigger/rabbitmq/types.go index 96a738efa84..1479d978cde 100644 --- a/pkg/processor/trigger/rabbitmq/types.go +++ b/pkg/processor/trigger/rabbitmq/types.go @@ -56,7 +56,7 @@ func NewConfiguration(id string, newConfiguration.Configuration = *baseConfiguration // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/trigger/test/broker.go b/pkg/processor/trigger/test/broker.go index d6edc927f02..afc3e69b438 100644 --- a/pkg/processor/trigger/test/broker.go +++ b/pkg/processor/trigger/test/broker.go @@ -118,7 +118,7 @@ func (suite *AbstractBrokerSuite) SetupSuite() { } func (suite *AbstractBrokerSuite) TearDownSuite() { - suite.TestSuite.TearDownTest() + suite.TearDownTest() // if we weren't successful starting, nothing to do if suite.BrokerContainerID != "" { diff --git a/pkg/processor/trigger/trigger.go b/pkg/processor/trigger/trigger.go index 6a7756998b2..4bec94cdb41 100644 --- a/pkg/processor/trigger/trigger.go +++ b/pkg/processor/trigger/trigger.go @@ -198,6 +198,8 @@ func (at *AbstractTrigger) AllocateWorkerAndSubmitEvent(event nuclio.Event, } // AllocateWorkerAndSubmitEvents submits multiple events to an allocated worker +// +//nolint:staticcheck // ST1008: submitError comes before processErrors for logical reasons func (at *AbstractTrigger) AllocateWorkerAndSubmitEvents(events []nuclio.Event, functionLogger logger.Logger, timeout time.Duration) (responses []nuclio.ProcessingResult, submitError error, processErrors []error) { diff --git a/pkg/processor/trigger/types.go b/pkg/processor/trigger/types.go index bb301e67ae0..4b191122e53 100644 --- a/pkg/processor/trigger/types.go +++ b/pkg/processor/trigger/types.go @@ -90,7 +90,7 @@ func (c *Configuration) PopulateConfigurationFromAnnotations(annotationConfigFie var err error for _, annotationConfigField := range annotationConfigFields { - annotationValue, annotationKeyExists := c.RuntimeConfiguration.Config.Meta.Annotations[annotationConfigField.Key] + annotationValue, annotationKeyExists := c.RuntimeConfiguration.Meta.Annotations[annotationConfigField.Key] if !annotationKeyExists { continue } @@ -156,10 +156,10 @@ func (c *Configuration) PopulateExplicitAckMode(logger logger.Logger, explicitAc } if c.ExplicitAckMode != functionconfig.ExplicitAckModeDisable { - if !functionconfig.RuntimeSupportExplicitAck(c.RuntimeConfiguration.Config.Spec.Runtime) { + if !functionconfig.RuntimeSupportExplicitAck(c.RuntimeConfiguration.Spec.Runtime) { logger.WarnWith("Explicit Ack is not supported for the configured runtime. "+ "Setting explicitAck mode to `disable`", - "runtime", c.RuntimeConfiguration.Config.Spec.Runtime) + "runtime", c.RuntimeConfiguration.Spec.Runtime) c.ExplicitAckMode = functionconfig.ExplicitAckModeDisable } } diff --git a/pkg/processor/trigger/v3iostream/test/v3iostream_test.go b/pkg/processor/trigger/v3iostream/test/v3iostream_test.go index df0bfa58588..189c542c4a1 100644 --- a/pkg/processor/trigger/v3iostream/test/v3iostream_test.go +++ b/pkg/processor/trigger/v3iostream/test/v3iostream_test.go @@ -73,7 +73,7 @@ func (suite *testSuite) SetupSuite() { // END OF change // we use an Iguazio system, not a containerzed broker - suite.AbstractBrokerSuite.SkipStartBrokerContainer = true + suite.SkipStartBrokerContainer = true suite.AbstractBrokerSuite.SetupSuite() suite.stateContentsAttributeKey = "state" @@ -286,7 +286,7 @@ func (suite *testSuite) TestReceiveRecords() { }, } - triggertest.InvokeEventRecorder(&suite.AbstractBrokerSuite.TestSuite, + triggertest.InvokeEventRecorder(&suite.TestSuite, suite.BrokerHost, createFunctionOptions, map[string]triggertest.TopicMessages{ diff --git a/pkg/processor/trigger/v3iostream/trigger.go b/pkg/processor/trigger/v3iostream/trigger.go index a4b027dca7a..08438d528e0 100644 --- a/pkg/processor/trigger/v3iostream/trigger.go +++ b/pkg/processor/trigger/v3iostream/trigger.go @@ -83,7 +83,7 @@ func newTrigger(parentLogger logger.Logger, if err != nil { return nil, errors.Wrap(err, "Failed to get v3io stream config") } - newTrigger.AbstractTrigger.Trigger = newTrigger + newTrigger.Trigger = newTrigger return newTrigger, nil } @@ -351,10 +351,10 @@ func (vs *v3iostream) newConsumerGroupMember() (streamconsumergroup.Member, erro } maxReplicas := 1 - if vs.configuration.RuntimeConfiguration.Config.Spec.Replicas != nil { - maxReplicas = *vs.configuration.RuntimeConfiguration.Config.Spec.Replicas - } else if vs.configuration.RuntimeConfiguration.Config.Spec.MaxReplicas != nil { - maxReplicas = *vs.configuration.RuntimeConfiguration.Config.Spec.MaxReplicas + if vs.configuration.RuntimeConfiguration.Spec.Replicas != nil { + maxReplicas = *vs.configuration.RuntimeConfiguration.Spec.Replicas + } else if vs.configuration.RuntimeConfiguration.Spec.MaxReplicas != nil { + maxReplicas = *vs.configuration.RuntimeConfiguration.Spec.MaxReplicas } streamConsumerGroup, err := streamconsumergroup.NewStreamConsumerGroup(vs.Logger, diff --git a/pkg/processor/trigger/v3iostream/types.go b/pkg/processor/trigger/v3iostream/types.go index 03392417652..affd82e8950 100644 --- a/pkg/processor/trigger/v3iostream/types.go +++ b/pkg/processor/trigger/v3iostream/types.go @@ -93,7 +93,7 @@ func NewConfiguration(id string, triggerConfiguration *functionconfig.Trigger, } // parse attributes - if err := mapstructure.Decode(newConfiguration.Configuration.Attributes, &newConfiguration); err != nil { + if err := mapstructure.Decode(newConfiguration.Attributes, &newConfiguration); err != nil { return nil, errors.Wrap(err, "Failed to decode attributes") } diff --git a/pkg/processor/util/v3io/v3ioutil.go b/pkg/processor/util/v3io/v3ioutil.go index 1c20c30c1c7..e2ac8f3ecb1 100644 --- a/pkg/processor/util/v3io/v3ioutil.go +++ b/pkg/processor/util/v3io/v3ioutil.go @@ -17,7 +17,6 @@ limitations under the License. package v3ioutil import ( - "fmt" "net/url" "strings" @@ -75,7 +74,7 @@ func ParseURL(rawURL string) (addr string, containerAlias string, path string, e // get the container alias (at the very least /x (2 chars) if len(parsedURL.RequestURI()) < 2 { - err = fmt.Errorf("Missing container alias: %s", rawURL) + err = errors.Errorf("Missing container alias: %s", rawURL) return } @@ -94,7 +93,7 @@ func ParseURL(rawURL string) (addr string, containerAlias string, path string, e containerAlias = containerAliasAndPath[0] case 0: - err = fmt.Errorf("Expected at least one part in request Host: %s", containerAliasAndPathString) + err = errors.Errorf("Expected at least one part in request Host: %s", containerAliasAndPathString) return } diff --git a/pkg/processwaiter/processwaiter.go b/pkg/processwaiter/processwaiter.go index bf2a16870d2..7be30e127f7 100644 --- a/pkg/processwaiter/processwaiter.go +++ b/pkg/processwaiter/processwaiter.go @@ -17,9 +17,10 @@ limitations under the License. package processwaiter import ( - "errors" "os" "time" + + "github.com/nuclio/errors" ) var ErrCancelled = errors.New("Wait cancelled") From 749eb69f4a5537ebf431d6388ca980d88625c9b1 Mon Sep 17 00:00:00 2001 From: rokatyy Date: Tue, 1 Jul 2025 13:41:32 +0100 Subject: [PATCH 2/4] merge --- pkg/processor/runtime/rpc/result/result.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/pkg/processor/runtime/rpc/result/result.go b/pkg/processor/runtime/rpc/result/result.go index 6ab8f3e9dde..6704391d9ce 100644 --- a/pkg/processor/runtime/rpc/result/result.go +++ b/pkg/processor/runtime/rpc/result/result.go @@ -195,10 +195,10 @@ func (sr *SingleResult) UnmarshalJSON(data []byte) error { if sr.Response == nil { sr.Response = &nuclio.Response{} } - sr.Response.StatusCode = rawResult.StatusCode - sr.Response.ContentType = rawResult.ContentType - sr.Response.Headers = rawResult.Headers - sr.Response.Body = decodedBody + sr.StatusCode = rawResult.StatusCode + sr.ContentType = rawResult.ContentType + sr.Headers = rawResult.Headers + sr.Body = decodedBody // Fill EventId sr.EventId = rawResult.EventId @@ -275,12 +275,13 @@ func NewResultFromData(data []byte) Result { return NewSingleResultsWithError(errors.New("Data is too short to contain a valid result")) } - if data[1] == '{' { + switch data[1] { + case '{': var singleResult *SingleResult if err := json.Unmarshal(data[1:], &singleResult); err == nil { return singleResult } - } else if data[1] == '[' { + case '[': var results []*SingleResult if err := json.Unmarshal(data[1:], &results); err == nil { return &BatchedResults{Results: results} From 96b54c7bf4d79f9ea857352b56c99b243498acd6 Mon Sep 17 00:00:00 2001 From: rokatyy Date: Tue, 1 Jul 2025 13:43:24 +0100 Subject: [PATCH 3/4] copyright back --- .golangci.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.golangci.yml b/.golangci.yml index 87e8127b2ec..6aae1484964 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,17 @@ +# Copyright 2023 The Nuclio Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# version: "2" run: build-tags: From 61e7516b8bab241cf740c81c9eac917b4ac7bcaa Mon Sep 17 00:00:00 2001 From: rokatyy Date: Fri, 4 Jul 2025 09:50:31 +0100 Subject: [PATCH 4/4] CR --- .golangci.yml | 13 +++++-------- Makefile | 2 +- pkg/functionconfig/handler.go | 5 +++-- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 6aae1484964..cb67dfa614a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,9 @@ # limitations under the License. # version: "2" + +# timeout for analysis +timeout: 5m run: build-tags: - test_unit @@ -66,10 +69,7 @@ linters: text: error should be the last paths: - docs - - vendor - - third_party$ - - builtin$ - - examples$ + - hack formatters: enable: - gci @@ -87,7 +87,4 @@ formatters: generated: lax paths: - docs - - vendor - - third_party$ - - builtin$ - - examples$ + - hack diff --git a/Makefile b/Makefile index 8dfe1899f82..c221843c2dc 100644 --- a/Makefile +++ b/Makefile @@ -702,7 +702,7 @@ ensure-golangci-linter: echo "golangci-lint not found. Installing..."; \ $(GOLANGCI_LINT_INSTALL_COMMAND); \ else \ - installed_version=$$($(GOLANGCI_LINT_BIN) version | awk '/version/ {print $$4}'); \ + installed_version=$$($(GOLANGCI_LINT_BIN) version | awk '/version/ {gsub(/^v/, "", $$4); print $$4}'); \ if [ "$$installed_version" != "$(GOLANGCI_LINT_VERSION)" ]; then \ echo "golangci-lint version mismatch ($$installed_version != $(GOLANGCI_LINT_VERSION)). Reinstalling..."; \ $(GOLANGCI_LINT_INSTALL_COMMAND); \ diff --git a/pkg/functionconfig/handler.go b/pkg/functionconfig/handler.go index 7f9b14d7f6a..0ff19767406 100644 --- a/pkg/functionconfig/handler.go +++ b/pkg/functionconfig/handler.go @@ -17,8 +17,9 @@ limitations under the License. package functionconfig import ( - "fmt" "strings" + + "github.com/nuclio/errors" ) func ParseHandler(handler string) (string, string, error) { @@ -36,6 +37,6 @@ func ParseHandler(handler string) (string, string, error) { return moduleAndEntrypoint[0], moduleAndEntrypoint[1], nil default: - return "", "", fmt.Errorf("invalid handler name %s", handler) + return "", "", errors.Errorf("Invalid handler name %s", handler) } }