From d892cf692882a6490e6ac1af152e3c244ca43be1 Mon Sep 17 00:00:00 2001 From: Korbinian Stoemmer Date: Tue, 5 Dec 2023 17:54:51 +0100 Subject: [PATCH] enable more linters (#282) * enable nestif * enable gomoddirectives * enable nilerr * enable forbidigo * enable gofmt * enable gci * enable goimports * enable exhaustive * enable loggercheck * enable wastedassign * enable dupword * enable gofumpt * update go.mod and go.sum --- .golangci.yaml | 16 +---- api/eventing/v1alpha1/condition_unit_test.go | 5 +- api/eventing/v1alpha1/fixtures_test.go | 28 ++++---- .../v1alpha1/subscription_conversion.go | 49 +++++++------- .../subscription_conversion_unit_test.go | 12 ++-- api/eventing/v1alpha1/subscription_types.go | 8 +-- .../v1alpha1/subscription_types_unit_test.go | 3 +- api/eventing/v1alpha2/condition_unit_test.go | 10 ++- api/eventing/v1alpha2/errors.go | 4 +- api/eventing/v1alpha2/subscription_types.go | 8 +-- .../v1alpha2/subscription_types_test.go | 13 ++-- api/eventing/v1alpha2/subscription_webhook.go | 7 +- .../subscription_webhook_unit_test.go | 14 ++-- api/operator/v1alpha1/eventing_types.go | 16 ++--- api/operator/v1alpha1/groupversion_info.go | 4 +- api/operator/v1alpha1/status.go | 15 +++-- cmd/main.go | 25 +++---- go.mod | 6 +- go.sum | 12 ++-- hack/e2e/common/eventing/publisher.go | 7 +- hack/e2e/common/eventing/sinkclient.go | 3 +- hack/e2e/common/eventing/utils.go | 2 +- hack/e2e/common/fixtures/fixtures.go | 11 ++- hack/e2e/common/k8s.go | 13 ++-- .../testenvironment/test_environment.go | 13 ++-- hack/e2e/env/env.go | 20 +++--- .../subscription/eventmesh/reconciler.go | 51 +++++++------- .../reconciler_internal_integration_test.go | 23 +++---- .../subscription/eventmesh/test/assertions.go | 9 +-- .../test/reconciler_integration_test.go | 46 +++++++------ .../subscription/eventmesh/test/utils.go | 8 +-- .../eventmesh/testwebhookauth/assertions.go | 9 +-- .../reconciler_integration_test.go | 5 +- .../eventmesh/testwebhookauth/utils.go | 8 +-- .../eventing/subscription/eventmesh/utils.go | 2 +- .../subscription/eventmesh/utils_test.go | 18 +++-- .../subscription/jetstream/matchers_test.go | 9 +-- .../subscription/jetstream/reconciler.go | 39 +++++------ .../jetstream/reconciler_integration_test.go | 12 ++-- .../reconciler_internal_unit_test.go | 7 +- .../subscription/jetstream/test_utils_test.go | 51 +++++++------- .../operator/eventing/controller.go | 15 +++-- .../operator/eventing/controller_test.go | 6 +- .../controller/operator/eventing/eventmesh.go | 4 +- .../operator/eventing/eventmesh_test.go | 10 ++- .../controller/integration_test.go | 11 ++- .../controller_switching/integration_test.go | 3 +- .../controllersinglecr/integration_test.go | 6 +- .../nats_disabled/integration_test.go | 11 ++- internal/controller/operator/eventing/nats.go | 4 +- .../controller/operator/eventing/nats_test.go | 6 +- .../controller/operator/eventing/status.go | 34 ++++++---- .../controller/operator/eventing/unit_test.go | 27 +++----- .../operator/eventing/utils_test.go | 3 - .../controller/operator/eventing/webhook.go | 3 +- options/options.go | 4 +- pkg/backend/cleaner/jetstream_unit_test.go | 3 +- pkg/backend/eventmesh/eventmesh.go | 27 +++++--- .../eventmesh/eventmesh_integration_test.go | 3 +- pkg/backend/eventmesh/mocks/Backend.go | 2 +- pkg/backend/eventmesh/types.go | 2 +- pkg/backend/eventmesh/utils.go | 32 ++++----- .../eventtype/clean_internal_unit_test.go | 2 +- pkg/backend/eventtype/simple_clean.go | 8 +-- .../jetstream/config_internal_unit_test.go | 3 +- .../jetstream/connection_integration_test.go | 3 +- pkg/backend/jetstream/jetstream.go | 45 ++++++++----- .../jetstream/jetstream_integration_test.go | 9 +-- .../jetstream/jetstream_internal_unit_test.go | 16 ++--- pkg/backend/jetstream/stubs_test.go | 12 ++-- pkg/backend/jetstream/test_helpers.go | 16 ++--- pkg/backend/jetstream/types.go | 6 +- pkg/backend/jetstream/utils.go | 40 ++++++----- .../jetstream/utils_internal_unit_test.go | 6 +- pkg/backend/metrics/collector.go | 9 ++- pkg/backend/sink/validator.go | 8 +-- pkg/backend/utils/eventmesh_utils.go | 12 ++-- pkg/backend/utils/eventmesh_utils_test.go | 10 ++- pkg/backend/utils/utils.go | 16 ++--- pkg/cloudevent/client_unit_test.go | 3 +- pkg/ems/auth/auth.go | 2 +- pkg/ems/auth/auth_unit_test.go | 4 +- pkg/env/backend_config.go | 38 +++++------ pkg/env/config.go | 22 +++--- pkg/env/nats_config.go | 22 +++--- pkg/env/nats_config_test.go | 9 +-- pkg/eventing/deployment.go | 32 +++++---- pkg/eventing/deployment_test.go | 8 +-- pkg/eventing/manager.go | 26 +++---- pkg/eventing/manager_test.go | 19 ++---- pkg/eventing/utils.go | 12 ++-- .../peerauthentication/peerauthentication.go | 5 +- .../peerauthentication_test.go | 7 +- pkg/k8s/client.go | 13 ++-- pkg/k8s/client_test.go | 18 ++--- pkg/logger/logger_test.go | 3 +- pkg/object/apirule.go | 6 +- pkg/object/apirule_test.go | 2 +- pkg/object/equality.go | 3 +- pkg/object/equality_test.go | 12 ++-- pkg/object/object.go | 2 +- .../eventmesh/eventmesh.go | 17 ++--- .../eventmesh/eventmesh_test.go | 17 ++--- pkg/subscriptionmanager/factory.go | 8 +-- .../jetstream/jetstream.go | 21 +++--- .../jetstream/jetstream_test.go | 6 +- pkg/tracing/tracing.go | 3 +- pkg/tracing/tracing_test.go | 1 + pkg/utils/utils.go | 5 +- test/utils.go | 4 +- test/utils/integration/integration.go | 67 +++++++++---------- test/utils/utils.go | 16 ++--- testing/eventmesh_unit_test.go | 4 +- testing/eventmeshmock.go | 21 +++--- testing/matchers.go | 9 +-- testing/subscriber.go | 5 +- testing/test_helpers.go | 23 ++++--- 117 files changed, 758 insertions(+), 795 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 0ebda8f3..1de839f0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -21,13 +21,9 @@ linters: ### disabled for now... will be enabled 1 by 1 - containedctx - dupl - - dupword - errorlint - - exhaustive - - forbidigo - forcetypeassert - funlen - - gci - ginkgolinter - gochecknoglobals - gochecknoinits @@ -36,18 +32,11 @@ linters: - gocritic - godox - goerr113 - - gofumpt - - gofmt - gomnd - - gomoddirectives - gosec - inamedparam - - interfacebloat - ireturn - - loggercheck - maintidx - - nestif - - nilerr - noctx - nolintlint - nonamedreturns @@ -62,11 +51,8 @@ linters: - unconvert - unparam - varnamelen - - wastedassign - wrapcheck - godot - - goimports - - mirror - tagalign - whitespace @@ -133,7 +119,7 @@ linters-settings: alias: eventingv1alpha2 - pkg: github.com/kyma-project/eventing-manager/api/operator/v1alpha1 alias: operatorv1alpha1 - - pkg: github.com/kyma-incubator/api-gateway/api/v1beta1 + - pkg: github.com/kyma-project/api-gateway/apis/gateway/v1beta1 alias: apigatewayv1beta1 - pkg: k8s.io/client-go/dynamic/fake alias: kdynamicfake diff --git a/api/eventing/v1alpha1/condition_unit_test.go b/api/eventing/v1alpha1/condition_unit_test.go index f5d33bc1..1a334e52 100644 --- a/api/eventing/v1alpha1/condition_unit_test.go +++ b/api/eventing/v1alpha1/condition_unit_test.go @@ -5,15 +5,16 @@ import ( "testing" "time" - . "github.com/onsi/gomega" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + + . "github.com/onsi/gomega" ) func Test_InitializeSubscriptionConditions(t *testing.T) { - var tests = []struct { + tests := []struct { name string givenConditions []v1alpha1.Condition }{ diff --git a/api/eventing/v1alpha1/fixtures_test.go b/api/eventing/v1alpha1/fixtures_test.go index 474a1d23..1ee905f2 100644 --- a/api/eventing/v1alpha1/fixtures_test.go +++ b/api/eventing/v1alpha1/fixtures_test.go @@ -3,13 +3,12 @@ package v1alpha1_test import ( "fmt" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - "github.com/kyma-project/eventing-manager/pkg/utils" - eventingtesting "github.com/kyma-project/eventing-manager/testing" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/pkg/utils" + eventingtesting "github.com/kyma-project/eventing-manager/testing" ) const ( @@ -30,17 +29,16 @@ const ( defaultStatusReady = true ) -var ( - v2DefaultConditions = []v1alpha2.Condition{ - { - Type: v1alpha2.ConditionSubscriptionActive, - Status: "true", - }, - { - Type: v1alpha2.ConditionSubscribed, - Status: "false", - }} -) +var v2DefaultConditions = []v1alpha2.Condition{ + { + Type: v1alpha2.ConditionSubscriptionActive, + Status: "true", + }, + { + Type: v1alpha2.ConditionSubscribed, + Status: "false", + }, +} func newDefaultSubscription(opts ...eventingtesting.SubscriptionV1alpha1Opt) *v1alpha1.Subscription { var defaultConditions []v1alpha1.Condition diff --git a/api/eventing/v1alpha1/subscription_conversion.go b/api/eventing/v1alpha1/subscription_conversion.go index f6d8205e..5e3cb7df 100644 --- a/api/eventing/v1alpha1/subscription_conversion.go +++ b/api/eventing/v1alpha1/subscription_conversion.go @@ -5,12 +5,11 @@ import ( "strconv" "strings" - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" - "github.com/pkg/errors" "sigs.k8s.io/controller-runtime/pkg/conversion" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" ) const ( @@ -62,7 +61,7 @@ func V1ToV2(src *Subscription, dst *v1alpha2.Subscription) error { } // ConvertFrom converts this Subscription from the Hub version (v2) to v1. -func (dst *Subscription) ConvertFrom(srcRaw conversion.Hub) error { //nolint:revive +func (dst *Subscription) ConvertFrom(srcRaw conversion.Hub) error { src, ok := srcRaw.(*v1alpha2.Subscription) if !ok { return errors.Errorf(ErrorHubVersionMsg) @@ -133,27 +132,31 @@ func (src *Subscription) setV2ProtocolFields(dst *v1alpha2.Subscription) { } // protocol settings if src.Spec.ProtocolSettings != nil { - if src.Spec.ProtocolSettings.ContentMode != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsContentMode] = *src.Spec.ProtocolSettings.ContentMode - } - if src.Spec.ProtocolSettings.ExemptHandshake != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsExemptHandshake] = fmt.Sprint(*src.Spec.ProtocolSettings.ExemptHandshake) - } - if src.Spec.ProtocolSettings.Qos != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsQos] = *src.Spec.ProtocolSettings.Qos + src.setProtocolSettings(dst) + } +} + +func (src *Subscription) setProtocolSettings(dst *v1alpha2.Subscription) { + if src.Spec.ProtocolSettings.ContentMode != nil { + dst.Spec.Config[v1alpha2.ProtocolSettingsContentMode] = *src.Spec.ProtocolSettings.ContentMode + } + if src.Spec.ProtocolSettings.ExemptHandshake != nil { + dst.Spec.Config[v1alpha2.ProtocolSettingsExemptHandshake] = fmt.Sprint(*src.Spec.ProtocolSettings.ExemptHandshake) + } + if src.Spec.ProtocolSettings.Qos != nil { + dst.Spec.Config[v1alpha2.ProtocolSettingsQos] = *src.Spec.ProtocolSettings.Qos + } + // webhookAuth fields + if src.Spec.ProtocolSettings.WebhookAuth != nil { + if src.Spec.ProtocolSettings.WebhookAuth.Type != "" { + dst.Spec.Config[v1alpha2.WebhookAuthType] = src.Spec.ProtocolSettings.WebhookAuth.Type } - // webhookAuth fields - if src.Spec.ProtocolSettings.WebhookAuth != nil { - if src.Spec.ProtocolSettings.WebhookAuth.Type != "" { - dst.Spec.Config[v1alpha2.WebhookAuthType] = src.Spec.ProtocolSettings.WebhookAuth.Type - } - dst.Spec.Config[v1alpha2.WebhookAuthGrantType] = src.Spec.ProtocolSettings.WebhookAuth.GrantType - dst.Spec.Config[v1alpha2.WebhookAuthClientID] = src.Spec.ProtocolSettings.WebhookAuth.ClientID - dst.Spec.Config[v1alpha2.WebhookAuthClientSecret] = src.Spec.ProtocolSettings.WebhookAuth.ClientSecret - dst.Spec.Config[v1alpha2.WebhookAuthTokenURL] = src.Spec.ProtocolSettings.WebhookAuth.TokenURL - if src.Spec.ProtocolSettings.WebhookAuth.Scope != nil { - dst.Spec.Config[v1alpha2.WebhookAuthScope] = strings.Join(src.Spec.ProtocolSettings.WebhookAuth.Scope, ",") - } + dst.Spec.Config[v1alpha2.WebhookAuthGrantType] = src.Spec.ProtocolSettings.WebhookAuth.GrantType + dst.Spec.Config[v1alpha2.WebhookAuthClientID] = src.Spec.ProtocolSettings.WebhookAuth.ClientID + dst.Spec.Config[v1alpha2.WebhookAuthClientSecret] = src.Spec.ProtocolSettings.WebhookAuth.ClientSecret + dst.Spec.Config[v1alpha2.WebhookAuthTokenURL] = src.Spec.ProtocolSettings.WebhookAuth.TokenURL + if src.Spec.ProtocolSettings.WebhookAuth.Scope != nil { + dst.Spec.Config[v1alpha2.WebhookAuthScope] = strings.Join(src.Spec.ProtocolSettings.WebhookAuth.Scope, ",") } } } diff --git a/api/eventing/v1alpha1/subscription_conversion_unit_test.go b/api/eventing/v1alpha1/subscription_conversion_unit_test.go index 563caf94..0fda40c4 100644 --- a/api/eventing/v1alpha1/subscription_conversion_unit_test.go +++ b/api/eventing/v1alpha1/subscription_conversion_unit_test.go @@ -3,19 +3,15 @@ package v1alpha1_test import ( "testing" - "github.com/kyma-project/eventing-manager/pkg/logger" - - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" - - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" - - eventingtesting "github.com/kyma-project/eventing-manager/testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" + "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + "github.com/kyma-project/eventing-manager/pkg/logger" + eventingtesting "github.com/kyma-project/eventing-manager/testing" ) func Test_Conversion(t *testing.T) { diff --git a/api/eventing/v1alpha1/subscription_types.go b/api/eventing/v1alpha1/subscription_types.go index 66836244..ca52fbcd 100644 --- a/api/eventing/v1alpha1/subscription_types.go +++ b/api/eventing/v1alpha1/subscription_types.go @@ -19,7 +19,7 @@ const ( var Finalizer = GroupVersion.Group // WebhookAuth defines the Webhook called by an active subscription in BEB. -// TODO: Remove it when depreciating code of v1alpha1 +// TODO: Remove it when depreciating code of v1alpha1. type WebhookAuth struct { // Defines the authentication type. // +optional @@ -42,7 +42,7 @@ type WebhookAuth struct { } // ProtocolSettings defines the CE protocol setting specification implementation. -// TODO: Remove it when depreciating code of v1alpha1 +// TODO: Remove it when depreciating code of v1alpha1. type ProtocolSettings struct { // Defines the content mode for eventing based on BEB. // The value is either `BINARY`, or `STRUCTURED`. @@ -62,7 +62,7 @@ type ProtocolSettings struct { WebhookAuth *WebhookAuth `json:"webhookAuth,omitempty"` } -// TODO: Remove it when depreciating code of v1alpha1 +// TODO: Remove it when depreciating code of v1alpha1. const ( ProtocolSettingsContentModeBinary string = "BINARY" ProtocolSettingsContentModeStructured string = "STRUCTURED" @@ -267,7 +267,7 @@ func (s Subscription) MarshalJSON() ([]byte, error) { type SubscriptionList struct { kmetav1.TypeMeta `json:",inline"` kmetav1.ListMeta `json:"metadata,omitempty"` - Items []Subscription `json:"items"` + Items []Subscription `json:"items"` } // InitializeCleanEventTypes initializes the SubscriptionStatus.CleanEventTypes with an empty slice of strings. diff --git a/api/eventing/v1alpha1/subscription_types_unit_test.go b/api/eventing/v1alpha1/subscription_types_unit_test.go index ce2f62be..f755a3a0 100644 --- a/api/eventing/v1alpha1/subscription_types_unit_test.go +++ b/api/eventing/v1alpha1/subscription_types_unit_test.go @@ -6,9 +6,8 @@ import ( "github.com/stretchr/testify/require" - "github.com/kyma-project/eventing-manager/pkg/env" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + "github.com/kyma-project/eventing-manager/pkg/env" ) func TestBEBFilters_Deduplicate(t *testing.T) { diff --git a/api/eventing/v1alpha2/condition_unit_test.go b/api/eventing/v1alpha2/condition_unit_test.go index 0abeb21e..c39c190c 100644 --- a/api/eventing/v1alpha2/condition_unit_test.go +++ b/api/eventing/v1alpha2/condition_unit_test.go @@ -6,20 +6,18 @@ import ( "time" "github.com/pkg/errors" - - eventingtesting "github.com/kyma-project/eventing-manager/testing" - "github.com/stretchr/testify/require" - - . "github.com/onsi/gomega" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + eventingtesting "github.com/kyma-project/eventing-manager/testing" + + . "github.com/onsi/gomega" ) func Test_InitializeSubscriptionConditions(t *testing.T) { - var tests = []struct { + tests := []struct { name string givenConditions []v1alpha2.Condition }{ diff --git a/api/eventing/v1alpha2/errors.go b/api/eventing/v1alpha2/errors.go index 09fe2668..6afbe419 100644 --- a/api/eventing/v1alpha2/errors.go +++ b/api/eventing/v1alpha2/errors.go @@ -4,9 +4,9 @@ import ( "fmt" "strconv" - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" - "k8s.io/apimachinery/pkg/util/validation/field" + + "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" ) //nolint:gochecknoglobals // these are required for testing diff --git a/api/eventing/v1alpha2/subscription_types.go b/api/eventing/v1alpha2/subscription_types.go index b50c7a0d..a5ce05b7 100644 --- a/api/eventing/v1alpha2/subscription_types.go +++ b/api/eventing/v1alpha2/subscription_types.go @@ -4,14 +4,12 @@ import ( "encoding/json" "strconv" - "github.com/kyma-project/eventing-manager/pkg/env" - + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kunstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" kruntime "k8s.io/apimachinery/pkg/runtime" + "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/utils" - - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type TypeMatching string @@ -135,7 +133,7 @@ func (s *Subscription) ToUnstructuredSub() (*kunstructured.Unstructured, error) type SubscriptionList struct { kmetav1.TypeMeta `json:",inline"` kmetav1.ListMeta `json:"metadata,omitempty"` - Items []Subscription `json:"items"` + Items []Subscription `json:"items"` } func init() { //nolint:gochecknoinits diff --git a/api/eventing/v1alpha2/subscription_types_test.go b/api/eventing/v1alpha2/subscription_types_test.go index 78610994..a0b7453c 100644 --- a/api/eventing/v1alpha2/subscription_types_test.go +++ b/api/eventing/v1alpha2/subscription_types_test.go @@ -3,10 +3,10 @@ package v1alpha2_test import ( "testing" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/stretchr/testify/assert" + "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/env" - "github.com/stretchr/testify/assert" ) func TestGetMaxInFlightMessages(t *testing.T) { @@ -30,7 +30,8 @@ func TestGetMaxInFlightMessages(t *testing.T) { givenSubscription: &v1alpha2.Subscription{ Spec: v1alpha2.SubscriptionSpec{ Config: map[string]string{ - "otherConfigKey": "20"}, + "otherConfigKey": "20", + }, }, }, wantResult: defaultSubConfig.MaxInFlightMessages, @@ -40,7 +41,8 @@ func TestGetMaxInFlightMessages(t *testing.T) { givenSubscription: &v1alpha2.Subscription{ Spec: v1alpha2.SubscriptionSpec{ Config: map[string]string{ - v1alpha2.MaxInFlightMessages: "20"}, + v1alpha2.MaxInFlightMessages: "20", + }, }, }, wantResult: 20, @@ -50,7 +52,8 @@ func TestGetMaxInFlightMessages(t *testing.T) { givenSubscription: &v1alpha2.Subscription{ Spec: v1alpha2.SubscriptionSpec{ Config: map[string]string{ - v1alpha2.MaxInFlightMessages: "nonInt"}, + v1alpha2.MaxInFlightMessages: "nonInt", + }, }, }, wantResult: defaultSubConfig.MaxInFlightMessages, diff --git a/api/eventing/v1alpha2/subscription_webhook.go b/api/eventing/v1alpha2/subscription_webhook.go index c156447f..db4b889c 100644 --- a/api/eventing/v1alpha2/subscription_webhook.go +++ b/api/eventing/v1alpha2/subscription_webhook.go @@ -4,16 +4,15 @@ import ( "strconv" "strings" - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" - - "github.com/kyma-project/eventing-manager/pkg/utils" - kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" kctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + "github.com/kyma-project/eventing-manager/pkg/utils" ) const ( diff --git a/api/eventing/v1alpha2/subscription_webhook_unit_test.go b/api/eventing/v1alpha2/subscription_webhook_unit_test.go index 9194cdf2..c99597fe 100644 --- a/api/eventing/v1alpha2/subscription_webhook_unit_test.go +++ b/api/eventing/v1alpha2/subscription_webhook_unit_test.go @@ -179,8 +179,10 @@ func Test_validateSubscription(t *testing.T) { givenSub: eventingtesting.NewSubscription(subName, subNamespace, eventingtesting.WithTypeMatchingStandard(), eventingtesting.WithSource(eventingtesting.EventSourceClean), - eventingtesting.WithTypes([]string{eventingtesting.OrderCreatedV1Event, - eventingtesting.OrderCreatedV1Event}), + eventingtesting.WithTypes([]string{ + eventingtesting.OrderCreatedV1Event, + eventingtesting.OrderCreatedV1Event, + }), eventingtesting.WithMaxInFlightMessages(v1alpha2.DefaultMaxInFlightMessages), eventingtesting.WithSink(sink), ), @@ -409,10 +411,12 @@ func Test_validateSubscription(t *testing.T) { ), wantErr: kerrors.NewInvalid( v1alpha2.GroupKind, subName, - field.ErrorList{v1alpha2.MakeInvalidFieldError(v1alpha2.SourcePath, - subName, v1alpha2.EmptyErrDetail), + field.ErrorList{ + v1alpha2.MakeInvalidFieldError(v1alpha2.SourcePath, + subName, v1alpha2.EmptyErrDetail), v1alpha2.MakeInvalidFieldError(v1alpha2.ConfigPath, - subName, v1alpha2.StringIntErrDetail)}), + subName, v1alpha2.StringIntErrDetail), + }), }, } diff --git a/api/operator/v1alpha1/eventing_types.go b/api/operator/v1alpha1/eventing_types.go index f1af176d..c7b21be0 100644 --- a/api/operator/v1alpha1/eventing_types.go +++ b/api/operator/v1alpha1/eventing_types.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// nolint:lll //this is annotation +//nolint:lll //this is annotation package v1alpha1 import ( @@ -39,12 +39,12 @@ const ( ConditionSubscriptionManagerReady ConditionType = "SubscriptionManagerReady" ConditionDeleted ConditionType = "Deleted" - // common reasons + // common reasons. ConditionReasonProcessing ConditionReason = "Processing" ConditionReasonDeleted ConditionReason = "Deleted" ConditionReasonStopped ConditionReason = "Stopped" - // publisher proxy reasons + // publisher proxy reasons. ConditionReasonDeployed ConditionReason = "Deployed" ConditionReasonDeployedFailed ConditionReason = "DeployFailed" ConditionReasonDeploymentStatusSyncFailed ConditionReason = "DeploymentStatusSyncFailed" @@ -55,7 +55,7 @@ const ( ConditionReasonWebhookReady ConditionReason = "Ready" ConditionReasonDeletionError ConditionReason = "DeletionError" - // message for conditions + // message for conditions. ConditionPublisherProxyReadyMessage = "Publisher proxy is deployed" ConditionPublisherProxyDeletedMessage = "Publisher proxy is deleted" ConditionNATSAvailableMessage = "NATS is available" @@ -64,7 +64,7 @@ const ( ConditionSubscriptionManagerReadyMessage = "Subscription manager is ready" ConditionSubscriptionManagerStoppedMessage = "Subscription manager is stopped" - // subscription manager reasons + // subscription manager reasons. ConditionReasonEventMeshSubManagerReady ConditionReason = "EventMeshSubscriptionManagerReady" ConditionReasonEventMeshSubManagerFailed ConditionReason = "EventMeshSubscriptionManagerFailed" ConditionReasonEventMeshSubManagerStopFailed ConditionReason = "EventMeshSubscriptionManagerStopFailed" @@ -87,7 +87,7 @@ type Eventing struct { Status EventingStatus `json:"status,omitempty"` } -// EventingStatus defines the observed state of Eventing +// EventingStatus defines the observed state of Eventing. type EventingStatus struct { ActiveBackend BackendType `json:"activeBackend"` BackendConfigHash int64 `json:"specHash"` @@ -95,7 +95,7 @@ type EventingStatus struct { Conditions []kmetav1.Condition `json:"conditions,omitempty"` } -// EventingSpec defines the desired state of Eventing +// EventingSpec defines the desired state of Eventing. type EventingSpec struct { // Backend defines the active backend used by Eventing. // +kubebuilder:default:={type:"NATS", config:{natsStreamStorageType:"File", natsStreamReplicas:3, natsStreamMaxSize:"700Mi", natsMaxMsgsPerTopic:1000000}} @@ -119,7 +119,7 @@ type EventingSpec struct { // +kubebuilder:object:root=true -// EventingList contains a list of Eventing +// EventingList contains a list of Eventing. type EventingList struct { kmetav1.TypeMeta `json:",inline"` kmetav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/operator/v1alpha1/groupversion_info.go b/api/operator/v1alpha1/groupversion_info.go index d5f916d3..34c9e3d4 100644 --- a/api/operator/v1alpha1/groupversion_info.go +++ b/api/operator/v1alpha1/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "operator.kyma-project.io", Version: "v1alpha1"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/api/operator/v1alpha1/status.go b/api/operator/v1alpha1/status.go index 03222d63..f79fda59 100644 --- a/api/operator/v1alpha1/status.go +++ b/api/operator/v1alpha1/status.go @@ -9,7 +9,8 @@ import ( ) func (es *EventingStatus) UpdateConditionNATSAvailable(status kmetav1.ConditionStatus, reason ConditionReason, - message string) { + message string, +) { condition := kmetav1.Condition{ Type: string(ConditionNATSAvailable), Status: status, @@ -21,7 +22,8 @@ func (es *EventingStatus) UpdateConditionNATSAvailable(status kmetav1.ConditionS } func (es *EventingStatus) UpdateConditionPublisherProxyReady(status kmetav1.ConditionStatus, reason ConditionReason, - message string) { + message string, +) { condition := kmetav1.Condition{ Type: string(ConditionPublisherProxyReady), Status: status, @@ -33,7 +35,8 @@ func (es *EventingStatus) UpdateConditionPublisherProxyReady(status kmetav1.Cond } func (es *EventingStatus) UpdateConditionWebhookReady(status kmetav1.ConditionStatus, reason ConditionReason, - message string) { + message string, +) { condition := kmetav1.Condition{ Type: string(ConditionWebhookReady), Status: status, @@ -45,7 +48,8 @@ func (es *EventingStatus) UpdateConditionWebhookReady(status kmetav1.ConditionSt } func (sm *EventingStatus) UpdateConditionSubscriptionManagerReady(status kmetav1.ConditionStatus, reason ConditionReason, - message string) { + message string, +) { condition := kmetav1.Condition{ Type: string(ConditionSubscriptionManagerReady), Status: status, @@ -57,7 +61,8 @@ func (sm *EventingStatus) UpdateConditionSubscriptionManagerReady(status kmetav1 } func (es *EventingStatus) UpdateConditionDeletion(status kmetav1.ConditionStatus, reason ConditionReason, - message string) { + message string, +) { condition := kmetav1.Condition{ Type: string(ConditionDeleted), Status: status, diff --git a/cmd/main.go b/cmd/main.go index 86c60fe6..925a7ce7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -23,16 +23,23 @@ import ( "os" "github.com/go-logr/zapr" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kapiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" kapixclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" kutilruntime "k8s.io/apimachinery/pkg/util/runtime" - - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + "k8s.io/client-go/dynamic" + kkubernetesscheme "k8s.io/client-go/kubernetes/scheme" + kctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" controllercache "github.com/kyma-project/eventing-manager/internal/controller/cache" controllerclient "github.com/kyma-project/eventing-manager/internal/controller/client" eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" @@ -45,20 +52,6 @@ import ( "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager" "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/jetstream" - - // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) - // to ensure that exec-entrypoint and run can make use of them. - "k8s.io/client-go/dynamic" - kkubernetesscheme "k8s.io/client-go/kubernetes/scheme" - _ "k8s.io/client-go/plugin/pkg/client/auth" - kctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/metrics/server" - "sigs.k8s.io/controller-runtime/pkg/webhook" - - operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - //+kubebuilder:scaffold:imports ) var ( diff --git a/go.mod b/go.mod index 2759fb21..56d27f47 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/go-logr/zapr v1.3.0 github.com/google/uuid v1.4.0 github.com/kelseyhightower/envconfig v1.4.0 - github.com/kyma-incubator/api-gateway v0.0.0-20220819093753-296e6704d413 + github.com/kyma-project/api-gateway v0.0.0-20231205091251-e217d20481f1 github.com/kyma-project/kyma/common/logging v0.0.0-20231113125307-562a57ab5198 github.com/kyma-project/nats-manager v1.0.3-0.20231124103356-1904d89ab2b2 github.com/mitchellh/hashstructure/v2 v2.0.2 @@ -101,7 +101,7 @@ require ( golang.org/x/sys v0.15.0 // indirect golang.org/x/term v0.15.0 // indirect golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.4.0 // indirect + golang.org/x/time v0.5.0 // indirect golang.org/x/tools v0.14.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect google.golang.org/appengine v1.6.8 // indirect @@ -120,5 +120,3 @@ require ( sigs.k8s.io/structured-merge-diff/v4 v4.3.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) - -replace github.com/kyma-incubator/api-gateway => github.com/kyma-project/api-gateway v0.0.0-20220819093753-296e6704d413 diff --git a/go.sum b/go.sum index 27397366..4c6cdc8f 100644 --- a/go.sum +++ b/go.sum @@ -216,8 +216,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kyma-project/api-gateway v0.0.0-20220819093753-296e6704d413 h1:fkGKNOFbltycpdQ7yCGfa+7MpH9X18F09x+n7Tgfp7A= -github.com/kyma-project/api-gateway v0.0.0-20220819093753-296e6704d413/go.mod h1:5kBV6C2JEaapjTAn10Mo81Te4e6LN3epexUCSLXgQLI= +github.com/kyma-project/api-gateway v0.0.0-20231205091251-e217d20481f1 h1:D/0EPcBZYYSnTBYcnzkJe0POmrtEFrQI+t8uiqXEOIk= +github.com/kyma-project/api-gateway v0.0.0-20231205091251-e217d20481f1/go.mod h1:MnfB9IW+mJc1Q5YMxEwgrZeRsJ4+E5j5to09pjt4BiE= github.com/kyma-project/kyma/common/logging v0.0.0-20231113125307-562a57ab5198 h1:xz4kPj7u51OgP+0f58OeaQlyiGm6AwEHALjbiLeK3Ec= github.com/kyma-project/kyma/common/logging v0.0.0-20231113125307-562a57ab5198/go.mod h1:JGb5RBi8Uz+RZ/jf54+qA+RqY6uPQBJ8pO1w3KSwm1Q= github.com/kyma-project/nats-manager v1.0.3-0.20231124103356-1904d89ab2b2 h1:P8SMLPxQMCnPlwGMpqid5ofHPO2dvybu94F8K32GNmw= @@ -267,8 +267,8 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= -github.com/onsi/ginkgo/v2 v2.13.1 h1:LNGfMbR2OVGBfXjvRZIZ2YCTQdGKtPLvuI1rMCCj3OU= -github.com/onsi/ginkgo/v2 v2.13.1/go.mod h1:XStQ8QcGwLyF4HdfcZB8SFOS/MWCgDuXMSBe6zrvLgM= +github.com/onsi/ginkgo/v2 v2.13.2 h1:Bi2gGVkfn6gQcjNjZJVO8Gf0FHzMPf2phUei9tejVMs= +github.com/onsi/ginkgo/v2 v2.13.2/go.mod h1:XStQ8QcGwLyF4HdfcZB8SFOS/MWCgDuXMSBe6zrvLgM= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.30.0 h1:hvMK7xYz4D3HapigLTeGdId/NcfQx1VHMJc60ew99+8= @@ -521,8 +521,8 @@ golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.4.0 h1:Z81tqI5ddIoXDPvVQ7/7CC9TnLM7ubaFG2qXYd5BbYY= -golang.org/x/time v0.4.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= diff --git a/hack/e2e/common/eventing/publisher.go b/hack/e2e/common/eventing/publisher.go index 6c55dd5c..daf560fe 100644 --- a/hack/e2e/common/eventing/publisher.go +++ b/hack/e2e/common/eventing/publisher.go @@ -10,11 +10,11 @@ import ( cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" - "github.com/cloudevents/sdk-go/v2/client" - "github.com/kyma-project/eventing-manager/hack/e2e/common" "github.com/pkg/errors" "go.uber.org/zap" + + "github.com/kyma-project/eventing-manager/hack/e2e/common" ) const ( @@ -63,7 +63,7 @@ func (p *Publisher) SendCloudEventWithRetries(event *cloudevents.Event, encoding func (p *Publisher) SendLegacyEvent(source, eventType, payload string) error { url := p.LegacyPublishEndpoint(source) - req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer([]byte(payload))) + req, err := http.NewRequest(http.MethodPost, url, bytes.NewBufferString(payload)) if err != nil { err = errors.Wrap(err, "Failed to create HTTP request for sending legacy event") p.logger.Debug(err.Error()) @@ -113,6 +113,7 @@ func (p *Publisher) SendCloudEvent(event *cloudevents.Event, encoding binding.En ce := *event newCtx := context.Background() ctx := cloudevents.ContextWithTarget(newCtx, p.PublishEndpoint()) + //nolint:exhaustive // we only support the two checked encodings. Every other encoding will result in an error. switch encoding { case binding.EncodingBinary: { diff --git a/hack/e2e/common/eventing/sinkclient.go b/hack/e2e/common/eventing/sinkclient.go index 5cf5360f..a8911b9d 100644 --- a/hack/e2e/common/eventing/sinkclient.go +++ b/hack/e2e/common/eventing/sinkclient.go @@ -11,9 +11,10 @@ import ( cloudevents "github.com/cloudevents/sdk-go/v2" ceevent "github.com/cloudevents/sdk-go/v2/event" - "github.com/kyma-project/eventing-manager/hack/e2e/common" "github.com/pkg/errors" "go.uber.org/zap" + + "github.com/kyma-project/eventing-manager/hack/e2e/common" ) const ( diff --git a/hack/e2e/common/eventing/utils.go b/hack/e2e/common/eventing/utils.go index 4df6b528..d718698f 100644 --- a/hack/e2e/common/eventing/utils.go +++ b/hack/e2e/common/eventing/utils.go @@ -7,7 +7,6 @@ import ( cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" - "github.com/google/uuid" ) @@ -24,6 +23,7 @@ func Is2XX(statusCode int) bool { func LegacyEventData(source, eventType string) string { return `{\"` + keyApp + `\":\"` + source + `\",\"` + keyMode + `\":\"legacy\",\"` + keyType + `\":\"` + eventType + `\"}` } + func LegacyEventPayload(eventId, eventVersion, eventType, data string) string { return `{"data":"` + data + `","event-id":"` + eventId + `","event-type":"` + eventType + `","event-time":"2020-04-02T21:37:00Z","event-type-version":"` + eventVersion + `"}` } diff --git a/hack/e2e/common/fixtures/fixtures.go b/hack/e2e/common/fixtures/fixtures.go index e13945b9..01de7c2b 100644 --- a/hack/e2e/common/fixtures/fixtures.go +++ b/hack/e2e/common/fixtures/fixtures.go @@ -5,18 +5,15 @@ import ( "fmt" "strings" - "k8s.io/apimachinery/pkg/runtime/schema" - kappsv1 "k8s.io/api/apps/v1" - "k8s.io/apimachinery/pkg/util/intstr" - - "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" - kcorev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/intstr" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" ) const ( @@ -26,7 +23,7 @@ const ( CRName = "eventing" ManagerContainerName = "manager" PublisherContainerName = "eventing-publisher-proxy" - WebhookServerCertSecretName = "eventing-manager-webhook-server-cert" //nolint:gosec // This is used for test purposes only. + WebhookServerCertSecretName = "eventing-manager-webhook-server-cert" WebhookServerCertJobName = "eventing-manager-cert-handler" EventMeshSecretNamespace = "kyma-system" EventMeshSecretName = "eventing-backend" diff --git a/hack/e2e/common/k8s.go b/hack/e2e/common/k8s.go index d9ba862c..3265de2e 100644 --- a/hack/e2e/common/k8s.go +++ b/hack/e2e/common/k8s.go @@ -4,24 +4,21 @@ import ( "os" "path/filepath" + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" "k8s.io/client-go/dynamic" - - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - - operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" ) func GetK8sClients() (*kubernetes.Clientset, client.Client, *dynamic.DynamicClient, error) { - kubeConfigPath := "" + var kubeConfigPath string if _, ok := os.LookupEnv("KUBECONFIG"); ok { kubeConfigPath = os.Getenv("KUBECONFIG") } else { diff --git a/hack/e2e/common/testenvironment/test_environment.go b/hack/e2e/common/testenvironment/test_environment.go index 89d1f82c..3c92c831 100644 --- a/hack/e2e/common/testenvironment/test_environment.go +++ b/hack/e2e/common/testenvironment/test_environment.go @@ -8,27 +8,23 @@ import ( "strings" "time" - istiopkgsecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/dynamic" - cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" - - operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - "go.uber.org/zap" + istiopkgsecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1" kappsv1 "k8s.io/api/apps/v1" kcorev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" ktypes "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - + operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/hack/e2e/common" "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" "github.com/kyma-project/eventing-manager/hack/e2e/common/fixtures" @@ -68,7 +64,6 @@ func NewTestEnvironment() *TestEnvironment { if err != nil { logger.Error(err.Error()) panic(err) - } logger.Info(fmt.Sprintf("##### NOTE: Tests will run w.r.t. backend: %s", testConfigs.BackendType)) diff --git a/hack/e2e/env/env.go b/hack/e2e/env/env.go index 5aa2005d..677e4b79 100644 --- a/hack/e2e/env/env.go +++ b/hack/e2e/env/env.go @@ -10,16 +10,16 @@ import ( // E2EConfig represents the environment config for the end-to-end tests for eventing-manager. type E2EConfig struct { - BackendType string `envconfig:"BACKEND_TYPE" default:"NATS"` // NATS or EventMesh - ManagerImage string `envconfig:"MANAGER_IMAGE" default:""` - EventTypePrefix string `envconfig:"EVENT_TYPE_PREFIX" default:"sap.kyma.custom"` - EventMeshNamespace string `envconfig:"EVENTMESH_NAMESPACE" default:"/default/sap.kyma/tunas-develop"` - SubscriptionSinkImage string `envconfig:"SUBSCRIPTION_SINK_IMAGE" default:"ghcr.io/kyma-project/eventing-manager/e2e-tests-sink:sha-8e81aae"` - SubscriptionSinkName string `envconfig:"SUBSCRIPTION_SINK_Name" default:"test-sink"` - SubscriptionSinkURL string `envconfig:"SUBSCRIPTION_SINK_URL" default:""` - TestNamespace string `envconfig:"TEST_NAMESPACE" default:"eventing-tests"` - PublisherURL string `envconfig:"PUBLISHER_URL" default:"http://localhost:38081"` - SinkPortForwardedURL string `envconfig:"SINK_PORT_FORWARDED_URL" default:"http://localhost:38071"` + BackendType string `default:"NATS" envconfig:"BACKEND_TYPE"` // NATS or EventMesh + ManagerImage string `default:"" envconfig:"MANAGER_IMAGE"` + EventTypePrefix string `default:"sap.kyma.custom" envconfig:"EVENT_TYPE_PREFIX"` + EventMeshNamespace string `default:"/default/sap.kyma/tunas-develop" envconfig:"EVENTMESH_NAMESPACE"` + SubscriptionSinkImage string `default:"ghcr.io/kyma-project/eventing-manager/e2e-tests-sink:sha-8e81aae" envconfig:"SUBSCRIPTION_SINK_IMAGE"` + SubscriptionSinkName string `default:"test-sink" envconfig:"SUBSCRIPTION_SINK_Name"` + SubscriptionSinkURL string `default:"" envconfig:"SUBSCRIPTION_SINK_URL"` + TestNamespace string `default:"eventing-tests" envconfig:"TEST_NAMESPACE"` + PublisherURL string `default:"http://localhost:38081" envconfig:"PUBLISHER_URL"` + SinkPortForwardedURL string `default:"http://localhost:38071" envconfig:"SINK_PORT_FORWARDED_URL"` } func (cfg E2EConfig) IsNATSBackend() bool { diff --git a/internal/controller/eventing/subscription/eventmesh/reconciler.go b/internal/controller/eventing/subscription/eventmesh/reconciler.go index 2105b3b3..b513bb7b 100644 --- a/internal/controller/eventing/subscription/eventmesh/reconciler.go +++ b/internal/controller/eventing/subscription/eventmesh/reconciler.go @@ -8,41 +8,36 @@ import ( "reflect" "time" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/pkg/errors" + "go.uber.org/zap" + "golang.org/x/xerrors" kcorev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" klabels "k8s.io/apimachinery/pkg/labels" ktypes "k8s.io/apimachinery/pkg/types" - - controllererrors "github.com/kyma-project/eventing-manager/internal/controller/errors" - "github.com/kyma-project/eventing-manager/internal/controller/events" - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - "github.com/kyma-project/eventing-manager/pkg/backend/metrics" - "github.com/kyma-project/eventing-manager/pkg/constants" - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" - "github.com/kyma-project/eventing-manager/pkg/object" - "github.com/kyma-project/eventing-manager/pkg/utils" - - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - "golang.org/x/xerrors" + "k8s.io/client-go/tools/record" + kctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/source" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + controllererrors "github.com/kyma-project/eventing-manager/internal/controller/errors" + "github.com/kyma-project/eventing-manager/internal/controller/events" + "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" - - "go.uber.org/zap" - - "k8s.io/client-go/tools/record" - kctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - + "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/backend/sink" backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" + "github.com/kyma-project/eventing-manager/pkg/constants" + "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" + "github.com/kyma-project/eventing-manager/pkg/object" + "github.com/kyma-project/eventing-manager/pkg/utils" ) type syncConditionWebhookCallStatusFunc func(subscription *eventingv1alpha2.Subscription) @@ -78,7 +73,8 @@ const ( func NewReconciler(ctx context.Context, client client.Client, logger *logger.Logger, recorder record.EventRecorder, cfg env.Config, cleaner cleaner.Cleaner, eventMeshBackend eventmesh.Backend, credential *eventmesh.OAuth2ClientCredentials, mapper backendutils.NameMapper, validator sink.Validator, - collector *metrics.Collector, domain string) *Reconciler { + collector *metrics.Collector, domain string, +) *Reconciler { if err := eventMeshBackend.Initialize(cfg); err != nil { logger.WithContext().Errorw("Failed to start reconciler", "name", reconcilerName, "error", err) @@ -257,7 +253,8 @@ func (r *Reconciler) syncFinalizer(subscription *eventingv1alpha2.Subscription, } func (r *Reconciler) handleDeleteSubscription(ctx context.Context, subscription *eventingv1alpha2.Subscription, - logger *zap.SugaredLogger) (kctrl.Result, error) { + logger *zap.SugaredLogger, +) (kctrl.Result, error) { // delete EventMesh subscriptions logger.Debug("Deleting subscription on EventMesh") if err := r.Backend.DeleteSubscription(subscription); err != nil { @@ -360,7 +357,8 @@ func syncConditionWebhookCallStatus(subscription *eventingv1alpha2.Subscription) // syncAPIRule validate the given subscription sink URL and sync its APIRule. func (r *Reconciler) syncAPIRule(ctx context.Context, subscription *eventingv1alpha2.Subscription, - logger *zap.SugaredLogger) (*apigatewayv1beta1.APIRule, error) { + logger *zap.SugaredLogger, +) (*apigatewayv1beta1.APIRule, error) { if err := r.sinkValidator.Validate(subscription); err != nil { return nil, err } @@ -398,7 +396,8 @@ func (r *Reconciler) syncAPIRule(ctx context.Context, subscription *eventingv1al // createOrUpdateAPIRule create new or update existing APIRule for the given subscription. func (r *Reconciler) createOrUpdateAPIRule(ctx context.Context, subscription *eventingv1alpha2.Subscription, - sink url.URL, logger *zap.SugaredLogger) (*apigatewayv1beta1.APIRule, error) { + sink url.URL, logger *zap.SugaredLogger, +) (*apigatewayv1beta1.APIRule, error) { svcNs, svcName, err := getSvcNsAndName(sink.Host) if err != nil { return nil, xerrors.Errorf("failed to parse svc name and ns in create or update APIRule: %v", err) @@ -468,7 +467,8 @@ func (r *Reconciler) createOrUpdateAPIRule(ctx context.Context, subscription *ev // if the OwnerReferences list is empty, then the APIRule will be deleted // else if the OwnerReferences list length was decreased, then the APIRule will be updated. func (r *Reconciler) handlePreviousAPIRule(ctx context.Context, subscription *eventingv1alpha2.Subscription, - reusableAPIRule *apigatewayv1beta1.APIRule) error { + reusableAPIRule *apigatewayv1beta1.APIRule, +) error { // subscription does not have a previous APIRule if len(subscription.Status.Backend.APIRuleName) == 0 { return nil @@ -696,7 +696,8 @@ func getRequiredConditions(subscriptionConditions, expectedConditions []eventing // replaceStatusCondition replaces the given condition on the subscription. Also it sets the readiness in the status. // So make sure you always use this method then changing a condition. func replaceStatusCondition(subscription *eventingv1alpha2.Subscription, - condition eventingv1alpha2.Condition) bool { + condition eventingv1alpha2.Condition, +) bool { // the subscription is ready if all conditions are fulfilled isReady := true diff --git a/internal/controller/eventing/subscription/eventmesh/reconciler_internal_integration_test.go b/internal/controller/eventing/subscription/eventmesh/reconciler_internal_integration_test.go index 806b7748..3d431dab 100644 --- a/internal/controller/eventing/subscription/eventmesh/reconciler_internal_integration_test.go +++ b/internal/controller/eventing/subscription/eventmesh/reconciler_internal_integration_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/pkg/errors" "github.com/stretchr/testify/assert" @@ -80,7 +80,7 @@ func TestReconciler_Reconcile(t *testing.T) { happyValidator := sink.ValidatorFunc(func(s *eventingv1alpha2.Subscription) error { return nil }) unhappyValidator := sink.ValidatorFunc(func(s *eventingv1alpha2.Subscription) error { return validatorErr }) - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenReconcilerSetup func() *Reconciler @@ -263,7 +263,7 @@ func TestReconciler_APIRuleConfig(t *testing.T) { col := metrics.NewCollector() - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenReconcilerSetup func() (*Reconciler, client.Client) @@ -392,7 +392,7 @@ func TestReconciler_APIRuleConfig_Upgrade(t *testing.T) { validator := sink.ValidatorFunc(func(s *eventingv1alpha2.Subscription) error { return nil }) col := metrics.NewCollector() - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenReconcilerSetup func() (*Reconciler, client.Client) @@ -584,7 +584,7 @@ func TestReconciler_PreserveBackendHashes(t *testing.T) { eventMeshLocalHash = int64(883494500014499) ) - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenReconcilerSetup func(*eventingv1alpha2.Subscription) (*Reconciler, client.Client) @@ -682,7 +682,7 @@ func TestReconciler_PreserveBackendHashes(t *testing.T) { } func Test_replaceStatusCondition(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string giveSubscription *eventingv1alpha2.Subscription giveCondition eventingv1alpha2.Condition @@ -820,7 +820,7 @@ func Test_getRequiredConditions(t *testing.T) { func Test_syncConditionSubscribed(t *testing.T) { currentTime := kmetav1.Now() errorMessage := "error message" - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenError error @@ -917,7 +917,7 @@ func Test_syncConditionSubscribed(t *testing.T) { func Test_syncConditionSubscriptionActive(t *testing.T) { currentTime := kmetav1.Now() - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenIsSubscribed bool @@ -1020,7 +1020,7 @@ func Test_syncConditionSubscriptionActive(t *testing.T) { func Test_syncConditionWebhookCallStatus(t *testing.T) { currentTime := kmetav1.Now() - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenIsSubscribed bool @@ -1216,8 +1216,7 @@ func Test_checkStatusActive(t *testing.T) { wantError: nil, }, { - name: `should return not active if the EventMeshSubscriptionStatus is inactive and the - the the FailedActivation time is set`, + name: `should return not active if the EventMeshSubscriptionStatus is inactive and the FailedActivation time is set`, subscription: func() *eventingv1alpha2.Subscription { sub := eventingtesting.NewSubscription("some-name", "some-namespace") sub.Status.InitializeConditions() @@ -1261,7 +1260,7 @@ func Test_checkStatusActive(t *testing.T) { } func Test_checkLastFailedDelivery(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription wantResult bool diff --git a/internal/controller/eventing/subscription/eventmesh/test/assertions.go b/internal/controller/eventing/subscription/eventmesh/test/assertions.go index e2d9ecbd..e633c10b 100644 --- a/internal/controller/eventing/subscription/eventmesh/test/assertions.go +++ b/internal/controller/eventing/subscription/eventmesh/test/assertions.go @@ -4,18 +4,18 @@ import ( "context" "log" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/onsi/gomega" kcorev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) // getSubscriptionAssert fetches a subscription using the lookupKey and allows making assertions on it. func getSubscriptionAssert(ctx context.Context, g *gomega.GomegaWithT, - subscription *eventingv1alpha2.Subscription) gomega.AsyncAssertion { + subscription *eventingv1alpha2.Subscription, +) gomega.AsyncAssertion { return g.Eventually(func() *eventingv1alpha2.Subscription { lookupKey := types.NamespacedName{ Namespace: subscription.Namespace, @@ -40,7 +40,8 @@ func getAPIRuleForASvcAssert(ctx context.Context, g *gomega.GomegaWithT, svc *kc // getAPIRuleAssert fetches an apiRule and allows making assertions on it. func getAPIRuleAssert(ctx context.Context, g *gomega.GomegaWithT, - apiRule *apigatewayv1beta1.APIRule) gomega.AsyncAssertion { + apiRule *apigatewayv1beta1.APIRule, +) gomega.AsyncAssertion { return g.Eventually(func() apigatewayv1beta1.APIRule { fetchedAPIRule, err := getAPIRule(ctx, apiRule) if err != nil { diff --git a/internal/controller/eventing/subscription/eventmesh/test/reconciler_integration_test.go b/internal/controller/eventing/subscription/eventmesh/test/reconciler_integration_test.go index e0c94574..d74691e3 100644 --- a/internal/controller/eventing/subscription/eventmesh/test/reconciler_integration_test.go +++ b/internal/controller/eventing/subscription/eventmesh/test/reconciler_integration_test.go @@ -9,16 +9,14 @@ import ( "testing" "time" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/onsi/gomega" gomegatypes "github.com/onsi/gomega/types" "github.com/stretchr/testify/assert" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - emstypes "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" "github.com/kyma-project/eventing-manager/pkg/object" eventingtesting "github.com/kyma-project/eventing-manager/testing" @@ -54,7 +52,7 @@ func TestMain(m *testing.M) { func Test_ValidationWebhook(t *testing.T) { t.Parallel() - var testCases = []struct { + testCases := []struct { name string givenSubscriptionFunc func(namespace string) *eventingv1alpha2.Subscription wantError error @@ -134,7 +132,7 @@ func Test_ValidationWebhook(t *testing.T) { } func Test_CreateSubscription(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenSubscriptionFunc func(namespace string) *eventingv1alpha2.Subscription wantSubscriptionMatchers gomegatypes.GomegaMatcher @@ -361,7 +359,7 @@ func Test_CreateSubscription(t *testing.T) { func Test_UpdateSubscription(t *testing.T) { t.Parallel() - var testCases = []struct { + testCases := []struct { name string givenSubscriptionFunc func(namespace string) *eventingv1alpha2.Subscription givenUpdateSubscriptionFunc func(namespace string) *eventingv1alpha2.Subscription @@ -577,7 +575,8 @@ func Test_DeleteSubscription(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace}} + Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule) @@ -643,7 +642,7 @@ func Test_FixingSinkAndApiRule(t *testing.T) { ) // test cases - var testCases = []struct { + testCases := []struct { name string givenSinkFormat string }{ @@ -762,7 +761,8 @@ func Test_SinkChangeAndAPIRule(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace}} + Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule) @@ -787,7 +787,8 @@ func Test_SinkChangeAndAPIRule(t *testing.T) { // fetch the new APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule = &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: updatedSubscription.Status.Backend.APIRuleName, Namespace: updatedSubscription.Namespace}} + Name: updatedSubscription.Status.Backend.APIRuleName, Namespace: updatedSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule) @@ -830,7 +831,8 @@ func Test_APIRuleReUseAfterUpdatingSink(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule1 := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace}} + Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule1).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule1) @@ -860,7 +862,8 @@ func Test_APIRuleReUseAfterUpdatingSink(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule2 := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription2.Status.Backend.APIRuleName, Namespace: createdSubscription2.Namespace}} + Name: createdSubscription2.Status.Backend.APIRuleName, Namespace: createdSubscription2.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule2).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule2) @@ -955,7 +958,8 @@ func Test_APIRuleExistsAfterDeletingSub(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule1 := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace}} + Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule1).Should(gomega.And( eventingtesting.HaveNotEmptyAPIRule(), eventingtesting.HaveAPIRuleOwnersRefs(createdSubscription1.UID, createdSubscription2.UID), @@ -981,7 +985,8 @@ func Test_APIRuleExistsAfterDeletingSub(t *testing.T) { // fetch the APIRule again and check apiRule1 = &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace}} + Name: createdSubscription1.Status.Backend.APIRuleName, Namespace: createdSubscription1.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule1).Should(gomega.And( eventingtesting.HaveNotEmptyAPIRule(), eventingtesting.HaveNotEmptyHost(), @@ -1040,7 +1045,8 @@ func Test_APIRuleRecreateAfterManualDelete(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace}} + Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule) @@ -1052,7 +1058,8 @@ func Test_APIRuleRecreateAfterManualDelete(t *testing.T) { // phase 3: Check if APIRule is re-created by the reconciler getSubscriptionAssert(ctx, g, createdSubscription).Should(eventingtesting.HaveNoneEmptyAPIRuleName()) apiRule = &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace}} + Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) } @@ -1090,7 +1097,8 @@ func Test_EventMeshSubRecreateAfterManualDelete(t *testing.T) { // fetch the APIRule and update the status of the APIRule to ready (mocking APIGateway controller) // and wait until the created Subscription becomes ready apiRule := &apigatewayv1beta1.APIRule{ObjectMeta: kmetav1.ObjectMeta{ - Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace}} + Name: createdSubscription.Status.Backend.APIRuleName, Namespace: createdSubscription.Namespace, + }} getAPIRuleAssert(ctx, g, apiRule).Should(eventingtesting.HaveNotEmptyAPIRule()) ensureAPIRuleStatusUpdatedWithStatusReady(ctx, t, apiRule) @@ -1129,14 +1137,14 @@ func TestWithEventMeshServerErrors(t *testing.T) { ) } - var testCases = []struct { + testCases := []struct { name string givenCreateResponseFunc func(w http.ResponseWriter, _ emstypes.Subscription) wantSubscriptionMatchers gomegatypes.GomegaMatcher wantEventMeshSubMatchers gomegatypes.GomegaMatcher }{ { - name: "should not be ready when when EventMesh server is not able to create new EventMesh subscriptions", + name: "should not be ready when EventMesh server is not able to create new EventMesh subscriptions", givenCreateResponseFunc: func(w http.ResponseWriter, _ emstypes.Subscription) { // ups ... server returns 500 w.WriteHeader(http.StatusInternalServerError) diff --git a/internal/controller/eventing/subscription/eventmesh/test/utils.go b/internal/controller/eventing/subscription/eventmesh/test/utils.go index ce38e07e..ef1e20c7 100644 --- a/internal/controller/eventing/subscription/eventmesh/test/utils.go +++ b/internal/controller/eventing/subscription/eventmesh/test/utils.go @@ -13,11 +13,9 @@ import ( "testing" "time" - subscriptioncontrollereventmesh "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" - "github.com/avast/retry-go/v3" "github.com/go-logr/zapr" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" kcorev1 "k8s.io/api/core/v1" @@ -38,7 +36,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - + subscriptioncontrollereventmesh "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" @@ -397,7 +395,7 @@ func filterAPIRulesForASvc(apiRules *apigatewayv1beta1.APIRuleList, svc *kcorev1 // countEventMeshRequests returns how many requests for a given subscription are sent for each HTTP method // -//nolint:gocognit + func countEventMeshRequests(subscriptionName, eventType string) (int, int, int) { countGet, countPost, countDelete := 0, 0, 0 emTestEnsemble.eventMeshMock.Requests.ReadEach( diff --git a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/assertions.go b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/assertions.go index defb19c2..0efc7095 100644 --- a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/assertions.go +++ b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/assertions.go @@ -4,17 +4,17 @@ import ( "context" "log" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/types" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) // getSubscriptionAssert fetches a subscription using the lookupKey and allows making assertions on it. func getSubscriptionAssert(ctx context.Context, g *gomega.GomegaWithT, - subscription *eventingv1alpha2.Subscription) gomega.AsyncAssertion { + subscription *eventingv1alpha2.Subscription, +) gomega.AsyncAssertion { return g.Eventually(func() *eventingv1alpha2.Subscription { lookupKey := types.NamespacedName{ Namespace: subscription.Namespace, @@ -30,7 +30,8 @@ func getSubscriptionAssert(ctx context.Context, g *gomega.GomegaWithT, // getAPIRuleAssert fetches an apiRule and allows making assertions on it. func getAPIRuleAssert(ctx context.Context, g *gomega.GomegaWithT, - apiRule *apigatewayv1beta1.APIRule) gomega.AsyncAssertion { + apiRule *apigatewayv1beta1.APIRule, +) gomega.AsyncAssertion { return g.Eventually(func() apigatewayv1beta1.APIRule { fetchedAPIRule, err := getAPIRule(ctx, apiRule) if err != nil { diff --git a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/reconciler_integration_test.go b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/reconciler_integration_test.go index 51d80091..a5f4c5a5 100644 --- a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/reconciler_integration_test.go +++ b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/reconciler_integration_test.go @@ -6,12 +6,11 @@ import ( "net/http" "testing" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/onsi/gomega" "github.com/stretchr/testify/require" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) @@ -76,7 +75,7 @@ func Test_UpdateWebhookAuthConfig(t *testing.T) { g.Expect(eventMeshSubscription).ShouldNot(gomega.BeNil()) // counts EventMesh mock requests before changing the credentials - var uri = getEventMeshSubKeyForMock(kymaSubscription.Name, kymaSubscription.Namespace) + uri := getEventMeshSubKeyForMock(kymaSubscription.Name, kymaSubscription.Namespace) deleteRequestsBefore := emTestEnsemble.eventMeshMock.CountRequests(http.MethodDelete, uri) patchRequestsBefore := emTestEnsemble.eventMeshMock.CountRequests(http.MethodPatch, uri) diff --git a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/utils.go b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/utils.go index 5b03bc24..d1ade3b4 100644 --- a/internal/controller/eventing/subscription/eventmesh/testwebhookauth/utils.go +++ b/internal/controller/eventing/subscription/eventmesh/testwebhookauth/utils.go @@ -11,10 +11,10 @@ import ( "testing" "time" - subscriptioncontrollereventmesh "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" - "github.com/avast/retry-go/v3" "github.com/go-logr/zapr" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" kcorev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" @@ -31,10 +31,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + subscriptioncontrollereventmesh "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" diff --git a/internal/controller/eventing/subscription/eventmesh/utils.go b/internal/controller/eventing/subscription/eventmesh/utils.go index 4cd313d7..286ac1b1 100644 --- a/internal/controller/eventing/subscription/eventmesh/utils.go +++ b/internal/controller/eventing/subscription/eventmesh/utils.go @@ -5,7 +5,7 @@ import ( "net/url" "strings" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/pkg/errors" "go.uber.org/zap" "golang.org/x/xerrors" diff --git a/internal/controller/eventing/subscription/eventmesh/utils_test.go b/internal/controller/eventing/subscription/eventmesh/utils_test.go index 914c0058..424d2a7b 100644 --- a/internal/controller/eventing/subscription/eventmesh/utils_test.go +++ b/internal/controller/eventing/subscription/eventmesh/utils_test.go @@ -4,20 +4,18 @@ import ( "testing" "time" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/logger" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) func Test_isInDeletion(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenSubscription func() *eventingv1alpha2.Subscription wantResult bool @@ -67,7 +65,7 @@ func Test_isInDeletion(t *testing.T) { } func Test_isFinalizerSet(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription wantResult bool @@ -101,7 +99,7 @@ func Test_addFinalizer(t *testing.T) { namedLogger := defaultLogger.WithContext().Named(reconcilerName) - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription wantFinalizersLen int @@ -135,7 +133,7 @@ func Test_addFinalizer(t *testing.T) { } func Test_getSvcNsAndName(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenURL string wantName string @@ -170,7 +168,7 @@ func Test_getSvcNsAndName(t *testing.T) { } func Test_computeAPIRuleReadyStatus(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string givenAPIRule *apigatewayv1beta1.APIRule wantResult bool @@ -241,7 +239,7 @@ func Test_computeAPIRuleReadyStatus(t *testing.T) { func Test_setSubscriptionStatusExternalSink(t *testing.T) { host1 := "kyma-project.io" - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenAPIRule *apigatewayv1beta1.APIRule diff --git a/internal/controller/eventing/subscription/jetstream/matchers_test.go b/internal/controller/eventing/subscription/jetstream/matchers_test.go index 1448ddd4..0017b63b 100644 --- a/internal/controller/eventing/subscription/jetstream/matchers_test.go +++ b/internal/controller/eventing/subscription/jetstream/matchers_test.go @@ -3,12 +3,12 @@ package jetstream_test import ( "fmt" - "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/onsi/gomega" + gomegatypes "github.com/onsi/gomega/types" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" - "github.com/onsi/gomega" - gomegatypes "github.com/onsi/gomega/types" + "github.com/kyma-project/eventing-manager/pkg/env" ) func BeValidSubscription() gomegatypes.GomegaMatcher { @@ -28,7 +28,8 @@ func BeNatsSubWithMaxPending(expectedMaxAckPending int) gomegatypes.GomegaMatche } func BeJetStreamSubscriptionWithSubject(source, subject string, - typeMatching eventingv1alpha2.TypeMatching, natsConfig env.NATSConfig) gomegatypes.GomegaMatcher { + typeMatching eventingv1alpha2.TypeMatching, natsConfig env.NATSConfig, +) gomegatypes.GomegaMatcher { return gomega.WithTransform(func(subscriber jetstream.Subscriber) (bool, error) { info, err := subscriber.ConsumerInfo() if err != nil { diff --git a/internal/controller/eventing/subscription/jetstream/reconciler.go b/internal/controller/eventing/subscription/jetstream/reconciler.go index ac148c33..8bbc07f1 100644 --- a/internal/controller/eventing/subscription/jetstream/reconciler.go +++ b/internal/controller/eventing/subscription/jetstream/reconciler.go @@ -5,20 +5,10 @@ import ( "reflect" "time" - "github.com/kyma-project/eventing-manager/pkg/backend/metrics" - - ktypes "k8s.io/apimachinery/pkg/types" - - "github.com/kyma-project/eventing-manager/internal/controller/events" - "github.com/nats-io/nats.go" - - "github.com/kyma-project/eventing-manager/pkg/errors" - "github.com/kyma-project/eventing-manager/pkg/object" - pkgerrors "github.com/pkg/errors" - "go.uber.org/zap" + ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" kctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -27,14 +17,17 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/source" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/internal/controller/events" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" + "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" + "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/backend/sink" backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" - "github.com/kyma-project/eventing-manager/pkg/utils" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" + "github.com/kyma-project/eventing-manager/pkg/errors" "github.com/kyma-project/eventing-manager/pkg/logger" + "github.com/kyma-project/eventing-manager/pkg/object" + "github.com/kyma-project/eventing-manager/pkg/utils" ) const ( @@ -57,7 +50,8 @@ type Reconciler struct { func NewReconciler(ctx context.Context, client client.Client, jsBackend jetstream.Backend, logger *logger.Logger, recorder record.EventRecorder, cleaner cleaner.Cleaner, - defaultSinkValidator sink.Validator, collector *metrics.Collector) *Reconciler { + defaultSinkValidator sink.Validator, collector *metrics.Collector, +) *Reconciler { reconciler := &Reconciler{ Client: client, ctx: ctx, @@ -239,8 +233,8 @@ func (r *Reconciler) enqueueReconciliationForSubscriptions(subs []eventingv1alph // handleSubscriptionDeletion deletes the JetStream subscription and removes its finalizer if it is set. func (r *Reconciler) handleSubscriptionDeletion(ctx context.Context, - subscription *eventingv1alpha2.Subscription, log *zap.SugaredLogger) (kctrl.Result, error) { - + subscription *eventingv1alpha2.Subscription, log *zap.SugaredLogger, +) (kctrl.Result, error) { // delete the JetStream subscription/consumer if !utils.ContainsString(subscription.ObjectMeta.Finalizers, eventingv1alpha2.Finalizer) { return kctrl.Result{}, nil @@ -281,7 +275,8 @@ func (r *Reconciler) handleSubscriptionDeletion(ctx context.Context, // syncSubscriptionStatus syncs Subscription status and updates the k8s subscription. func (r *Reconciler) syncSubscriptionStatus(ctx context.Context, - desiredSubscription *eventingv1alpha2.Subscription, err error, log *zap.SugaredLogger) error { + desiredSubscription *eventingv1alpha2.Subscription, err error, log *zap.SugaredLogger, +) error { // set ready state desiredSubscription.Status.Ready = err == nil @@ -294,7 +289,8 @@ func (r *Reconciler) syncSubscriptionStatus(ctx context.Context, // updateSubscriptionStatus updates the subscription's status changes to k8s. func (r *Reconciler) updateSubscriptionStatus(ctx context.Context, - sub *eventingv1alpha2.Subscription, logger *zap.SugaredLogger) error { + sub *eventingv1alpha2.Subscription, logger *zap.SugaredLogger, +) error { namespacedName := &ktypes.NamespacedName{ Name: sub.Name, Namespace: sub.Namespace, @@ -320,7 +316,8 @@ func (r *Reconciler) updateSubscriptionStatus(ctx context.Context, // updateStatus updates the status to k8s if modified. func (r *Reconciler) updateStatus(ctx context.Context, oldSubscription, - newSubscription *eventingv1alpha2.Subscription, logger *zap.SugaredLogger) error { + newSubscription *eventingv1alpha2.Subscription, logger *zap.SugaredLogger, +) error { // compare the status taking into consideration lastTransitionTime in conditions if object.IsSubscriptionStatusEqual(oldSubscription.Status, newSubscription.Status) { return nil diff --git a/internal/controller/eventing/subscription/jetstream/reconciler_integration_test.go b/internal/controller/eventing/subscription/jetstream/reconciler_integration_test.go index 3aaafd4a..03695bc8 100644 --- a/internal/controller/eventing/subscription/jetstream/reconciler_integration_test.go +++ b/internal/controller/eventing/subscription/jetstream/reconciler_integration_test.go @@ -12,9 +12,8 @@ import ( "github.com/stretchr/testify/require" kcorev1 "k8s.io/api/core/v1" - eventingtesting "github.com/kyma-project/eventing-manager/testing" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + eventingtesting "github.com/kyma-project/eventing-manager/testing" ) // TestMain pre-hook and post-hook to run before and after all tests. @@ -40,7 +39,7 @@ func TestMain(m *testing.M) { func Test_ValidationWebhook(t *testing.T) { t.Parallel() - var testCases = []struct { + testCases := []struct { name string givenSubscriptionOpts []eventingtesting.SubscriptionOpt wantError func(subName string) error @@ -205,7 +204,7 @@ func Test_Idempotency(t *testing.T) { // TestCreateSubscription tests if subscriptions get created properly by the reconciler. func Test_CreateSubscription(t *testing.T) { t.Parallel() - var testCases = []struct { + testCases := []struct { name string givenSubscriptionOpts []eventingtesting.SubscriptionOpt want Want @@ -267,7 +266,8 @@ func Test_CreateSubscription(t *testing.T) { )), }, K8sEvents: []kcorev1.Event{ - EventInvalidSink("Sink does not correspond to a valid cluster local svc")}, + EventInvalidSink("Sink does not correspond to a valid cluster local svc"), + }, }, }, { @@ -333,7 +333,7 @@ func Test_CreateSubscription(t *testing.T) { // Test_ChangeSubscription tests if existing subscriptions are reconciled properly after getting changed. func Test_ChangeSubscription(t *testing.T) { t.Parallel() - var testCases = []struct { + testCases := []struct { name string givenSubscriptionOpts []eventingtesting.SubscriptionOpt wantBefore Want diff --git a/internal/controller/eventing/subscription/jetstream/reconciler_internal_unit_test.go b/internal/controller/eventing/subscription/jetstream/reconciler_internal_unit_test.go index 85248265..9ca5e2ee 100644 --- a/internal/controller/eventing/subscription/jetstream/reconciler_internal_unit_test.go +++ b/internal/controller/eventing/subscription/jetstream/reconciler_internal_unit_test.go @@ -66,7 +66,7 @@ func Test_Reconcile(t *testing.T) { unhappyValidator := sink.ValidatorFunc(func(s *eventingv1alpha2.Subscription) error { return validatorErr }) collector := metrics.NewCollector() - var testCases = []struct { + testCases := []struct { name string givenSubscription *eventingv1alpha2.Subscription givenReconcilerSetup func() (*Reconciler, *backendjetstreammocks.Backend) @@ -283,7 +283,6 @@ func Test_handleSubscriptionDeletion(t *testing.T) { for _, tC := range testCases { testCase := tC t.Run(testCase.name, func(t *testing.T) { - // given sub := eventingtesting.NewSubscription(subscriptionName, namespaceName, eventingtesting.WithFinalizers(testCase.givenFinalizers), @@ -381,7 +380,6 @@ func Test_addFinalizer(t *testing.T) { } func Test_syncSubscriptionStatus(t *testing.T) { - jetStreamError := errors.New("JetStream is not ready") falseNatsSubActiveCondition := eventingv1alpha2.MakeCondition(eventingv1alpha2.ConditionSubscriptionActive, eventingv1alpha2.ConditionReasonNATSSubscriptionNotActive, @@ -793,7 +791,8 @@ func fetchTestSubscription(ctx context.Context, r *Reconciler) (eventingv1alpha2 } func ensureSubscriptionMatchesConditionsAndStatus(t *testing.T, - subscription eventingv1alpha2.Subscription, wantConditions []eventingv1alpha2.Condition, wantStatus bool) { + subscription eventingv1alpha2.Subscription, wantConditions []eventingv1alpha2.Condition, wantStatus bool, +) { require.Equal(t, len(wantConditions), len(subscription.Status.Conditions)) comparisonResult := eventingv1alpha2.ConditionsEquals(wantConditions, subscription.Status.Conditions) require.True(t, comparisonResult) diff --git a/internal/controller/eventing/subscription/jetstream/test_utils_test.go b/internal/controller/eventing/subscription/jetstream/test_utils_test.go index 5a3dda67..a7120e4e 100644 --- a/internal/controller/eventing/subscription/jetstream/test_utils_test.go +++ b/internal/controller/eventing/subscription/jetstream/test_utils_test.go @@ -10,12 +10,11 @@ import ( "testing" "time" - subscriptioncontrollerjetstream "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/jetstream" - - "github.com/kyma-project/eventing-manager/pkg/backend/sink" - "github.com/avast/retry-go/v3" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" natsioserver "github.com/nats-io/nats-server/v2/server" + "github.com/onsi/gomega" + gomegatypes "github.com/onsi/gomega/types" "github.com/pkg/errors" "github.com/stretchr/testify/require" kcorev1 "k8s.io/api/core/v1" @@ -23,26 +22,23 @@ import ( kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" + kctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" - "github.com/kyma-project/eventing-manager/internal/controller/events" - - kymalogger "github.com/kyma-project/kyma/common/logging/logger" - "github.com/onsi/gomega" - gomegatypes "github.com/onsi/gomega/types" - "k8s.io/client-go/kubernetes/scheme" - kctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/envtest" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + subscriptioncontrollerjetstream "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/jetstream" + "github.com/kyma-project/eventing-manager/internal/controller/events" backendcleaner "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" + "github.com/kyma-project/eventing-manager/pkg/backend/sink" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" eventingtesting "github.com/kyma-project/eventing-manager/testing" @@ -258,7 +254,8 @@ func cleanupResources() error { } func testSubscriptionOnNATS(g *gomega.GomegaWithT, subscription *eventingv1alpha2.Subscription, - subject string, expectations ...gomegatypes.GomegaMatcher) { + subject string, expectations ...gomegatypes.GomegaMatcher, +) { description := "Failed to match nats subscriptions" getSubscriptionFromJetStream(g, subscription, jsTestEnsemble.jetStreamBackend.GetJetStreamSubject( @@ -280,7 +277,8 @@ func testSubscriptionDeletion(g *gomega.GomegaWithT, subscription *eventingv1alp // ensureNATSSubscriptionIsDeleted ensures that the NATS subscription is not found anymore. // This ensures the controller did delete it correctly then the Subscription was deleted. func ensureNATSSubscriptionIsDeleted(g *gomega.GomegaWithT, - subscription *eventingv1alpha2.Subscription, subject string) { + subscription *eventingv1alpha2.Subscription, subject string, +) { getSubscriptionFromJetStream(g, subscription, subject). ShouldNot(BeExistingSubscription(), "Failed to delete NATS subscription") } @@ -290,7 +288,8 @@ func ensureNATSSubscriptionIsDeleted(g *gomega.GomegaWithT, // Otherwise, the returned NATS subscription could have the wrong state. // For this reason Eventually is used here. func getSubscriptionFromJetStream(g *gomega.GomegaWithT, - subscription *eventingv1alpha2.Subscription, subject string) gomega.AsyncAssertion { + subscription *eventingv1alpha2.Subscription, subject string, +) gomega.AsyncAssertion { return g.Eventually(func() jetstream.Subscriber { subscriptions := jsTestEnsemble.jetStreamBackend.GetNATSSubscriptions() subscriptionSubject := jetstream.NewSubscriptionSubjectIdentifier(subscription, subject) @@ -308,7 +307,8 @@ func getSubscriptionFromJetStream(g *gomega.GomegaWithT, // To avoid a 409 conflict, the subscription CR data is read from the apiserver before a new update is performed. // This conflict can happen if another entity such as the eventing-controller changed the sub in the meantime. func EventuallyUpdateSubscriptionOnK8s(ctx context.Context, ens *Ensemble, - sub *eventingv1alpha2.Subscription, updateFunc func(*eventingv1alpha2.Subscription) error) error { + sub *eventingv1alpha2.Subscription, updateFunc func(*eventingv1alpha2.Subscription) error, +) error { return doRetry(func() error { // get a fresh version of the Subscription lookupKey := types.NamespacedName{ @@ -326,7 +326,8 @@ func EventuallyUpdateSubscriptionOnK8s(ctx context.Context, ens *Ensemble, } func NewSubscription(ens *Ensemble, - subscriptionOpts ...eventingtesting.SubscriptionOpt) *eventingv1alpha2.Subscription { + subscriptionOpts ...eventingtesting.SubscriptionOpt, +) *eventingv1alpha2.Subscription { subscriptionName := fmt.Sprintf(subscriptionNameFormat, ens.testID) ens.testID++ subscription := eventingtesting.NewSubscription(subscriptionName, ens.SubscriberSvc.Namespace, subscriptionOpts...) @@ -334,7 +335,8 @@ func NewSubscription(ens *Ensemble, } func CreateSubscription(t *testing.T, ens *Ensemble, - subscriptionOpts ...eventingtesting.SubscriptionOpt) *eventingv1alpha2.Subscription { + subscriptionOpts ...eventingtesting.SubscriptionOpt, +) *eventingv1alpha2.Subscription { subscription := NewSubscription(ens, subscriptionOpts...) EnsureNamespaceCreatedForSub(t, ens, subscription) require.NoError(t, ensureSubscriptionCreated(ens, subscription)) @@ -342,7 +344,8 @@ func CreateSubscription(t *testing.T, ens *Ensemble, } func CheckSubscriptionOnK8s(g *gomega.WithT, ens *Ensemble, subscription *eventingv1alpha2.Subscription, - expectations ...gomegatypes.GomegaMatcher) { + expectations ...gomegatypes.GomegaMatcher, +) { description := "Failed to match the eventing subscription" expectations = append(expectations, eventingtesting.HaveSubscriptionName(subscription.Name)) getSubscriptionOnK8S(g, ens, subscription).Should(gomega.And(expectations...), description) @@ -364,7 +367,8 @@ func ValidSinkURL(ens *Ensemble, additions ...string) string { // IsSubscriptionDeletedOnK8s checks a subscription is deleted and allows making assertions on it. func IsSubscriptionDeletedOnK8s(g *gomega.WithT, ens *Ensemble, - subscription *eventingv1alpha2.Subscription) gomega.AsyncAssertion { + subscription *eventingv1alpha2.Subscription, +) gomega.AsyncAssertion { return g.Eventually(func() bool { lookupKey := types.NamespacedName{ Namespace: subscription.Namespace, @@ -457,7 +461,7 @@ func createSubscriberSvcInK8s(ens *Ensemble) error { return err } return nil - }, "Failed to to create the namespace for the subscriber") + }, "Failed to create the namespace for the subscriber") if err != nil { return err } @@ -510,7 +514,8 @@ func fixtureNamespace(name string) *kcorev1.Namespace { // getSubscriptionOnK8S fetches a subscription using the lookupKey and allows making assertions on it. func getSubscriptionOnK8S(g *gomega.WithT, ens *Ensemble, - subscription *eventingv1alpha2.Subscription) gomega.AsyncAssertion { + subscription *eventingv1alpha2.Subscription, +) gomega.AsyncAssertion { return g.Eventually(func() *eventingv1alpha2.Subscription { lookupKey := types.NamespacedName{ Namespace: subscription.Namespace, diff --git a/internal/controller/operator/eventing/controller.go b/internal/controller/operator/eventing/controller.go index 42b830e3..e9efdc71 100644 --- a/internal/controller/operator/eventing/controller.go +++ b/internal/controller/operator/eventing/controller.go @@ -204,7 +204,8 @@ func (r *Reconciler) Reconcile(ctx context.Context, req kctrl.Request) (kctrl.Re // handleEventingCRAllowedCheck checks if Eventing CR is allowed to be created or not. // returns true if the Eventing CR is allowed. func (r *Reconciler) handleEventingCRAllowedCheck(ctx context.Context, eventing *operatorv1alpha1.Eventing, - log *zap.SugaredLogger) (bool, error) { + log *zap.SugaredLogger, +) (bool, error) { // if the name and namespace matches with allowed NATS CR then allow the CR to be reconciled. if eventing.Name == r.allowedEventingCR.Name && eventing.Namespace == r.allowedEventingCR.Namespace { return true, nil @@ -370,7 +371,8 @@ func (r *Reconciler) loggerWithEventing(eventing *operatorv1alpha1.Eventing) *za } func (r *Reconciler) handleEventingDeletion(ctx context.Context, eventing *operatorv1alpha1.Eventing, - log *zap.SugaredLogger) (kctrl.Result, error) { + log *zap.SugaredLogger, +) (kctrl.Result, error) { // skip reconciliation for deletion if the finalizer is not set. if !r.containsFinalizer(eventing) { log.Debug("skipped reconciliation for deletion as finalizer is not set.") @@ -428,7 +430,8 @@ func (r *Reconciler) deleteClusterScopedResources(ctx context.Context, eventingC } func (r *Reconciler) handleEventingReconcile(ctx context.Context, - eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger) (kctrl.Result, error) { + eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger, +) (kctrl.Result, error) { log.Info("handling Eventing reconciliation...") // make sure the finalizer exists. @@ -476,7 +479,8 @@ func (r *Reconciler) handleEventingReconcile(ctx context.Context, } func (r *Reconciler) handleBackendSwitching( - eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger, +) error { // check if the backend was changed. if !eventing.IsSpecBackendTypeChanged() { return nil @@ -557,7 +561,8 @@ func (r *Reconciler) checkNATSAvailability(ctx context.Context, eventing *operat func (r *Reconciler) handlePublisherProxy( ctx context.Context, eventing *operatorv1alpha1.Eventing, - backendType operatorv1alpha1.BackendType) (*kappsv1.Deployment, error) { + backendType operatorv1alpha1.BackendType, +) (*kappsv1.Deployment, error) { // get nats config with NATS server url var natsConfig *env.NATSConfig if backendType == operatorv1alpha1.NatsBackendType { diff --git a/internal/controller/operator/eventing/controller_test.go b/internal/controller/operator/eventing/controller_test.go index 7770c43c..620b1aa1 100644 --- a/internal/controller/operator/eventing/controller_test.go +++ b/internal/controller/operator/eventing/controller_test.go @@ -5,17 +5,15 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/mock" - - "github.com/kyma-project/eventing-manager/pkg/watcher" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/event" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" + "github.com/kyma-project/eventing-manager/pkg/watcher" watchermocks "github.com/kyma-project/eventing-manager/pkg/watcher/mocks" testutils "github.com/kyma-project/eventing-manager/test/utils" ) diff --git a/internal/controller/operator/eventing/eventmesh.go b/internal/controller/operator/eventing/eventmesh.go index 07937daf..cfc37cbc 100644 --- a/internal/controller/operator/eventing/eventmesh.go +++ b/internal/controller/operator/eventing/eventmesh.go @@ -140,7 +140,8 @@ func (r *Reconciler) getEventMeshSubManagerParams() submgrmanager.Params { } func (r *Reconciler) startEventMeshSubManager(defaultSubsConfig env.DefaultSubscriptionConfig, - eventMeshSubMgrParams submgrmanager.Params) error { + eventMeshSubMgrParams submgrmanager.Params, +) error { if err := r.eventMeshSubManager.Start(defaultSubsConfig, eventMeshSubMgrParams); err != nil { return err } @@ -209,7 +210,6 @@ func (r *Reconciler) syncOauth2ClientIDAndSecret(ctx context.Context, eventing * errors.New(message), r.namedLogger()); updateErr != nil { return updateErr } - } if oauth2CredentialsNotFound { return err diff --git a/internal/controller/operator/eventing/eventmesh_test.go b/internal/controller/operator/eventing/eventmesh_test.go index b1eaf61a..efa1e4b7 100644 --- a/internal/controller/operator/eventing/eventmesh_test.go +++ b/internal/controller/operator/eventing/eventmesh_test.go @@ -5,12 +5,6 @@ import ( "errors" "testing" - "github.com/kyma-project/eventing-manager/pkg/eventing" - - "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - "github.com/kyma-project/eventing-manager/pkg/k8s" - k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -19,9 +13,13 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/internal/label" "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/kyma-project/eventing-manager/pkg/eventing" eventingmocks "github.com/kyma-project/eventing-manager/pkg/eventing/mocks" + "github.com/kyma-project/eventing-manager/pkg/k8s" + k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" "github.com/kyma-project/eventing-manager/pkg/logger" submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" submgrmocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/mocks" diff --git a/internal/controller/operator/eventing/integrationtests/controller/integration_test.go b/internal/controller/operator/eventing/integrationtests/controller/integration_test.go index c7438a01..422b9eb5 100644 --- a/internal/controller/operator/eventing/integrationtests/controller/integration_test.go +++ b/internal/controller/operator/eventing/integrationtests/controller/integration_test.go @@ -7,8 +7,8 @@ import ( "os" "testing" - eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" - + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/onsi/gomega" gomegatypes "github.com/onsi/gomega/types" "github.com/stretchr/testify/require" @@ -17,12 +17,9 @@ import ( kerrors "k8s.io/apimachinery/pkg/api/errors" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - natstestutils "github.com/kyma-project/nats-manager/testutils" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" "github.com/kyma-project/eventing-manager/pkg/eventing" "github.com/kyma-project/eventing-manager/pkg/k8s" "github.com/kyma-project/eventing-manager/test/matchers" @@ -340,7 +337,7 @@ func Test_ReconcileSameEventingCR(t *testing.T) { // Ensure reconciling the same Eventing CR multiple times does not update the EPP deployment. const runs = 3 - var resourceVersionBefore = eppDeployment.ObjectMeta.ResourceVersion + resourceVersionBefore := eppDeployment.ObjectMeta.ResourceVersion for r := 0; r < runs; r++ { //// // when diff --git a/internal/controller/operator/eventing/integrationtests/controller_switching/integration_test.go b/internal/controller/operator/eventing/integrationtests/controller_switching/integration_test.go index 47ed8492..93f9a9e5 100644 --- a/internal/controller/operator/eventing/integrationtests/controller_switching/integration_test.go +++ b/internal/controller/operator/eventing/integrationtests/controller_switching/integration_test.go @@ -5,8 +5,6 @@ import ( "os" "testing" - eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/onsi/gomega" @@ -15,6 +13,7 @@ import ( kappsv1 "k8s.io/api/apps/v1" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" "github.com/kyma-project/eventing-manager/pkg/eventing" "github.com/kyma-project/eventing-manager/test/matchers" "github.com/kyma-project/eventing-manager/test/utils" diff --git a/internal/controller/operator/eventing/integrationtests/controllersinglecr/integration_test.go b/internal/controller/operator/eventing/integrationtests/controllersinglecr/integration_test.go index e766c408..467c2310 100644 --- a/internal/controller/operator/eventing/integrationtests/controllersinglecr/integration_test.go +++ b/internal/controller/operator/eventing/integrationtests/controllersinglecr/integration_test.go @@ -6,14 +6,12 @@ import ( "testing" natstestutils "github.com/kyma-project/nats-manager/testutils" + "github.com/onsi/gomega" + gomegatypes "github.com/onsi/gomega/types" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/test/matchers" testutils "github.com/kyma-project/eventing-manager/test/utils" - - "github.com/onsi/gomega" - gomegatypes "github.com/onsi/gomega/types" - testutilsintegration "github.com/kyma-project/eventing-manager/test/utils/integration" ) diff --git a/internal/controller/operator/eventing/integrationtests/nats_disabled/integration_test.go b/internal/controller/operator/eventing/integrationtests/nats_disabled/integration_test.go index 057d2e7a..11a9052c 100644 --- a/internal/controller/operator/eventing/integrationtests/nats_disabled/integration_test.go +++ b/internal/controller/operator/eventing/integrationtests/nats_disabled/integration_test.go @@ -5,20 +5,17 @@ import ( "os" "testing" - eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" - natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/onsi/gomega" - - "github.com/kyma-project/eventing-manager/pkg/k8s" - "github.com/kyma-project/eventing-manager/test/matchers" - "github.com/kyma-project/eventing-manager/test/utils" - "github.com/stretchr/testify/require" kappsv1 "k8s.io/api/apps/v1" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" "github.com/kyma-project/eventing-manager/pkg/eventing" + "github.com/kyma-project/eventing-manager/pkg/k8s" + "github.com/kyma-project/eventing-manager/test/matchers" + "github.com/kyma-project/eventing-manager/test/utils" testutilsintegration "github.com/kyma-project/eventing-manager/test/utils/integration" ) diff --git a/internal/controller/operator/eventing/nats.go b/internal/controller/operator/eventing/nats.go index cd3d18a1..877c975b 100644 --- a/internal/controller/operator/eventing/nats.go +++ b/internal/controller/operator/eventing/nats.go @@ -4,13 +4,13 @@ import ( "context" "fmt" - "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" + "go.uber.org/zap" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/options" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/k8s" - "go.uber.org/zap" + "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" ) func (r *Reconciler) reconcileNATSSubManager(ctx context.Context, eventing *v1alpha1.Eventing, log *zap.SugaredLogger) error { diff --git a/internal/controller/operator/eventing/nats_test.go b/internal/controller/operator/eventing/nats_test.go index e46cc0be..8cd25e3f 100644 --- a/internal/controller/operator/eventing/nats_test.go +++ b/internal/controller/operator/eventing/nats_test.go @@ -7,20 +7,18 @@ import ( "testing" "time" - "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing/mocks" - - submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing/mocks" "github.com/kyma-project/eventing-manager/options" "github.com/kyma-project/eventing-manager/pkg/env" eventingmocks "github.com/kyma-project/eventing-manager/pkg/eventing/mocks" k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" + submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" submgrmocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/mocks" "github.com/kyma-project/eventing-manager/test/utils" ) diff --git a/internal/controller/operator/eventing/status.go b/internal/controller/operator/eventing/status.go index e53907c6..63562514 100644 --- a/internal/controller/operator/eventing/status.go +++ b/internal/controller/operator/eventing/status.go @@ -16,7 +16,7 @@ import ( const RequeueTimeForStatusCheck = 10 -// InitStateProcessing initializes the state of the EventingStatus if it is not set +// InitStateProcessing initializes the state of the EventingStatus if it is not set. func (es *Reconciler) InitStateProcessing(eventing *operatorv1alpha1.Eventing) { if eventing.Status.State == "" { eventing.Status.SetStateProcessing() @@ -26,7 +26,8 @@ func (es *Reconciler) InitStateProcessing(eventing *operatorv1alpha1.Eventing) { // syncStatusWithNATSErr syncs Eventing status and sets an error state. // Returns the relevant error. func (r *Reconciler) syncStatusWithNATSErr(ctx context.Context, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { // Set error state in status eventing.Status.SetStateError() eventing.Status.UpdateConditionNATSAvailable(kmetav1.ConditionFalse, operatorv1alpha1.ConditionReasonNATSNotAvailable, @@ -38,14 +39,16 @@ func (r *Reconciler) syncStatusWithNATSErr(ctx context.Context, // syncStatusWithPublisherProxyErr updates Publisher Proxy condition and sets an error state. // Returns the relevant error. func (r *Reconciler) syncStatusWithPublisherProxyErr(ctx context.Context, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { return r.syncStatusWithPublisherProxyErrWithReason(ctx, operatorv1alpha1.ConditionReasonDeployedFailed, eventing, err, log) } func (r *Reconciler) syncStatusWithPublisherProxyErrWithReason(ctx context.Context, reason operatorv1alpha1.ConditionReason, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { // Set error state in status eventing.Status.SetStateError() eventing.Status.UpdateConditionPublisherProxyReady(kmetav1.ConditionFalse, reason, @@ -57,7 +60,8 @@ func (r *Reconciler) syncStatusWithPublisherProxyErrWithReason(ctx context.Conte // syncStatusWithSubscriptionManagerErr updates subscription manager condition and sets an error state. // Returns the relevant error. func (r *Reconciler) syncStatusWithSubscriptionManagerErr(ctx context.Context, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { return r.syncStatusWithSubscriptionManagerErrWithReason(ctx, operatorv1alpha1.ConditionReasonEventMeshSubManagerFailed, eventing, err, log) } @@ -65,7 +69,8 @@ func (r *Reconciler) syncStatusWithSubscriptionManagerErr(ctx context.Context, func (r *Reconciler) syncStatusWithSubscriptionManagerErrWithReason(ctx context.Context, reason operatorv1alpha1.ConditionReason, eventing *operatorv1alpha1.Eventing, - err error, log *zap.SugaredLogger) error { + err error, log *zap.SugaredLogger, +) error { // Set error state in status eventing.Status.SetStateError() eventing.Status.UpdateConditionSubscriptionManagerReady(kmetav1.ConditionFalse, reason, err.Error()) @@ -76,7 +81,8 @@ func (r *Reconciler) syncStatusWithSubscriptionManagerErrWithReason(ctx context. // sets an error state. It doesn't return the incoming error. func (r *Reconciler) syncStatusWithSubscriptionManagerFailedCondition(ctx context.Context, eventing *operatorv1alpha1.Eventing, - err error, log *zap.SugaredLogger) error { + err error, log *zap.SugaredLogger, +) error { // Set error state in status eventing.Status.SetStateError() eventing.Status.UpdateConditionSubscriptionManagerReady(kmetav1.ConditionFalse, @@ -85,7 +91,8 @@ func (r *Reconciler) syncStatusWithSubscriptionManagerFailedCondition(ctx contex } func (r *Reconciler) syncStatusWithWebhookErr(ctx context.Context, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { // Set error state in status eventing.Status.SetStateError() eventing.Status.UpdateConditionWebhookReady(kmetav1.ConditionFalse, operatorv1alpha1.ConditionReasonWebhookFailed, @@ -95,7 +102,8 @@ func (r *Reconciler) syncStatusWithWebhookErr(ctx context.Context, } func (r *Reconciler) syncStatusWithDeletionErr(ctx context.Context, - eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, err error, log *zap.SugaredLogger, +) error { eventing.Status.UpdateConditionDeletion(kmetav1.ConditionFalse, operatorv1alpha1.ConditionReasonDeletionError, err.Error()) @@ -104,7 +112,8 @@ func (r *Reconciler) syncStatusWithDeletionErr(ctx context.Context, // syncEventingStatus syncs Eventing status. func (r *Reconciler) syncEventingStatus(ctx context.Context, - eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger) error { + eventing *operatorv1alpha1.Eventing, log *zap.SugaredLogger, +) error { namespacedName := &ktypes.NamespacedName{ Name: eventing.Name, Namespace: eventing.Namespace, @@ -126,7 +135,8 @@ func (r *Reconciler) syncEventingStatus(ctx context.Context, // updateStatus updates the status to k8s if modified. func (r *Reconciler) updateStatus(ctx context.Context, oldEventing, newEventing *operatorv1alpha1.Eventing, - logger *zap.SugaredLogger) error { + logger *zap.SugaredLogger, +) error { // Compare the status taking into consideration lastTransitionTime in conditions if oldEventing.Status.IsEqual(newEventing.Status) { return nil @@ -168,7 +178,7 @@ func (r *Reconciler) handleEventingState(ctx context.Context, deployment *kappsv return kctrl.Result{}, r.syncEventingStatus(ctx, eventing, log) } -// to be able to mock this function in tests +// to be able to mock this function in tests. var IsDeploymentReady = func(deployment *kappsv1.Deployment) bool { return deployment.Status.AvailableReplicas == *deployment.Spec.Replicas } diff --git a/internal/controller/operator/eventing/unit_test.go b/internal/controller/operator/eventing/unit_test.go index 3bed9c20..72e2bb99 100644 --- a/internal/controller/operator/eventing/unit_test.go +++ b/internal/controller/operator/eventing/unit_test.go @@ -4,34 +4,25 @@ import ( "context" "testing" - eventingcontrollermocks "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing/mocks" - - kapixclientsetfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" - - "github.com/kyma-project/eventing-manager/pkg/k8s" - + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + "github.com/stretchr/testify/require" kadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" kcorev1 "k8s.io/api/core/v1" - - "github.com/kyma-project/eventing-manager/pkg/env" - - "github.com/kyma-project/eventing-manager/options" - - "github.com/kyma-project/eventing-manager/pkg/logger" - + kapixclientsetfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" "k8s.io/apimachinery/pkg/runtime" - - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/types" + kdynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + eventingcontrollermocks "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing/mocks" + "github.com/kyma-project/eventing-manager/options" + "github.com/kyma-project/eventing-manager/pkg/env" eventingmocks "github.com/kyma-project/eventing-manager/pkg/eventing/mocks" - - kdynamicfake "k8s.io/client-go/dynamic/fake" + "github.com/kyma-project/eventing-manager/pkg/k8s" + "github.com/kyma-project/eventing-manager/pkg/logger" ) // MockedUnitTestEnvironment provides mocked resources for unit tests. diff --git a/internal/controller/operator/eventing/utils_test.go b/internal/controller/operator/eventing/utils_test.go index 79d2cc6e..418918d3 100644 --- a/internal/controller/operator/eventing/utils_test.go +++ b/internal/controller/operator/eventing/utils_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" @@ -53,7 +52,6 @@ func Test_addFinalizer(t *testing.T) { t.Parallel() t.Run("should add finalizer", func(t *testing.T) { - // given givenEventing := utils.NewEventingCR() @@ -75,7 +73,6 @@ func Test_removeFinalizer(t *testing.T) { t.Parallel() t.Run("should remove finalizer", func(t *testing.T) { - // given givenEventing := utils.NewEventingCR(utils.WithEventingCRFinalizer(FinalizerName)) diff --git a/internal/controller/operator/eventing/webhook.go b/internal/controller/operator/eventing/webhook.go index c5e2a5dc..6c0edeb1 100644 --- a/internal/controller/operator/eventing/webhook.go +++ b/internal/controller/operator/eventing/webhook.go @@ -4,9 +4,10 @@ import ( "bytes" "context" - emerrors "github.com/kyma-project/eventing-manager/pkg/errors" "github.com/pkg/errors" "sigs.k8s.io/controller-runtime/pkg/client" + + emerrors "github.com/kyma-project/eventing-manager/pkg/errors" ) const ( diff --git a/options/options.go b/options/options.go index 239e0bf7..a3758194 100644 --- a/options/options.go +++ b/options/options.go @@ -42,8 +42,8 @@ type Args struct { // Env represents the controller environment variables. type Env struct { - LogFormat string `envconfig:"APP_LOG_FORMAT" default:"json"` - LogLevel string `envconfig:"APP_LOG_LEVEL" default:"warn"` + LogFormat string `default:"json" envconfig:"APP_LOG_FORMAT"` + LogLevel string `default:"warn" envconfig:"APP_LOG_LEVEL"` } // New returns a new Options instance. diff --git a/pkg/backend/cleaner/jetstream_unit_test.go b/pkg/backend/cleaner/jetstream_unit_test.go index c0533fc1..62a5baca 100644 --- a/pkg/backend/cleaner/jetstream_unit_test.go +++ b/pkg/backend/cleaner/jetstream_unit_test.go @@ -3,9 +3,10 @@ package cleaner import ( "testing" - "github.com/kyma-project/eventing-manager/pkg/logger" kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" + + "github.com/kyma-project/eventing-manager/pkg/logger" ) func Test_JSCleanSource(t *testing.T) { diff --git a/pkg/backend/eventmesh/eventmesh.go b/pkg/backend/eventmesh/eventmesh.go index 81770bba..99f3fc88 100644 --- a/pkg/backend/eventmesh/eventmesh.go +++ b/pkg/backend/eventmesh/eventmesh.go @@ -5,10 +5,9 @@ import ( "fmt" "net/http" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "go.uber.org/zap" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" @@ -45,7 +44,8 @@ type Backend interface { } func NewEventMesh(credentials *OAuth2ClientCredentials, mapper backendutils.NameMapper, - logger *logger.Logger) *EventMesh { + logger *logger.Logger, +) *EventMesh { return &EventMesh{ oAuth2credentials: credentials, logger: logger, @@ -99,7 +99,8 @@ func getWebHookAuth(credentials *OAuth2ClientCredentials) *types.WebhookAuth { // SyncSubscription synchronize the EV2 subscription with the EMS subscription. // It returns true, if the EV2 subscription status was changed. func (em *EventMesh) SyncSubscription(subscription *eventingv1alpha2.Subscription, cleaner cleaner.Cleaner, - apiRule *apigatewayv1beta1.APIRule) (bool, error) { //nolint:funlen,gocognit + apiRule *apigatewayv1beta1.APIRule, +) (bool, error) { //nolint:funlen,gocognit // Format logger log := backendutils.LoggerWithSubscription(em.namedLogger(), subscription) @@ -119,11 +120,10 @@ func (em *EventMesh) SyncSubscription(subscription *eventingv1alpha2.Subscriptio } // check and handle if Kyma subscription or EventMesh subscription is modified - isKymaSubModified := false isEventMeshSubModified := false // check if Kyma Subscription was modified. - isKymaSubModified, err = em.handleKymaSubModified(eventMeshSub, subscription) + isKymaSubModified, err := em.handleKymaSubModified(eventMeshSub, subscription) if err != nil { log.Errorw("Failed to handle kyma subscription modified", errorLogKey, err) return false, err @@ -188,7 +188,8 @@ func (em *EventMesh) DeleteSubscription(subscription *eventingv1alpha2.Subscript // getProcessedEventTypes returns the processed types after cleaning // and prefixing as required by EventMesh specifications. func (em *EventMesh) getProcessedEventTypes(kymaSubscription *eventingv1alpha2.Subscription, - cleaner cleaner.Cleaner) ([]backendutils.EventTypeInfo, error) { + cleaner cleaner.Cleaner, +) ([]backendutils.EventTypeInfo, error) { // deduplicate event types uniqueTypes := kymaSubscription.GetUniqueTypes() @@ -218,8 +219,10 @@ func (em *EventMesh) getProcessedEventTypes(kymaSubscription *eventingv1alpha2.S "max number of segements allowed: %d", eventTypeSegmentsLimit) } - result = append(result, backendutils.EventTypeInfo{OriginalType: t, CleanType: cleanedType, - ProcessedType: eventMeshSubject}) + result = append(result, backendutils.EventTypeInfo{ + OriginalType: t, CleanType: cleanedType, + ProcessedType: eventMeshSubject, + }) } return result, nil @@ -292,7 +295,8 @@ func (em *EventMesh) handleCreateEventMeshSub(eventMeshSub *types.Subscription, // handleWebhookAuthChange handles the EventMesh subscription WebhookAuth changes. // It uses the PATCH request API provided by EventMesh to update the subscription WebhookAuth. func (em *EventMesh) handleWebhookAuthChange(eventMeshSub *types.Subscription, - kymaSub *eventingv1alpha2.Subscription) error { + kymaSub *eventingv1alpha2.Subscription, +) error { hash, err := backendutils.GetWebhookAuthHash(eventMeshSub.WebhookAuth) if err != nil { return fmt.Errorf("failed to get the EventMesh WebhookAuth hash: %w", err) @@ -357,7 +361,8 @@ func (em *EventMesh) handleWebhookAuthChange(eventMeshSub *types.Subscription, // Returns true if status is updated. func (em *EventMesh) handleKymaSubStatusUpdate(eventMeshServerSub *types.Subscription, eventMeshSub *types.Subscription, kymaSub *eventingv1alpha2.Subscription, - typesInfo []backendutils.EventTypeInfo) (bool, error) { + typesInfo []backendutils.EventTypeInfo, +) (bool, error) { // Update status.types kymaSub.Status.Types = statusCleanEventTypes(typesInfo) diff --git a/pkg/backend/eventmesh/eventmesh_integration_test.go b/pkg/backend/eventmesh/eventmesh_integration_test.go index 84ffaf76..391e5757 100644 --- a/pkg/backend/eventmesh/eventmesh_integration_test.go +++ b/pkg/backend/eventmesh/eventmesh_integration_test.go @@ -5,9 +5,8 @@ import ( "net/http" "testing" - "github.com/stretchr/testify/require" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" + "github.com/stretchr/testify/require" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" diff --git a/pkg/backend/eventmesh/mocks/Backend.go b/pkg/backend/eventmesh/mocks/Backend.go index 18d512c0..910da790 100644 --- a/pkg/backend/eventmesh/mocks/Backend.go +++ b/pkg/backend/eventmesh/mocks/Backend.go @@ -10,7 +10,7 @@ import ( v1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - v1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + v1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" ) // Backend is an autogenerated mock type for the Backend type diff --git a/pkg/backend/eventmesh/types.go b/pkg/backend/eventmesh/types.go index 0173bda4..9dfeef50 100644 --- a/pkg/backend/eventmesh/types.go +++ b/pkg/backend/eventmesh/types.go @@ -11,7 +11,7 @@ func (e HTTPStatusError) Error() string { } func (e *HTTPStatusError) Is(target error) bool { - t, ok := target.(*HTTPStatusError) //nolint: errorlint // converted to pointer and checked. + t, ok := target.(*HTTPStatusError) if !ok { return false } diff --git a/pkg/backend/eventmesh/utils.go b/pkg/backend/eventmesh/utils.go index 950033ec..d06fe2fd 100644 --- a/pkg/backend/eventmesh/utils.go +++ b/pkg/backend/eventmesh/utils.go @@ -22,7 +22,8 @@ func isEventTypeSegmentsOverLimit(eventType string) bool { } func updateHashesInStatus(kymaSubscription *eventingv1alpha2.Subscription, - eventMeshLocalSubscription *types.Subscription, eventMeshServerSubscription *types.Subscription) error { + eventMeshLocalSubscription *types.Subscription, eventMeshServerSubscription *types.Subscription, +) error { if err := setEventMeshLocalSubHashInStatus(kymaSubscription, eventMeshLocalSubscription); err != nil { return err } @@ -34,7 +35,8 @@ func updateHashesInStatus(kymaSubscription *eventingv1alpha2.Subscription, // setEventMeshLocalSubHashInStatus sets the hash for EventMesh local sub in Kyma Sub status. func setEventMeshLocalSubHashInStatus(kymaSubscription *eventingv1alpha2.Subscription, - eventMeshSubscription *types.Subscription) error { + eventMeshSubscription *types.Subscription, +) error { // generate hash newHash, err := backendutils.GetHash(eventMeshSubscription) if err != nil { @@ -66,7 +68,8 @@ func setWebhookAuthHashInStatus(kymaSubscription *eventingv1alpha2.Subscription, // setEventMeshServerSubHashInStatus sets the hash for EventMesh local sub in Kyma Sub status. func setEventMeshServerSubHashInStatus(kymaSubscription *eventingv1alpha2.Subscription, - eventMeshSubscription *types.Subscription) error { + eventMeshSubscription *types.Subscription, +) error { // clean up the server sub object from extra info cleanedEventMeshSub := backendutils.GetCleanedEventMeshSubscription(eventMeshSubscription) // generate hash @@ -83,8 +86,10 @@ func setEventMeshServerSubHashInStatus(kymaSubscription *eventingv1alpha2.Subscr func statusCleanEventTypes(typeInfos []backendutils.EventTypeInfo) []eventingv1alpha2.EventType { var cleanEventTypes []eventingv1alpha2.EventType for _, i := range typeInfos { - cleanEventTypes = append(cleanEventTypes, eventingv1alpha2.EventType{OriginalType: i.OriginalType, - CleanType: i.CleanType}) + cleanEventTypes = append(cleanEventTypes, eventingv1alpha2.EventType{ + OriginalType: i.OriginalType, + CleanType: i.CleanType, + }) } return cleanEventTypes } @@ -102,8 +107,9 @@ func statusFinalEventTypes(typeInfos []backendutils.EventTypeInfo) []eventingv1a // setEmsSubscriptionStatus sets the status of EventMesh Subscription in ev2Subscription. func setEmsSubscriptionStatus(subscription *eventingv1alpha2.Subscription, - eventMeshSubscription *types.Subscription) bool { - var statusChanged = false + eventMeshSubscription *types.Subscription, +) bool { + statusChanged := false if subscription.Status.Backend.EventMeshSubscriptionStatus == nil { subscription.Status.Backend.EventMeshSubscriptionStatus = &eventingv1alpha2.EventMeshSubscriptionStatus{} } @@ -113,26 +119,22 @@ func setEmsSubscriptionStatus(subscription *eventingv1alpha2.Subscription, } if subscription.Status.Backend.EventMeshSubscriptionStatus.StatusReason != eventMeshSubscription.SubscriptionStatusReason { - subscription.Status.Backend.EventMeshSubscriptionStatus.StatusReason = - eventMeshSubscription.SubscriptionStatusReason + subscription.Status.Backend.EventMeshSubscriptionStatus.StatusReason = eventMeshSubscription.SubscriptionStatusReason statusChanged = true } if subscription.Status.Backend.EventMeshSubscriptionStatus.LastSuccessfulDelivery != eventMeshSubscription.LastSuccessfulDelivery { - subscription.Status.Backend.EventMeshSubscriptionStatus.LastSuccessfulDelivery = - eventMeshSubscription.LastSuccessfulDelivery + subscription.Status.Backend.EventMeshSubscriptionStatus.LastSuccessfulDelivery = eventMeshSubscription.LastSuccessfulDelivery statusChanged = true } if subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDelivery != eventMeshSubscription.LastFailedDelivery { - subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDelivery = - eventMeshSubscription.LastFailedDelivery + subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDelivery = eventMeshSubscription.LastFailedDelivery statusChanged = true } if subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDeliveryReason != eventMeshSubscription.LastFailedDeliveryReason { - subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDeliveryReason = - eventMeshSubscription.LastFailedDeliveryReason + subscription.Status.Backend.EventMeshSubscriptionStatus.LastFailedDeliveryReason = eventMeshSubscription.LastFailedDeliveryReason statusChanged = true } return statusChanged diff --git a/pkg/backend/eventtype/clean_internal_unit_test.go b/pkg/backend/eventtype/clean_internal_unit_test.go index 853abc8a..757dc2af 100644 --- a/pkg/backend/eventtype/clean_internal_unit_test.go +++ b/pkg/backend/eventtype/clean_internal_unit_test.go @@ -3,10 +3,10 @@ package eventtype import ( "testing" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/pkg/logger" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" ) func TestCleaner(t *testing.T) { diff --git a/pkg/backend/eventtype/simple_clean.go b/pkg/backend/eventtype/simple_clean.go index 1b17f119..637a82be 100644 --- a/pkg/backend/eventtype/simple_clean.go +++ b/pkg/backend/eventtype/simple_clean.go @@ -13,10 +13,8 @@ const ( simpleCleanerName = "event-type-simple-cleaner" ) -var ( - // invalidApplicationNameSegment used to match and replace none-alphanumeric characters in the application name. - invalidApplicationNameSegment = regexp.MustCompile(`\W|_`) -) +// invalidApplicationNameSegment used to match and replace none-alphanumeric characters in the application name. +var invalidApplicationNameSegment = regexp.MustCompile(`\W|_`) type simpleCleaner struct { eventTypePrefix string @@ -42,7 +40,7 @@ func (sc *simpleCleaner) Clean(eventType string) (string, error) { } // clean the application name - var eventTypeClean = build(sc.eventTypePrefix, getCleanName(appName), event, version) + eventTypeClean := build(sc.eventTypePrefix, getCleanName(appName), event, version) // clean the event-type segments eventTypeClean = cleanEventType(eventTypeClean) diff --git a/pkg/backend/jetstream/config_internal_unit_test.go b/pkg/backend/jetstream/config_internal_unit_test.go index bf05d49b..98af3ecd 100644 --- a/pkg/backend/jetstream/config_internal_unit_test.go +++ b/pkg/backend/jetstream/config_internal_unit_test.go @@ -4,8 +4,9 @@ import ( "strings" "testing" - "github.com/kyma-project/eventing-manager/pkg/env" "github.com/stretchr/testify/assert" + + "github.com/kyma-project/eventing-manager/pkg/env" ) func TestUnitValidate_For_Errors(t *testing.T) { diff --git a/pkg/backend/jetstream/connection_integration_test.go b/pkg/backend/jetstream/connection_integration_test.go index cf4ad684..6988d8c3 100644 --- a/pkg/backend/jetstream/connection_integration_test.go +++ b/pkg/backend/jetstream/connection_integration_test.go @@ -5,14 +5,13 @@ import ( "testing" "time" - "github.com/kyma-project/eventing-manager/pkg/env" - "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" + "github.com/kyma-project/eventing-manager/pkg/env" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) diff --git a/pkg/backend/jetstream/jetstream.go b/pkg/backend/jetstream/jetstream.go index 32357199..f470d0e9 100644 --- a/pkg/backend/jetstream/jetstream.go +++ b/pkg/backend/jetstream/jetstream.go @@ -8,22 +8,19 @@ import ( "strings" "time" - cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" - - backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" - "github.com/kyma-project/eventing-manager/pkg/errors" - cloudevents "github.com/cloudevents/sdk-go/v2" ceprotocol "github.com/cloudevents/sdk-go/v2/protocol" + cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" "github.com/nats-io/nats.go" pkgerrors "github.com/pkg/errors" "go.uber.org/zap" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendmetrics "github.com/kyma-project/eventing-manager/pkg/backend/metrics" + backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/kyma-project/eventing-manager/pkg/errors" "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-manager/pkg/tracing" "github.com/kyma-project/eventing-manager/pkg/utils" @@ -42,7 +39,8 @@ const ( ) func NewJetStream(config env.NATSConfig, metricsCollector *backendmetrics.Collector, - cleaner cleaner.Cleaner, subsConfig env.DefaultSubscriptionConfig, logger *logger.Logger) *JetStream { + cleaner cleaner.Cleaner, subsConfig env.DefaultSubscriptionConfig, logger *logger.Logger, +) *JetStream { return &JetStream{ Config: config, logger: logger, @@ -160,7 +158,8 @@ func (js *JetStream) DeleteSubscriptionsOnly(subscription *eventingv1alpha2.Subs // GetJetStreamSubjects returns a list of subjects appended with prefix if needed. func (js *JetStream) GetJetStreamSubjects(source string, subjects []string, - typeMatching eventingv1alpha2.TypeMatching) []string { + typeMatching eventingv1alpha2.TypeMatching, +) []string { var result []string for _, subject := range subjects { result = append(result, js.GetJetStreamSubject(source, subject, typeMatching)) @@ -376,7 +375,8 @@ func (js *JetStream) syncSubscriptionEventTypes(subscription *eventingv1alpha2.S // syncSubscriptionEventType syncs controller runtime subscriptions to subscription CR event types and to JetStream // subscriptions/consumers. func (js *JetStream) syncSubscriptionEventType(key SubscriptionSubjectIdentifier, - subscription *eventingv1alpha2.Subscription, subscriber Subscriber) error { + subscription *eventingv1alpha2.Subscription, subscriber Subscriber, +) error { // don't try to delete invalid subscriber and its consumer if subscriber has type in subscription CR it belongs to. // This means that it will be bound to the existing JetStream consumer in later steps. if !subscriber.IsValid() && js.runtimeSubscriptionExistsInKymaSub(key, subscription) { @@ -391,7 +391,8 @@ func (js *JetStream) cleanupUnnecessaryJetStreamSubscribers( jsSub Subscriber, subscription *eventingv1alpha2.Subscription, log *zap.SugaredLogger, - key SubscriptionSubjectIdentifier) error { + key SubscriptionSubjectIdentifier, +) error { consumer, err := js.jsCtx.ConsumerInfo(js.Config.JSStreamName, key.ConsumerName()) if err != nil { if pkgerrors.Is(err, nats.ErrConsumerNotFound) { @@ -418,7 +419,8 @@ func (js *JetStream) cleanupUnnecessaryJetStreamSubscribers( // runtimeSubscriptionExistsInKymaSub returns true if runtime subscriber subject exists in subscription CR. func (js *JetStream) runtimeSubscriptionExistsInKymaSub(runtimeSubscriptionKey SubscriptionSubjectIdentifier, - subscription *eventingv1alpha2.Subscription) bool { + subscription *eventingv1alpha2.Subscription, +) bool { for _, subject := range subscription.Status.Types { jsSubject := js.getJetStreamSubject(subscription.Spec.Source, subject.CleanType, subscription.Spec.TypeMatching) jsSubKey := NewSubscriptionSubjectIdentifier(subscription, jsSubject) @@ -431,7 +433,8 @@ func (js *JetStream) runtimeSubscriptionExistsInKymaSub(runtimeSubscriptionKey S // consumerSubjectExistsInKymaSub checks if the specified consumer is used by the subscription. func (js *JetStream) consumerSubjectExistsInKymaSub(consumer *nats.ConsumerInfo, - subscription *eventingv1alpha2.Subscription) bool { + subscription *eventingv1alpha2.Subscription, +) bool { return utils.ContainsString( js.GetJetStreamSubjects( subscription.Spec.Source, @@ -462,7 +465,8 @@ func (js *JetStream) deleteSubscriptionFromJetStream(jsSub Subscriber, jsSubKey // deleteSubscriptionFromJetStreamOnly deletes the subscription from NATS server and from in-memory db. // Note: The consumer will not be deleted, meaning there should be no message loss. func (js *JetStream) deleteSubscriptionFromJetStreamOnly(jsSub Subscriber, - jsSubKey SubscriptionSubjectIdentifier) error { + jsSubKey SubscriptionSubjectIdentifier, +) error { if jsSub.IsValid() { // The Unsubscribe function should not delete the consumer because it was added manually. if err := jsSub.Unsubscribe(); err != nil { @@ -580,7 +584,8 @@ func (js *JetStream) deleteConsumerFromJetStream(name string) error { // syncConsumerAndSubscription makes sure there is a consumer and subscription created on the NATS Backend. // these also must be bound to each other to ensure that NATS JetStream eventing logic works as expected. func (js *JetStream) syncConsumerAndSubscription(subscription *eventingv1alpha2.Subscription, - asyncCallback func(m *nats.Msg)) error { + asyncCallback func(m *nats.Msg), +) error { for _, eventType := range subscription.Status.Types { jsSubject := js.GetJetStreamSubject(subscription.Spec.Source, eventType.CleanType, subscription.Spec.TypeMatching) jsSubKey := NewSubscriptionSubjectIdentifier(subscription, jsSubject) @@ -620,7 +625,8 @@ func (js *JetStream) syncConsumerAndSubscription(subscription *eventingv1alpha2. // getOrCreateConsumer fetches the ConsumerInfo from NATS Server or creates it in case it doesn't exist. func (js *JetStream) getOrCreateConsumer(subscription *eventingv1alpha2.Subscription, - subject eventingv1alpha2.EventType) (*nats.ConsumerInfo, error) { + subject eventingv1alpha2.EventType, +) (*nats.ConsumerInfo, error) { jsSubject := js.GetJetStreamSubject(subscription.Spec.Source, subject.CleanType, subscription.Spec.TypeMatching) jsSubKey := NewSubscriptionSubjectIdentifier(subscription, jsSubject) @@ -644,7 +650,8 @@ func (js *JetStream) getOrCreateConsumer(subscription *eventingv1alpha2.Subscrip // createNATSSubscription creates a NATS Subscription and binds it to the already existing consumer. func (js *JetStream) createNATSSubscription(subscription *eventingv1alpha2.Subscription, - subject eventingv1alpha2.EventType, asyncCallback func(m *nats.Msg)) error { + subject eventingv1alpha2.EventType, asyncCallback func(m *nats.Msg), +) error { jsSubject := js.GetJetStreamSubject(subscription.Spec.Source, subject.CleanType, subscription.Spec.TypeMatching) jsSubKey := NewSubscriptionSubjectIdentifier(subscription, jsSubject) @@ -671,7 +678,8 @@ func (js *JetStream) createNATSSubscription(subscription *eventingv1alpha2.Subsc // bindInvalidSubscriptions tries to bind the invalid NATS Subscription to the existing consumer. func (js *JetStream) bindInvalidSubscriptions(subscription *eventingv1alpha2.Subscription, - subject eventingv1alpha2.EventType, asyncCallback func(m *nats.Msg)) error { + subject eventingv1alpha2.EventType, asyncCallback func(m *nats.Msg), +) error { jsSubject := js.GetJetStreamSubject(subscription.Spec.Source, subject.CleanType, subscription.Spec.TypeMatching) jsSubKey := NewSubscriptionSubjectIdentifier(subscription, jsSubject) // bind the existing consumer to a new subscription on JetStream @@ -691,7 +699,8 @@ func (js *JetStream) bindInvalidSubscriptions(subscription *eventingv1alpha2.Sub // syncConsumerMaxInFlight checks that the latest Subscription's maxInFlight value // is propagated to the NATS consumer as MaxAckPending. func (js *JetStream) syncConsumerMaxInFlight(subscription *eventingv1alpha2.Subscription, - consumerInfo nats.ConsumerInfo) error { + consumerInfo nats.ConsumerInfo, +) error { ecSubsConfig := env.DefaultSubscriptionConfig(js.subsConfig) maxInFlight := subscription.GetMaxInFlightMessages(&ecSubsConfig) diff --git a/pkg/backend/jetstream/jetstream_integration_test.go b/pkg/backend/jetstream/jetstream_integration_test.go index 7b86170f..a9c50974 100644 --- a/pkg/backend/jetstream/jetstream_integration_test.go +++ b/pkg/backend/jetstream/jetstream_integration_test.go @@ -7,10 +7,9 @@ import ( "testing" "time" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" - - kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" @@ -302,7 +301,8 @@ func prepareTestEnvironment(t *testing.T) *TestEnvironment { func createSubscriptionAndAssert(t *testing.T, testEnv *TestEnvironment, - subscriber *eventingtesting.Subscriber) (SubscriptionSubjectIdentifier, *eventingv1alpha2.Subscription) { + subscriber *eventingtesting.Subscriber, +) (SubscriptionSubjectIdentifier, *eventingv1alpha2.Subscription) { sub := eventingtesting.NewSubscription("sub", "foo", eventingtesting.WithCleanEventSourceAndType(), eventingtesting.WithNotCleanEventSourceAndType(), @@ -351,7 +351,8 @@ func startJetStream(t *testing.T, testEnv *TestEnvironment) { func assertNewSubscriptionReturnItsKey(t *testing.T, testEnv *TestEnvironment, - sub *eventingv1alpha2.Subscription) SubscriptionSubjectIdentifier { + sub *eventingv1alpha2.Subscription, +) SubscriptionSubjectIdentifier { firstSubject, err := testEnv.cleaner.CleanEventType(sub.Spec.Types[0]) require.NoError(t, err) require.NotEmpty(t, firstSubject) diff --git a/pkg/backend/jetstream/jetstream_internal_unit_test.go b/pkg/backend/jetstream/jetstream_internal_unit_test.go index 1f33f831..ac1399ab 100644 --- a/pkg/backend/jetstream/jetstream_internal_unit_test.go +++ b/pkg/backend/jetstream/jetstream_internal_unit_test.go @@ -3,23 +3,19 @@ package jetstream import ( "testing" - "github.com/kyma-project/eventing-manager/pkg/env" - ceevent "github.com/cloudevents/sdk-go/v2/event" kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/nats-io/nats.go" - - backendjetstreammocks "github.com/kyma-project/eventing-manager/pkg/backend/jetstream/mocks" - "github.com/kyma-project/eventing-manager/pkg/logger" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" + backendjetstreammocks "github.com/kyma-project/eventing-manager/pkg/backend/jetstream/mocks" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" + "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/kyma-project/eventing-manager/pkg/logger" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) @@ -842,7 +838,7 @@ func NewConsumers(subs []v1alpha2.Subscription, jsBackend *JetStream) []*nats.Co // existing subscription type with existing consumers // namespace: test1, sub: test1, type: v1 return []*nats.ConsumerInfo{ - &nats.ConsumerInfo{ + { Name: computeConsumerName( &sub1, jsBackend.getJetStreamSubject(sub1.Spec.Source, @@ -852,7 +848,7 @@ func NewConsumers(subs []v1alpha2.Subscription, jsBackend *JetStream) []*nats.Co Config: nats.ConsumerConfig{MaxAckPending: DefaultMaxInFlights}, PushBound: false, }, - &nats.ConsumerInfo{ + { Name: computeConsumerName( &sub2, jsBackend.getJetStreamSubject(sub2.Spec.Source, @@ -862,7 +858,7 @@ func NewConsumers(subs []v1alpha2.Subscription, jsBackend *JetStream) []*nats.Co Config: nats.ConsumerConfig{MaxAckPending: DefaultMaxInFlights}, PushBound: false, }, - &nats.ConsumerInfo{ + { Name: computeConsumerName( &sub2, jsBackend.getJetStreamSubject(sub2.Spec.Source, diff --git a/pkg/backend/jetstream/stubs_test.go b/pkg/backend/jetstream/stubs_test.go index 9e136434..1acb6882 100644 --- a/pkg/backend/jetstream/stubs_test.go +++ b/pkg/backend/jetstream/stubs_test.go @@ -105,13 +105,15 @@ func (j jetStreamContextStub) ChanSubscribe(_ string, _ chan *nats.Msg, _ ...nat } func (j jetStreamContextStub) ChanQueueSubscribe(_, _ string, - _ chan *nats.Msg, _ ...nats.SubOpt) (*nats.Subscription, error) { + _ chan *nats.Msg, _ ...nats.SubOpt, +) (*nats.Subscription, error) { // TODO implement me panic("implement me") } func (j jetStreamContextStub) QueueSubscribe(_, _ string, _ nats.MsgHandler, - _ ...nats.SubOpt) (*nats.Subscription, error) { + _ ...nats.SubOpt, +) (*nats.Subscription, error) { // TODO implement me panic("implement me") } @@ -180,12 +182,14 @@ func (j jetStreamContextStub) SecureDeleteMsg(_ string, _ uint64, _ ...nats.JSOp } func (j jetStreamContextStub) AddConsumer(_ string, _ *nats.ConsumerConfig, - _ ...nats.JSOpt) (*nats.ConsumerInfo, error) { + _ ...nats.JSOpt, +) (*nats.ConsumerInfo, error) { return j.addConsumer, j.addConsumerError } func (j jetStreamContextStub) UpdateConsumer(_ string, _ *nats.ConsumerConfig, - _ ...nats.JSOpt) (*nats.ConsumerInfo, error) { + _ ...nats.JSOpt, +) (*nats.ConsumerInfo, error) { return j.update, j.updateError } diff --git a/pkg/backend/jetstream/test_helpers.go b/pkg/backend/jetstream/test_helpers.go index 7b0ef651..811f5200 100644 --- a/pkg/backend/jetstream/test_helpers.go +++ b/pkg/backend/jetstream/test_helpers.go @@ -7,21 +7,17 @@ import ( "net/http" "time" - "github.com/kyma-project/eventing-manager/pkg/env" - - "github.com/nats-io/nats-server/v2/server" - - "github.com/kyma-project/eventing-manager/pkg/logger" - - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - cenats "github.com/cloudevents/sdk-go/protocol/nats/v2" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" + "github.com/nats-io/nats-server/v2/server" "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/kyma-project/eventing-manager/pkg/logger" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) @@ -80,7 +76,7 @@ func SendCloudEventToJetStream(jetStreamClient *JetStream, subject, eventData, c } else { headers = eventingtesting.GetStructuredMessageHeaders() } - req, err := http.NewRequest(http.MethodPost, "dummy", bytes.NewBuffer([]byte(eventData))) + req, err := http.NewRequest(http.MethodPost, "dummy", bytes.NewBufferString(eventData)) if err != nil { return err } @@ -104,7 +100,7 @@ func SendCloudEventToJetStream(jetStreamClient *JetStream, subject, eventData, c url := jetStreamClient.Config.URL sender, err := cenats.NewSender(url, subject, natsOpts) if err != nil { - return nil + return err } client, err := cloudevents.NewClient(sender) if err != nil { diff --git a/pkg/backend/jetstream/types.go b/pkg/backend/jetstream/types.go index 383d53ee..144ed8c9 100644 --- a/pkg/backend/jetstream/types.go +++ b/pkg/backend/jetstream/types.go @@ -5,15 +5,13 @@ package jetstream import ( "sync" - "github.com/nats-io/nats.go" - - backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" - cloudevents "github.com/cloudevents/sdk-go/v2" + "github.com/nats-io/nats.go" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendmetrics "github.com/kyma-project/eventing-manager/pkg/backend/metrics" + backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" ) diff --git a/pkg/backend/jetstream/utils.go b/pkg/backend/jetstream/utils.go index 14d88765..811fd02c 100644 --- a/pkg/backend/jetstream/utils.go +++ b/pkg/backend/jetstream/utils.go @@ -6,18 +6,15 @@ import ( "fmt" "strings" - "github.com/kyma-project/eventing-manager/pkg/env" - - pkgerrors "github.com/pkg/errors" - "github.com/nats-io/nats.go" + pkgerrors "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/types" - "github.com/kyma-project/eventing-manager/pkg/errors" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" + "github.com/kyma-project/eventing-manager/pkg/env" + "github.com/kyma-project/eventing-manager/pkg/errors" ) const ( @@ -38,7 +35,8 @@ const ( // getDefaultSubscriptionOptions builds the default nats.SubOpts by using the subscription/consumer configuration. func (js *JetStream) getDefaultSubscriptionOptions(consumer SubscriptionSubjectIdentifier, - maxInFlightMessages int) DefaultSubOpts { + maxInFlightMessages int, +) DefaultSubOpts { return DefaultSubOpts{ nats.Durable(consumer.consumerName), nats.Description(consumer.namespacedSubjectName), @@ -54,9 +52,11 @@ func (js *JetStream) getDefaultSubscriptionOptions(consumer SubscriptionSubjectI } } -var ErrInvalidStorageType = errors.NewArgumentError("invalid stream storage type: %q") -var ErrInvalidRetentionPolicy = errors.NewArgumentError("invalid stream retention policy: %q") -var ErrInvalidDiscardPolicy = errors.NewArgumentError("invalid stream discard policy: %q") +var ( + ErrInvalidStorageType = errors.NewArgumentError("invalid stream storage type: %q") + ErrInvalidRetentionPolicy = errors.NewArgumentError("invalid stream retention policy: %q") + ErrInvalidDiscardPolicy = errors.NewArgumentError("invalid stream discard policy: %q") +) // toJetStreamStorageType converts a string to a nats.StorageType. func toJetStreamStorageType(s string) (nats.StorageType, error) { @@ -169,7 +169,8 @@ func getStreamConfig(natsConfig env.NATSConfig) (*nats.StreamConfig, error) { // getConsumerConfig return the consumerConfig according to the default configuration. func (js *JetStream) getConsumerConfig(jsSubKey SubscriptionSubjectIdentifier, - jsSubject string, maxInFlight int) *nats.ConsumerConfig { + jsSubject string, maxInFlight int, +) *nats.ConsumerConfig { return &nats.ConsumerConfig{ Durable: jsSubKey.ConsumerName(), Description: jsSubKey.namespacedSubjectName, @@ -202,7 +203,7 @@ func GetCleanEventTypesFromEventTypes(eventTypes []eventingv1alpha2.EventType) [ return cleantypes } -// TODO: to be moved to subscription types +// TODO: to be moved to subscription types. func getUniqueEventTypes(eventTypes []string) []string { unique := make([]string, 0, len(eventTypes)) mapper := make(map[string]bool) @@ -238,15 +239,18 @@ func GetCleanEventTypes(sub *eventingv1alpha2.Subscription, cleaner cleaner.Clea // GetBackendJetStreamTypes gets the original event type and the consumer name for all the subscriptions // and this slice is set as the backend specific status for JetStream. func GetBackendJetStreamTypes(subscription *eventingv1alpha2.Subscription, - jsSubjects []string) ([]eventingv1alpha2.JetStreamTypes, error) { + jsSubjects []string, +) ([]eventingv1alpha2.JetStreamTypes, error) { if len(jsSubjects) != len(subscription.Spec.Types) { return nil, pkgerrors.New("length of JetStream subjects do not match with eventTypes from spec") } var jsTypes []eventingv1alpha2.JetStreamTypes for i, ot := range subscription.Spec.Types { - jt := eventingv1alpha2.JetStreamTypes{OriginalType: ot, - ConsumerName: computeConsumerName(subscription, jsSubjects[i])} + jt := eventingv1alpha2.JetStreamTypes{ + OriginalType: ot, + ConsumerName: computeConsumerName(subscription, jsSubjects[i]), + } jsTypes = append(jsTypes, jt) } return jsTypes, nil @@ -255,7 +259,8 @@ func GetBackendJetStreamTypes(subscription *eventingv1alpha2.Subscription, // isJsSubAssociatedWithKymaSub returns true if the given SubscriptionSubjectIdentifier and Kyma subscription // have the same namespaced name, otherwise returns false. func isJsSubAssociatedWithKymaSub(jsSubKey SubscriptionSubjectIdentifier, - subscription *eventingv1alpha2.Subscription) bool { + subscription *eventingv1alpha2.Subscription, +) bool { return createKeyPrefix(subscription) == jsSubKey.NamespacedName() } @@ -275,7 +280,8 @@ func (s SubscriptionSubjectIdentifier) ConsumerName() string { // NewSubscriptionSubjectIdentifier returns a new SubscriptionSubjectIdentifier instance. func NewSubscriptionSubjectIdentifier(subscription *eventingv1alpha2.Subscription, - subject string) SubscriptionSubjectIdentifier { + subject string, +) SubscriptionSubjectIdentifier { cn := computeConsumerName(subscription, subject) // compute the consumer name once nn := computeNamespacedSubjectName(subscription, subject) // compute the namespaced name with the subject once return SubscriptionSubjectIdentifier{consumerName: cn, namespacedSubjectName: nn} diff --git a/pkg/backend/jetstream/utils_internal_unit_test.go b/pkg/backend/jetstream/utils_internal_unit_test.go index 822d95a4..eec0628b 100644 --- a/pkg/backend/jetstream/utils_internal_unit_test.go +++ b/pkg/backend/jetstream/utils_internal_unit_test.go @@ -5,15 +5,13 @@ import ( "reflect" "testing" - "github.com/nats-io/nats.go" - - "github.com/kyma-project/eventing-manager/pkg/env" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" + "github.com/nats-io/nats.go" "github.com/stretchr/testify/require" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" + "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) diff --git a/pkg/backend/metrics/collector.go b/pkg/backend/metrics/collector.go index 7c9a2c4f..f83cf2a7 100644 --- a/pkg/backend/metrics/collector.go +++ b/pkg/backend/metrics/collector.go @@ -141,7 +141,8 @@ func (c *Collector) RecordDeliveryPerSubscription(subscriptionName, subscription func (c *Collector) RecordLatencyPerSubscription( duration time.Duration, subscriptionName, subscriptionNamespace, eventType, consumerName, sink string, - statusCode int) { + statusCode int, +) { c.latencyPerSubscriber.WithLabelValues( subscriptionName, subscriptionNamespace, @@ -158,7 +159,8 @@ func (c *Collector) RecordEventTypes(subscriptionName, subscriptionNamespace, ev // RecordSubscriptionStatus records an eventing_ec_subscription_status metric. func (c *Collector) RecordSubscriptionStatus(isActive bool, subscriptionName, - subscriptionNamespace, backendType, consumer, streamName string) { + subscriptionNamespace, backendType, consumer, streamName string, +) { var v float64 if isActive { v = 1 @@ -174,7 +176,8 @@ func (c *Collector) RecordSubscriptionStatus(isActive bool, subscriptionName, // RemoveSubscriptionStatus removes an eventing_ec_subscription_status metric. func (c *Collector) RemoveSubscriptionStatus(subscriptionName, subscriptionNamespace, - backendType, consumer, streamName string) { + backendType, consumer, streamName string, +) { c.subscriptionStatus.Delete(prometheus.Labels{ subscriptionNameLabel: subscriptionName, subscriptionNamespaceLabel: subscriptionNamespace, diff --git a/pkg/backend/sink/validator.go b/pkg/backend/sink/validator.go index 8f7c706a..b7cc2e40 100644 --- a/pkg/backend/sink/validator.go +++ b/pkg/backend/sink/validator.go @@ -3,18 +3,16 @@ package sink import ( "context" - kcorev1 "k8s.io/api/core/v1" - ktypes "k8s.io/apimachinery/pkg/types" - "golang.org/x/xerrors" + kcorev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" + ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" - "github.com/kyma-project/eventing-manager/pkg/utils" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/internal/controller/events" + "github.com/kyma-project/eventing-manager/pkg/utils" ) type Validator interface { diff --git a/pkg/backend/utils/eventmesh_utils.go b/pkg/backend/utils/eventmesh_utils.go index 932d3ba0..7b1649fe 100644 --- a/pkg/backend/utils/eventmesh_utils.go +++ b/pkg/backend/utils/eventmesh_utils.go @@ -5,11 +5,10 @@ import ( "fmt" "strconv" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/mitchellh/hashstructure/v2" "github.com/pkg/errors" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" "github.com/kyma-project/eventing-manager/pkg/featureflags" @@ -84,7 +83,8 @@ func getDefaultSubscriptionV1Alpha2(protocolSettings *ProtocolSettings) (*types. } func getEventMeshEvents(typeInfos []EventTypeInfo, typeMatching eventingv1alpha2.TypeMatching, - defaultNamespace, source string) types.Events { + defaultNamespace, source string, +) types.Events { eventMeshNamespace := defaultNamespace if typeMatching == eventingv1alpha2.TypeMatchingExact && source != "" { eventMeshNamespace = source @@ -107,7 +107,8 @@ func getEventMeshEvents(typeInfos []EventTypeInfo, typeMatching eventingv1alpha2 func ConvertKymaSubToEventMeshSub(subscription *eventingv1alpha2.Subscription, typeInfos []EventTypeInfo, apiRule *apigatewayv1beta1.APIRule, defaultWebhookAuth *types.WebhookAuth, defaultProtocolSettings *ProtocolSettings, - defaultNamespace string, nameMapper NameMapper) (*types.Subscription, error) { //nolint:gocognit + defaultNamespace string, nameMapper NameMapper, +) (*types.Subscription, error) { //nolint:gocognit // get default EventMesh subscription object eventMeshSubscription, err := getDefaultSubscriptionV1Alpha2(defaultProtocolSettings) if err != nil { @@ -166,7 +167,8 @@ func setEventMeshProtocolSettings(subscription *eventingv1alpha2.Subscription, e // getEventMeshWebhookAuth uses default webhook auth unless specified in Subscription CR. func getEventMeshWebhookAuth(subscription *eventingv1alpha2.Subscription, - defaultWebhookAuth *types.WebhookAuth) (*types.WebhookAuth, error) { + defaultWebhookAuth *types.WebhookAuth, +) (*types.WebhookAuth, error) { auth := &types.WebhookAuth{} // extract auth info from subscription CR if any if authType, ok := subscription.Spec.Config[eventingv1alpha2.WebhookAuthType]; ok { diff --git a/pkg/backend/utils/eventmesh_utils_test.go b/pkg/backend/utils/eventmesh_utils_test.go index 8cf746cf..587c843b 100644 --- a/pkg/backend/utils/eventmesh_utils_test.go +++ b/pkg/backend/utils/eventmesh_utils_test.go @@ -6,18 +6,16 @@ import ( "strings" "testing" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/stretchr/testify/require" - - "github.com/kyma-project/eventing-manager/pkg/utils" - - . "github.com/onsi/gomega" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + "github.com/kyma-project/eventing-manager/pkg/utils" eventingtesting "github.com/kyma-project/eventing-manager/testing" + + . "github.com/onsi/gomega" ) func TestConvertKymaSubToEventMeshSub(t *testing.T) { diff --git a/pkg/backend/utils/utils.go b/pkg/backend/utils/utils.go index a749ceb1..c656ff90 100644 --- a/pkg/backend/utils/utils.go +++ b/pkg/backend/utils/utils.go @@ -6,18 +6,16 @@ import ( "fmt" "net/url" + ceevent "github.com/cloudevents/sdk-go/v2/event" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" + "github.com/nats-io/nats.go" "github.com/pkg/errors" "go.uber.org/zap" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - - ceevent "github.com/cloudevents/sdk-go/v2/event" - "github.com/nats-io/nats.go" - - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - "k8s.io/apimachinery/pkg/runtime/schema" ) type EventTypeInfo struct { @@ -77,7 +75,8 @@ func GetExposedURLFromAPIRule(apiRule *apigatewayv1beta1.APIRule, targetURL stri // UpdateSubscriptionStatus updates the status of all Kyma subscriptions on k8s. func UpdateSubscriptionStatus(ctx context.Context, dClient dynamic.Interface, - sub *eventingv1alpha2.Subscription) error { + sub *eventingv1alpha2.Subscription, +) error { unstructuredObj, err := sub.ToUnstructuredSub() if err != nil { return errors.Wrap(err, "convert subscription to unstructured failed") @@ -92,7 +91,8 @@ func UpdateSubscriptionStatus(ctx context.Context, dClient dynamic.Interface, // LoggerWithSubscription returns a logger with the given subscription (v1alpha2) details. func LoggerWithSubscription(log *zap.SugaredLogger, - subscription *eventingv1alpha2.Subscription) *zap.SugaredLogger { + subscription *eventingv1alpha2.Subscription, +) *zap.SugaredLogger { return log.With( "kind", subscription.GetObjectKind().GroupVersionKind().Kind, "version", subscription.GetGeneration(), diff --git a/pkg/cloudevent/client_unit_test.go b/pkg/cloudevent/client_unit_test.go index 743bd85e..99888a27 100644 --- a/pkg/cloudevent/client_unit_test.go +++ b/pkg/cloudevent/client_unit_test.go @@ -3,9 +3,10 @@ package cloudevent_test import ( "testing" - "github.com/kyma-project/eventing-manager/pkg/cloudevent" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/kyma-project/eventing-manager/pkg/cloudevent" ) func Test_NewHTTP(t *testing.T) { diff --git a/pkg/ems/auth/auth.go b/pkg/ems/auth/auth.go index 544a3588..e56ff3b4 100644 --- a/pkg/ems/auth/auth.go +++ b/pkg/ems/auth/auth.go @@ -15,7 +15,7 @@ func NewAuthenticatedClient(cfg env.Config) *http.Client { // create and configure oauth2 client client := config.Client(ctx) - var base = http.DefaultTransport.(*http.Transport).Clone() + base := http.DefaultTransport.(*http.Transport).Clone() client.Transport.(*oauth2.Transport).Base = base // TODO: Support tracing in eventing-controller #9767: https://github.com/kyma-project/kyma/issues/9767 diff --git a/pkg/ems/auth/auth_unit_test.go b/pkg/ems/auth/auth_unit_test.go index 7cc3ebec..ea068ad4 100644 --- a/pkg/ems/auth/auth_unit_test.go +++ b/pkg/ems/auth/auth_unit_test.go @@ -4,9 +4,9 @@ import ( "net/http" "testing" - "github.com/kyma-project/eventing-manager/pkg/env" - "golang.org/x/oauth2" + + "github.com/kyma-project/eventing-manager/pkg/env" ) const ( diff --git a/pkg/env/backend_config.go b/pkg/env/backend_config.go index 30985c22..6eedcc04 100644 --- a/pkg/env/backend_config.go +++ b/pkg/env/backend_config.go @@ -12,40 +12,40 @@ type BackendConfig struct { PublisherConfig PublisherConfig // namespace where eventing-manager is deployed. - Namespace string `envconfig:"NAMESPACE" default:"kyma-system"` - EventingCRName string `envconfig:"EVENTING_CR_NAME" default:"eventing"` - EventingCRNamespace string `envconfig:"EVENTING_CR_NAMESPACE" default:"kyma-system"` + Namespace string `default:"kyma-system" envconfig:"NAMESPACE"` + EventingCRName string `default:"eventing" envconfig:"EVENTING_CR_NAME"` + EventingCRNamespace string `default:"kyma-system" envconfig:"EVENTING_CR_NAMESPACE"` - WebhookSecretName string `envconfig:"WEBHOOK_SECRET_NAME" default:"eventing-manager-webhook-server-cert"` - MutatingWebhookName string `envconfig:"MUTATING_WEBHOOK_NAME" default:"subscription-mutating-webhook-configuration"` + WebhookSecretName string `default:"eventing-manager-webhook-server-cert" envconfig:"WEBHOOK_SECRET_NAME"` + MutatingWebhookName string `default:"subscription-mutating-webhook-configuration" envconfig:"MUTATING_WEBHOOK_NAME"` //nolint:lll - ValidatingWebhookName string `envconfig:"VALIDATING_WEBHOOK_NAME" default:"subscription-validating-webhook-configuration"` + ValidatingWebhookName string `default:"subscription-validating-webhook-configuration" envconfig:"VALIDATING_WEBHOOK_NAME"` DefaultSubscriptionConfig DefaultSubscriptionConfig //nolint:lll - EventingWebhookAuthSecretName string `envconfig:"EVENTING_WEBHOOK_AUTH_SECRET_NAME" required:"true" default:"eventing-webhook-auth"` + EventingWebhookAuthSecretName string `default:"eventing-webhook-auth" envconfig:"EVENTING_WEBHOOK_AUTH_SECRET_NAME" required:"true"` //nolint:lll - EventingWebhookAuthSecretNamespace string `envconfig:"EVENTING_WEBHOOK_AUTH_SECRET_NAMESPACE" required:"true" default:"kyma-system"` + EventingWebhookAuthSecretNamespace string `default:"kyma-system" envconfig:"EVENTING_WEBHOOK_AUTH_SECRET_NAMESPACE" required:"true"` } type PublisherConfig struct { - Image string `envconfig:"PUBLISHER_IMAGE" default:"eu.gcr.io/kyma-project/event-publisher-proxy:c06eb4fc"` - ImagePullPolicy string `envconfig:"PUBLISHER_IMAGE_PULL_POLICY" default:"IfNotPresent"` - PortNum int `envconfig:"PUBLISHER_PORT_NUM" default:"8080"` - MetricsPortNum int `envconfig:"PUBLISHER_METRICS_PORT_NUM" default:"8080"` - ServiceAccount string `envconfig:"PUBLISHER_SERVICE_ACCOUNT" default:"eventing-publisher-proxy"` - RequestTimeout string `envconfig:"PUBLISHER_REQUEST_TIMEOUT" default:"5s"` - PriorityClassName string `envconfig:"PUBLISHER_PRIORITY_CLASS_NAME" default:""` + Image string `default:"eu.gcr.io/kyma-project/event-publisher-proxy:c06eb4fc" envconfig:"PUBLISHER_IMAGE"` + ImagePullPolicy string `default:"IfNotPresent" envconfig:"PUBLISHER_IMAGE_PULL_POLICY"` + PortNum int `default:"8080" envconfig:"PUBLISHER_PORT_NUM"` + MetricsPortNum int `default:"8080" envconfig:"PUBLISHER_METRICS_PORT_NUM"` + ServiceAccount string `default:"eventing-publisher-proxy" envconfig:"PUBLISHER_SERVICE_ACCOUNT"` + RequestTimeout string `default:"5s" envconfig:"PUBLISHER_REQUEST_TIMEOUT"` + PriorityClassName string `default:"" envconfig:"PUBLISHER_PRIORITY_CLASS_NAME"` // publisher takes the controller values - AppLogFormat string `envconfig:"APP_LOG_FORMAT" default:"json"` + AppLogFormat string `default:"json" envconfig:"APP_LOG_FORMAT"` ApplicationCRDEnabled bool } type DefaultSubscriptionConfig struct { - MaxInFlightMessages int `envconfig:"DEFAULT_MAX_IN_FLIGHT_MESSAGES" default:"10"` - DispatcherRetryPeriod time.Duration `envconfig:"DEFAULT_DISPATCHER_RETRY_PERIOD" default:"5m"` - DispatcherMaxRetries int `envconfig:"DEFAULT_DISPATCHER_MAX_RETRIES" default:"10"` + MaxInFlightMessages int `default:"10" envconfig:"DEFAULT_MAX_IN_FLIGHT_MESSAGES"` + DispatcherRetryPeriod time.Duration `default:"5m" envconfig:"DEFAULT_DISPATCHER_RETRY_PERIOD"` + DispatcherMaxRetries int `default:"10" envconfig:"DEFAULT_DISPATCHER_MAX_RETRIES"` } func GetBackendConfig() BackendConfig { diff --git a/pkg/env/config.go b/pkg/env/config.go index f2252f52..d4eabf1f 100644 --- a/pkg/env/config.go +++ b/pkg/env/config.go @@ -35,31 +35,31 @@ func Backend() (string, error) { // Config represents the environment config for the Eventing Controller. type Config struct { // Following details are for eventing-controller to communicate to BEB - BEBAPIURL string `envconfig:"BEB_API_URL" default:"https://enterprise-messaging-pubsub.cfapps.sap.hana.ondemand.com/sap/ems/v1"` - ClientID string `envconfig:"CLIENT_ID" default:"client-id"` - ClientSecret string `envconfig:"CLIENT_SECRET" default:"client-secret"` - TokenEndpoint string `envconfig:"TOKEN_ENDPOINT" default:"token-endpoint"` + BEBAPIURL string `default:"https://enterprise-messaging-pubsub.cfapps.sap.hana.ondemand.com/sap/ems/v1" envconfig:"BEB_API_URL"` + ClientID string `default:"client-id" envconfig:"CLIENT_ID"` + ClientSecret string `default:"client-secret" envconfig:"CLIENT_SECRET"` + TokenEndpoint string `default:"token-endpoint" envconfig:"TOKEN_ENDPOINT"` // Following details are for BEB to communicate to Kyma - WebhookActivationTimeout time.Duration `envconfig:"WEBHOOK_ACTIVATION_TIMEOUT" default:"60s"` + WebhookActivationTimeout time.Duration `default:"60s" envconfig:"WEBHOOK_ACTIVATION_TIMEOUT"` // Default protocol setting for BEB - ExemptHandshake bool `envconfig:"EXEMPT_HANDSHAKE" default:"true"` - Qos string `envconfig:"QOS" default:"AT_LEAST_ONCE"` - ContentMode string `envconfig:"CONTENT_MODE" default:""` + ExemptHandshake bool `default:"true" envconfig:"EXEMPT_HANDSHAKE"` + Qos string `default:"AT_LEAST_ONCE" envconfig:"QOS"` + ContentMode string `default:"" envconfig:"CONTENT_MODE"` // Default namespace for BEB - BEBNamespace string `envconfig:"BEB_NAMESPACE" default:"ns"` + BEBNamespace string `default:"ns" envconfig:"BEB_NAMESPACE"` // EventTypePrefix prefix for the EventType // note: eventType format is ... EventTypePrefix string `envconfig:"EVENT_TYPE_PREFIX" required:"true"` // EventingWebhookAuthEnabled enable/disable the Eventing webhook auth feature flag. - EventingWebhookAuthEnabled bool `envconfig:"EVENTING_WEBHOOK_AUTH_ENABLED" required:"false" default:"false"` + EventingWebhookAuthEnabled bool `default:"false" envconfig:"EVENTING_WEBHOOK_AUTH_ENABLED" required:"false"` // NATSProvisioningEnabled enable/disable the NATS resources provisioning feature flag. - NATSProvisioningEnabled bool `envconfig:"NATS_PROVISIONING_ENABLED" required:"false" default:"true"` + NATSProvisioningEnabled bool `default:"true" envconfig:"NATS_PROVISIONING_ENABLED" required:"false"` } func GetConfig() Config { diff --git a/pkg/env/nats_config.go b/pkg/env/nats_config.go index 4029cf6f..d1a6d6dd 100644 --- a/pkg/env/nats_config.go +++ b/pkg/env/nats_config.go @@ -4,9 +4,9 @@ import ( "strings" "time" - "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - "github.com/kelseyhightower/envconfig" + + "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" ) // NATSConfig represents the environment config for the Eventing Controller with Nats. @@ -21,14 +21,14 @@ type NATSConfig struct { EventTypePrefix string // HTTP Transport config for the message dispatcher - MaxIdleConns int `envconfig:"MAX_IDLE_CONNS" default:"50"` - MaxConnsPerHost int `envconfig:"MAX_CONNS_PER_HOST" default:"50"` - MaxIdleConnsPerHost int `envconfig:"MAX_IDLE_CONNS_PER_HOST" default:"50"` - IdleConnTimeout time.Duration `envconfig:"IDLE_CONN_TIMEOUT" default:"10s"` + MaxIdleConns int `default:"50" envconfig:"MAX_IDLE_CONNS"` + MaxConnsPerHost int `default:"50" envconfig:"MAX_CONNS_PER_HOST"` + MaxIdleConnsPerHost int `default:"50" envconfig:"MAX_IDLE_CONNS_PER_HOST"` + IdleConnTimeout time.Duration `default:"10s" envconfig:"IDLE_CONN_TIMEOUT"` // JetStream-specific configs // Name of the JetStream stream where all events are stored. - JSStreamName string `envconfig:"JS_STREAM_NAME" default:"sap"` + JSStreamName string `default:"sap" envconfig:"JS_STREAM_NAME"` // Prefix for the subjects in the stream. JSSubjectPrefix string `envconfig:"JS_STREAM_SUBJECT_PREFIX"` // Storage type of the stream, memory or file. @@ -39,14 +39,14 @@ type NATSConfig struct { // interest: when all known observables have acknowledged a message, it can be removed. // limits: messages are retained until any given limit is reached. // configured via JSStreamMaxMessages and JSStreamMaxBytes. - JSStreamRetentionPolicy string `envconfig:"JS_STREAM_RETENTION_POLICY" default:"interest"` - JSStreamMaxMessages int64 `envconfig:"JS_STREAM_MAX_MSGS" default:"-1"` + JSStreamRetentionPolicy string `default:"interest" envconfig:"JS_STREAM_RETENTION_POLICY"` + JSStreamMaxMessages int64 `default:"-1" envconfig:"JS_STREAM_MAX_MSGS"` JSStreamMaxBytes string JSStreamMaxMsgsPerTopic int64 // JSStreamDiscardPolicy specifies which events to discard from the stream in case limits are reached // new: reject new messages for the stream // old: discard old messages from the stream to make room for new messages - JSStreamDiscardPolicy string `envconfig:"JS_STREAM_DISCARD_POLICY" default:"new"` + JSStreamDiscardPolicy string `default:"new" envconfig:"JS_STREAM_DISCARD_POLICY"` // Deliver Policy determines for a consumer where in the stream it starts receiving messages // (more info https://docs.nats.io/nats-concepts/jetstream/consumers#deliverpolicy-optstartseq-optstarttime): // - all: The consumer starts receiving from the earliest available message. @@ -55,7 +55,7 @@ type NATSConfig struct { // currently in the stream. // - new: When first consuming messages, the consumer starts receiving messages that were created // after the consumer was created. - JSConsumerDeliverPolicy string `envconfig:"JS_CONSUMER_DELIVER_POLICY" default:"new"` + JSConsumerDeliverPolicy string `default:"new" envconfig:"JS_CONSUMER_DELIVER_POLICY"` } // GetNewNATSConfig returns NATSConfig with values based on Eventing CR. diff --git a/pkg/env/nats_config_test.go b/pkg/env/nats_config_test.go index aff40c31..1a6df157 100644 --- a/pkg/env/nats_config_test.go +++ b/pkg/env/nats_config_test.go @@ -7,12 +7,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/resource" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" - - "github.com/stretchr/testify/require" ) func Test_GetNewNATSConfig(t *testing.T) { @@ -96,7 +95,8 @@ func Test_GetNATSConfig(t *testing.T) { want NATSConfig wantErr bool }{ - {name: "Required values only gives valid config", + { + name: "Required values only gives valid config", args: args{ envs: map[string]string{ "NATS_URL": "natsurl", @@ -122,7 +122,8 @@ func Test_GetNATSConfig(t *testing.T) { }, wantErr: false, }, - {name: "Envs are mapped correctly", + { + name: "Envs are mapped correctly", args: args{ envs: map[string]string{ "JS_STREAM_NAME": "jsn", diff --git a/pkg/eventing/deployment.go b/pkg/eventing/deployment.go index 526b5ea2..ef6a2ad3 100644 --- a/pkg/eventing/deployment.go +++ b/pkg/eventing/deployment.go @@ -38,9 +38,7 @@ const ( PriorityClassName = "eventing-manager-priority-class" ) -var ( - TerminationGracePeriodSeconds = int64(30) -) +var TerminationGracePeriodSeconds = int64(30) func newNATSPublisherDeployment( eventing *v1alpha1.Eventing, @@ -184,6 +182,7 @@ func WithAffinity(publisherName string) DeployOpt { } } } + func WithContainers(publisherConfig env.PublisherConfig, eventing *v1alpha1.Eventing) DeployOpt { return func(d *kappsv1.Deployment) { d.Spec.Template.Spec.Containers = []kcorev1.Container{ @@ -215,7 +214,8 @@ func WithLogEnvVars(publisherConfig env.PublisherConfig, eventing *v1alpha1.Even } func WithNATSEnvVars(natsConfig env.NATSConfig, publisherConfig env.PublisherConfig, - eventing *v1alpha1.Eventing) DeployOpt { + eventing *v1alpha1.Eventing, +) DeployOpt { return func(d *kappsv1.Deployment) { for i, container := range d.Spec.Template.Spec.Containers { if strings.EqualFold(container.Name, GetPublisherDeploymentName(*eventing)) { @@ -226,7 +226,8 @@ func WithNATSEnvVars(natsConfig env.NATSConfig, publisherConfig env.PublisherCon } func getNATSEnvVars(natsConfig env.NATSConfig, publisherConfig env.PublisherConfig, - eventing *v1alpha1.Eventing) []kcorev1.EnvVar { + eventing *v1alpha1.Eventing, +) []kcorev1.EnvVar { return []kcorev1.EnvVar{ {Name: "BACKEND", Value: "nats"}, {Name: "PORT", Value: strconv.Itoa(int(publisherPortNum))}, @@ -328,7 +329,8 @@ func getResources(requestsCPU, requestsMemory, limitsCPU, limitsMemory string) k } func WithBEBEnvVars(publisherName string, publisherConfig env.PublisherConfig, - eventing *v1alpha1.Eventing) DeployOpt { + eventing *v1alpha1.Eventing, +) DeployOpt { return func(d *kappsv1.Deployment) { for i, container := range d.Spec.Template.Spec.Containers { if strings.EqualFold(container.Name, publisherName) { @@ -339,7 +341,8 @@ func WithBEBEnvVars(publisherName string, publisherConfig env.PublisherConfig, } func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConfig, - eventing *v1alpha1.Eventing) []kcorev1.EnvVar { + eventing *v1alpha1.Eventing, +) []kcorev1.EnvVar { return []kcorev1.EnvVar{ {Name: "BACKEND", Value: "beb"}, {Name: "PORT", Value: strconv.Itoa(int(publisherPortNum))}, @@ -352,7 +355,8 @@ func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConf SecretKeyRef: &kcorev1.SecretKeySelector{ LocalObjectReference: kcorev1.LocalObjectReference{Name: publisherName}, Key: PublisherSecretClientIDKey, - }}, + }, + }, }, { Name: "CLIENT_SECRET", @@ -360,7 +364,8 @@ func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConf SecretKeyRef: &kcorev1.SecretKeySelector{ LocalObjectReference: kcorev1.LocalObjectReference{Name: publisherName}, Key: PublisherSecretClientSecretKey, - }}, + }, + }, }, { Name: "TOKEN_ENDPOINT", @@ -368,7 +373,8 @@ func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConf SecretKeyRef: &kcorev1.SecretKeySelector{ LocalObjectReference: kcorev1.LocalObjectReference{Name: publisherName}, Key: PublisherSecretTokenEndpointKey, - }}, + }, + }, }, { Name: "EMS_PUBLISH_URL", @@ -376,7 +382,8 @@ func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConf SecretKeyRef: &kcorev1.SecretKeySelector{ LocalObjectReference: kcorev1.LocalObjectReference{Name: publisherName}, Key: PublisherSecretEMSURLKey, - }}, + }, + }, }, { Name: "BEB_NAMESPACE_VALUE", @@ -384,7 +391,8 @@ func getEventMeshEnvVars(publisherName string, publisherConfig env.PublisherConf SecretKeyRef: &kcorev1.SecretKeySelector{ LocalObjectReference: kcorev1.LocalObjectReference{Name: publisherName}, Key: PublisherSecretBEBNamespaceKey, - }}, + }, + }, }, { Name: "BEB_NAMESPACE", diff --git a/pkg/eventing/deployment_test.go b/pkg/eventing/deployment_test.go index 90447d13..421eea39 100644 --- a/pkg/eventing/deployment_test.go +++ b/pkg/eventing/deployment_test.go @@ -5,12 +5,11 @@ import ( "strings" "testing" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" kappsv1 "k8s.io/api/apps/v1" kcorev1 "k8s.io/api/core/v1" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/internal/label" @@ -59,7 +58,7 @@ func TestNewDeployment(t *testing.T) { var natsConfig env.NATSConfig switch tc.givenBackendType { - case "NATS": + case v1alpha1.NatsBackendType: natsConfig = env.NATSConfig{ JSStreamName: "kyma", URL: natsURL, @@ -69,7 +68,7 @@ func TestNewDeployment(t *testing.T) { testutils.WithEventingCRNamespace(publisherNamespace), testutils.WithEventingEventTypePrefix(eventTypePrefix), ), natsConfig, publisherConfig) - case "EventMesh": + case v1alpha1.EventMeshBackendType: deployment = newEventMeshPublisherDeployment(testutils.NewEventingCR( testutils.WithEventingCRName(tc.givenPublisherName), testutils.WithEventingCRNamespace(publisherNamespace), @@ -176,6 +175,7 @@ func Test_GetNATSEnvVars(t *testing.T) { }) } } + func Test_GetLogEnvVars(t *testing.T) { testCases := []struct { name string diff --git a/pkg/eventing/manager.go b/pkg/eventing/manager.go index d31c57fa..fde4d4e4 100644 --- a/pkg/eventing/manager.go +++ b/pkg/eventing/manager.go @@ -11,7 +11,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/k8s" @@ -24,13 +23,11 @@ const ( memoryUtilization = 60 ) -var ( - // allowedAnnotations are the publisher proxy deployment spec template annotations - // which should be preserved during reconciliation. - allowedAnnotations = map[string]string{ - "kubectl.kubernetes.io/restartedAt": "", - } -) +// allowedAnnotations are the publisher proxy deployment spec template annotations +// which should be preserved during reconciliation. +var allowedAnnotations = map[string]string{ + "kubectl.kubernetes.io/restartedAt": "", +} //go:generate go run github.com/vektra/mockery/v2 --name=Manager --outpkg=mocks --case=underscore type Manager interface { @@ -78,7 +75,8 @@ func (em EventingManager) DeployPublisherProxy( ctx context.Context, eventing *v1alpha1.Eventing, natsConfig *env.NATSConfig, - backendType v1alpha1.BackendType) (*kappsv1.Deployment, error) { + backendType v1alpha1.BackendType, +) (*kappsv1.Deployment, error) { // update EC reconciler NATS and public config from the data in the eventing CR deployment, err := em.applyPublisherProxyDeployment(ctx, eventing, natsConfig, backendType) if err != nil { @@ -91,7 +89,8 @@ func (em *EventingManager) applyPublisherProxyDeployment( ctx context.Context, eventing *v1alpha1.Eventing, natsConfig *env.NATSConfig, - backendType v1alpha1.BackendType) (*kappsv1.Deployment, error) { + backendType v1alpha1.BackendType, +) (*kappsv1.Deployment, error) { var desiredPublisher *kappsv1.Deployment switch backendType { @@ -144,7 +143,8 @@ func (em *EventingManager) applyPublisherProxyDeployment( func (em *EventingManager) migratePublisherDeploymentFromEC( ctx context.Context, eventing *v1alpha1.Eventing, - currentPublisher kappsv1.Deployment, desiredPublisher kappsv1.Deployment) error { + currentPublisher kappsv1.Deployment, desiredPublisher kappsv1.Deployment, +) error { // If Eventing CR is already owner of deployment, then it means that the publisher deployment // was already migrated. if len(currentPublisher.OwnerReferences) == 1 && currentPublisher.OwnerReferences[0].Name == eventing.Name { @@ -190,7 +190,8 @@ func (em *EventingManager) SetBackendConfig(config env.BackendConfig) { func (em EventingManager) DeployPublisherProxyResources( ctx context.Context, eventing *v1alpha1.Eventing, - publisherDeployment *kappsv1.Deployment) error { + publisherDeployment *kappsv1.Deployment, +) error { // define list of resources to create for EPP. resources := []client.Object{ // ServiceAccount @@ -216,7 +217,6 @@ func (em EventingManager) DeployPublisherProxyResources( // create the resources on k8s. for _, obj := range resources { - // add owner reference. if err := controllerutil.SetControllerReference(eventing, obj, em.Scheme()); err != nil { return err diff --git a/pkg/eventing/manager_test.go b/pkg/eventing/manager_test.go index e7113847..aefe0ad7 100644 --- a/pkg/eventing/manager_test.go +++ b/pkg/eventing/manager_test.go @@ -6,29 +6,23 @@ import ( "fmt" "testing" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/utils/ptr" - - "github.com/kyma-project/eventing-manager/test" - - "sigs.k8s.io/controller-runtime/pkg/client" - - "k8s.io/apimachinery/pkg/runtime" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" kappsv1 "k8s.io/api/apps/v1" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/pkg/env" k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" + "github.com/kyma-project/eventing-manager/test" testutils "github.com/kyma-project/eventing-manager/test/utils" ) @@ -319,7 +313,6 @@ func Test_IsNATSAvailable(t *testing.T) { require.Equal(t, tc.wantErr, err) }) } - } func Test_ConvertECBackendType(t *testing.T) { diff --git a/pkg/eventing/utils.go b/pkg/eventing/utils.go index db56cd03..4d8a347f 100644 --- a/pkg/eventing/utils.go +++ b/pkg/eventing/utils.go @@ -43,7 +43,8 @@ func GetPublisherClusterRoleBindingName(eventing v1alpha1.Eventing) string { } func newHorizontalPodAutoscaler(name, namespace string, min, max, cpuUtilization, memoryUtilization int32, - labels map[string]string) *kautoscalingv2.HorizontalPodAutoscaler { + labels map[string]string, +) *kautoscalingv2.HorizontalPodAutoscaler { return &kautoscalingv2.HorizontalPodAutoscaler{ TypeMeta: kmetav1.TypeMeta{ Kind: "HorizontalPodAutoscaler", @@ -158,7 +159,8 @@ func newPublisherProxyClusterRoleBinding(name, namespace string, labels map[stri } func newPublisherProxyService(name, namespace string, labels map[string]string, - selectorLabels map[string]string) *kcorev1.Service { + selectorLabels map[string]string, +) *kcorev1.Service { // setting `TypeMeta` is important for patch apply to work. return &kcorev1.Service{ TypeMeta: kmetav1.TypeMeta{ @@ -185,7 +187,8 @@ func newPublisherProxyService(name, namespace string, labels map[string]string, } func newPublisherProxyMetricsService(name, namespace string, labels map[string]string, - selectorLabels map[string]string) *kcorev1.Service { + selectorLabels map[string]string, +) *kcorev1.Service { // setting `TypeMeta` is important for patch apply to work. return &kcorev1.Service{ TypeMeta: kmetav1.TypeMeta{ @@ -217,7 +220,8 @@ func newPublisherProxyMetricsService(name, namespace string, labels map[string]s } func newPublisherProxyHealthService(name, namespace string, labels map[string]string, - selectorLabels map[string]string) *kcorev1.Service { + selectorLabels map[string]string, +) *kcorev1.Service { // setting `TypeMeta` is important for patch apply to work. return &kcorev1.Service{ TypeMeta: kmetav1.TypeMeta{ diff --git a/pkg/istio/peerauthentication/peerauthentication.go b/pkg/istio/peerauthentication/peerauthentication.go index 38c7a9ee..4343b311 100644 --- a/pkg/istio/peerauthentication/peerauthentication.go +++ b/pkg/istio/peerauthentication/peerauthentication.go @@ -3,15 +3,14 @@ package peerauthentication import ( "context" - "go.uber.org/zap" - "k8s.io/utils/ptr" - "github.com/pkg/errors" + "go.uber.org/zap" istiosecurityv1beta1 "istio.io/api/security/v1beta1" istiotypev1beta1 "istio.io/api/type/v1beta1" istiopkgsecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1" kappsv1 "k8s.io/api/apps/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" "github.com/kyma-project/eventing-manager/pkg/k8s" ) diff --git a/pkg/istio/peerauthentication/peerauthentication_test.go b/pkg/istio/peerauthentication/peerauthentication_test.go index 32528c9a..ba0ecdf7 100644 --- a/pkg/istio/peerauthentication/peerauthentication_test.go +++ b/pkg/istio/peerauthentication/peerauthentication_test.go @@ -4,12 +4,13 @@ import ( "context" "testing" - k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" - "github.com/kyma-project/eventing-manager/test" - testutils "github.com/kyma-project/eventing-manager/test/utils" "github.com/pkg/errors" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + + k8smocks "github.com/kyma-project/eventing-manager/pkg/k8s/mocks" + "github.com/kyma-project/eventing-manager/test" + testutils "github.com/kyma-project/eventing-manager/test/utils" ) func Test_SyncPeerAuthentications(t *testing.T) { diff --git a/pkg/k8s/client.go b/pkg/k8s/client.go index 6522de03..6d39e4f9 100644 --- a/pkg/k8s/client.go +++ b/pkg/k8s/client.go @@ -5,6 +5,7 @@ import ( "errors" "strings" + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" istiopkgsecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1" kadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" kappsv1 "k8s.io/api/apps/v1" @@ -20,8 +21,6 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) @@ -31,6 +30,7 @@ var NatsGVK = schema.GroupVersionResource{ Resource: "nats", } +//nolint:interfacebloat // FIXME //go:generate go run github.com/vektra/mockery/v2 --name=Client --outpkg=mocks --case=underscore type Client interface { GetDeployment(ctx context.Context, name, namespace string) (*kappsv1.Deployment, error) @@ -63,7 +63,8 @@ type KubeClient struct { } func NewKubeClient(client client.Client, clientset kapixclientset.Interface, fieldManager string, - dynamicClient dynamic.Interface) Client { + dynamicClient dynamic.Interface, +) Client { return &KubeClient{ client: client, clientset: clientset, @@ -236,7 +237,8 @@ func (c *KubeClient) APIRuleCRDExists(ctx context.Context) (bool, error) { // GetMutatingWebHookConfiguration returns the MutatingWebhookConfiguration k8s resource. func (c *KubeClient) GetMutatingWebHookConfiguration(ctx context.Context, - name string) (*kadmissionregistrationv1.MutatingWebhookConfiguration, error) { + name string, +) (*kadmissionregistrationv1.MutatingWebhookConfiguration, error) { var mutatingWH kadmissionregistrationv1.MutatingWebhookConfiguration mutatingWHKey := client.ObjectKey{ Name: name, @@ -250,7 +252,8 @@ func (c *KubeClient) GetMutatingWebHookConfiguration(ctx context.Context, // GetValidatingWebHookConfiguration returns the ValidatingWebhookConfiguration k8s resource. func (c *KubeClient) GetValidatingWebHookConfiguration(ctx context.Context, - name string) (*kadmissionregistrationv1.ValidatingWebhookConfiguration, error) { + name string, +) (*kadmissionregistrationv1.ValidatingWebhookConfiguration, error) { var validatingWH kadmissionregistrationv1.ValidatingWebhookConfiguration validatingWHKey := client.ObjectKey{ Name: name, diff --git a/pkg/k8s/client_test.go b/pkg/k8s/client_test.go index fcc66dd7..99269c55 100644 --- a/pkg/k8s/client_test.go +++ b/pkg/k8s/client_test.go @@ -6,27 +6,23 @@ import ( "errors" "testing" + "github.com/stretchr/testify/require" istiopkgsecurityv1beta1 "istio.io/client-go/pkg/apis/security/v1beta1" - "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme" - - "k8s.io/apimachinery/pkg/runtime" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - - testutils "github.com/kyma-project/eventing-manager/test/utils" - kadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" - kapixclientsetfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" - - "github.com/stretchr/testify/require" kappsv1 "k8s.io/api/apps/v1" kcorev1 "k8s.io/api/core/v1" krbacv1 "k8s.io/api/rbac/v1" + kapixclientsetfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" + "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme" kerrors "k8s.io/apimachinery/pkg/api/errors" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + testutils "github.com/kyma-project/eventing-manager/test/utils" ) const testFieldManager = "eventing-manager" diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index 70f03b6a..3064cefb 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -3,8 +3,9 @@ package logger_test import ( "testing" - "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/stretchr/testify/assert" + + "github.com/kyma-project/eventing-manager/pkg/logger" ) func Test_Build(t *testing.T) { diff --git a/pkg/object/apirule.go b/pkg/object/apirule.go index eee40900..d1440b1f 100644 --- a/pkg/object/apirule.go +++ b/pkg/object/apirule.go @@ -4,11 +4,10 @@ import ( "fmt" "net/url" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/featureflags" ) @@ -122,7 +121,8 @@ func WithOwnerReference(subs []eventingv1alpha2.Subscription) Option { // WithRules sets the rules of an APIRule for all Subscriptions for a subscriber. func WithRules(certsURL string, subs []eventingv1alpha2.Subscription, svc apigatewayv1beta1.Service, - methods ...string) Option { + methods ...string, +) Option { return func(r *apigatewayv1beta1.APIRule) { var handler apigatewayv1beta1.Handler if featureflags.IsEventingWebhookAuthEnabled() { diff --git a/pkg/object/apirule_test.go b/pkg/object/apirule_test.go index 5f2f0100..e2435ec4 100644 --- a/pkg/object/apirule_test.go +++ b/pkg/object/apirule_test.go @@ -5,7 +5,7 @@ import ( "reflect" "testing" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/stretchr/testify/require" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" diff --git a/pkg/object/equality.go b/pkg/object/equality.go index 83db79cb..01fff25d 100644 --- a/pkg/object/equality.go +++ b/pkg/object/equality.go @@ -3,6 +3,7 @@ package object import ( "reflect" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kappsv1 "k8s.io/api/apps/v1" kautoscalingv2 "k8s.io/api/autoscaling/v2" kcorev1 "k8s.io/api/core/v1" @@ -10,8 +11,6 @@ import ( kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/conversion" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) diff --git a/pkg/object/equality_test.go b/pkg/object/equality_test.go index 87957f31..c2a7411b 100644 --- a/pkg/object/equality_test.go +++ b/pkg/object/equality_test.go @@ -4,8 +4,7 @@ import ( "net/http" "testing" - "k8s.io/apimachinery/pkg/util/intstr" - + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/stretchr/testify/require" kautoscalingv2 "k8s.io/api/autoscaling/v2" kcorev1 "k8s.io/api/core/v1" @@ -13,10 +12,9 @@ import ( "k8s.io/apimachinery/pkg/api/resource" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) @@ -255,7 +253,7 @@ func Test_isSubscriptionStatusEqual(t *testing.T) { } } -//func TestPublisherProxyDeploymentEqual(t *testing.T) { +// func TestPublisherProxyDeploymentEqual(t *testing.T) { // publisherCfg := env.PublisherConfig{ // Image: "publisher", // PortNum: 0, @@ -2113,9 +2111,7 @@ func Test_envEqual(t *testing.T) { } func Test_probeEqual(t *testing.T) { - var ( - probe = &kcorev1.Probe{} - ) + probe := &kcorev1.Probe{} type args struct { p1 *kcorev1.Probe diff --git a/pkg/object/object.go b/pkg/object/object.go index 7e6ce5af..f875f886 100644 --- a/pkg/object/object.go +++ b/pkg/object/object.go @@ -1,7 +1,7 @@ package object import ( - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" ) // Option is a functional option for API objects builders. diff --git a/pkg/subscriptionmanager/eventmesh/eventmesh.go b/pkg/subscriptionmanager/eventmesh/eventmesh.go index 7126c304..b766056a 100644 --- a/pkg/subscriptionmanager/eventmesh/eventmesh.go +++ b/pkg/subscriptionmanager/eventmesh/eventmesh.go @@ -6,15 +6,7 @@ import ( "strings" "time" - "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" - - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - "github.com/kyma-project/eventing-manager/pkg/backend/metrics" - - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" "github.com/pkg/errors" "go.uber.org/zap" "golang.org/x/xerrors" @@ -28,8 +20,12 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" + "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" + "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/backend/sink" backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" "github.com/kyma-project/eventing-manager/pkg/env" @@ -80,7 +76,8 @@ type SubscriptionManager struct { // NewSubscriptionManager creates the SubscriptionManager for BEB and initializes it as far as it // does not depend on non-common options. func NewSubscriptionManager(restCfg *rest.Config, metricsAddr string, resyncPeriod time.Duration, logger *logger.Logger, - collector *metrics.Collector, domain string) *SubscriptionManager { + collector *metrics.Collector, domain string, +) *SubscriptionManager { return &SubscriptionManager{ envCfg: env.GetConfig(), restCfg: restCfg, diff --git a/pkg/subscriptionmanager/eventmesh/eventmesh_test.go b/pkg/subscriptionmanager/eventmesh/eventmesh_test.go index 02dccb41..89c5fa07 100644 --- a/pkg/subscriptionmanager/eventmesh/eventmesh_test.go +++ b/pkg/subscriptionmanager/eventmesh/eventmesh_test.go @@ -6,25 +6,21 @@ import ( "net/http" "testing" + kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/stretchr/testify/require" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic" "sigs.k8s.io/controller-runtime/pkg/manager" - "github.com/kyma-project/eventing-manager/pkg/backend/utils" - submgrmanager "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" - - kymalogger "github.com/kyma-project/kyma/common/logging/logger" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" + "github.com/kyma-project/eventing-manager/pkg/backend/utils" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/client" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" + submgrmanager "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" eventingtesting "github.com/kyma-project/eventing-manager/testing" ) @@ -68,7 +64,6 @@ func Test_cleanupEventMesh(t *testing.T) { // start BEB Mock bebMock := startBEBMock() envConf := env.Config{ - BEBAPIURL: bebMock.MessagingURL, ClientID: "client-id", ClientSecret: "client-secret", diff --git a/pkg/subscriptionmanager/factory.go b/pkg/subscriptionmanager/factory.go index b3b3647f..93a420f0 100644 --- a/pkg/subscriptionmanager/factory.go +++ b/pkg/subscriptionmanager/factory.go @@ -3,16 +3,15 @@ package subscriptionmanager import ( "time" - "github.com/kyma-project/eventing-manager/pkg/backend/metrics" - "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" - "k8s.io/client-go/rest" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/eventmesh" "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/jetstream" + "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" ) // Perform a compile-time check. @@ -37,7 +36,8 @@ func NewFactory( metricsAddress string, metricsCollector *metrics.Collector, resyncPeriod time.Duration, - logger *logger.Logger) *Factory { + logger *logger.Logger, +) *Factory { return &Factory{ k8sRestCfg: k8sRestCfg, metricsAddress: metricsAddress, diff --git a/pkg/subscriptionmanager/jetstream/jetstream.go b/pkg/subscriptionmanager/jetstream/jetstream.go index 8b9c3ca6..f064ac65 100644 --- a/pkg/subscriptionmanager/jetstream/jetstream.go +++ b/pkg/subscriptionmanager/jetstream/jetstream.go @@ -4,36 +4,30 @@ import ( "context" "fmt" - subscriptioncontrollerjetstream "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/jetstream" - - submgrmanager "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" - - "github.com/kyma-project/eventing-manager/pkg/backend/sink" - backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" - - "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - - "golang.org/x/xerrors" - "github.com/pkg/errors" "go.uber.org/zap" + "golang.org/x/xerrors" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" - kkubernetesscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/manager" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" + subscriptioncontrollerjetstream "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/jetstream" + "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" backendjetstream "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" backendmetrics "github.com/kyma-project/eventing-manager/pkg/backend/metrics" + "github.com/kyma-project/eventing-manager/pkg/backend/sink" + backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/logger" + submgrmanager "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" ) const ( @@ -72,7 +66,8 @@ type SubscriptionManager struct { // NewSubscriptionManager creates the subscription manager for JetStream. func NewSubscriptionManager(restCfg *rest.Config, natsConfig env.NATSConfig, metricsAddr string, - metricsCollector *backendmetrics.Collector, logger *logger.Logger) *SubscriptionManager { + metricsCollector *backendmetrics.Collector, logger *logger.Logger, +) *SubscriptionManager { return &SubscriptionManager{ envCfg: natsConfig, restCfg: restCfg, diff --git a/pkg/subscriptionmanager/jetstream/jetstream_test.go b/pkg/subscriptionmanager/jetstream/jetstream_test.go index 79ea4186..0edf6eb6 100644 --- a/pkg/subscriptionmanager/jetstream/jetstream_test.go +++ b/pkg/subscriptionmanager/jetstream/jetstream_test.go @@ -6,14 +6,13 @@ import ( "testing" "time" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - kymalogger "github.com/kyma-project/kyma/common/logging/logger" "github.com/nats-io/nats-server/v2/server" "github.com/nats-io/nats.go" "github.com/stretchr/testify/require" "k8s.io/client-go/dynamic" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" @@ -81,7 +80,8 @@ func getNATSConf(natsURL string, natsPort int) env.NATSConfig { } func createAndSyncSubscription(t *testing.T, sinkURL string, - jsBackend *jetstream.JetStream) *eventingv1alpha2.Subscription { + jsBackend *jetstream.JetStream, +) *eventingv1alpha2.Subscription { // create test subscription testSub := eventingtesting.NewSubscription( subscriptionName, subscriptionNamespace, diff --git a/pkg/tracing/tracing.go b/pkg/tracing/tracing.go index e026b63a..8cb0757c 100644 --- a/pkg/tracing/tracing.go +++ b/pkg/tracing/tracing.go @@ -5,9 +5,8 @@ import ( "fmt" "net/http" - cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" - ceevent "github.com/cloudevents/sdk-go/v2/event" + cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" ) const ( diff --git a/pkg/tracing/tracing_test.go b/pkg/tracing/tracing_test.go index b5c373a1..69c1471b 100644 --- a/pkg/tracing/tracing_test.go +++ b/pkg/tracing/tracing_test.go @@ -8,6 +8,7 @@ import ( ceevent "github.com/cloudevents/sdk-go/v2/event" cehttp "github.com/cloudevents/sdk-go/v2/protocol/http" + . "github.com/onsi/gomega" ) diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 892a7bd1..f1a09b40 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -7,12 +7,10 @@ import ( "strings" "time" - kcorev1 "k8s.io/api/core/v1" - cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/event" - "github.com/pkg/errors" + kcorev1 "k8s.io/api/core/v1" emerrors "github.com/kyma-project/eventing-manager/pkg/errors" ) @@ -78,6 +76,7 @@ func Int64Ptr(i int64) *int64 { func StringPtr(s string) *string { return &s } + func ProcMountTypePtr(p kcorev1.ProcMountType) *kcorev1.ProcMountType { return &p } diff --git a/test/utils.go b/test/utils.go index 97888edc..b2b7ba39 100644 --- a/test/utils.go +++ b/test/utils.go @@ -6,12 +6,12 @@ import ( "net" "time" - "github.com/kyma-project/eventing-manager/pkg/logger" - "go.uber.org/zap" "go.uber.org/zap/zapcore" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/kyma-project/eventing-manager/pkg/logger" ) const ( diff --git a/test/utils/integration/integration.go b/test/utils/integration/integration.go index 349d4649..f2fa5aad 100644 --- a/test/utils/integration/integration.go +++ b/test/utils/integration/integration.go @@ -4,37 +4,30 @@ import ( "bytes" "context" "crypto/rand" - "fmt" "log" "path/filepath" "strings" "testing" "time" - kapiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - - eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" - - "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager" - "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" - submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" - - kapixclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - - "github.com/stretchr/testify/mock" - - submgrmocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/mocks" - - kcorev1 "k8s.io/api/core/v1" - krbacv1 "k8s.io/api/rbac/v1" - - "github.com/kyma-project/eventing-manager/test" - "github.com/avast/retry-go/v3" "github.com/go-logr/zapr" + natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" + natstestutils "github.com/kyma-project/nats-manager/testutils" "github.com/onsi/gomega" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + kadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" + kappsv1 "k8s.io/api/apps/v1" + kautoscalingv1 "k8s.io/api/autoscaling/v1" + kcorev1 "k8s.io/api/core/v1" + krbacv1 "k8s.io/api/rbac/v1" + kapiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + kapixclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" + "k8s.io/apimachinery/pkg/api/errors" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" @@ -45,23 +38,19 @@ import ( "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" - natsv1alpha1 "github.com/kyma-project/nats-manager/api/v1alpha1" - natstestutils "github.com/kyma-project/nats-manager/testutils" - kadmissionregistrationv1 "k8s.io/api/admissionregistration/v1" - kappsv1 "k8s.io/api/apps/v1" - kautoscalingv1 "k8s.io/api/autoscaling/v1" - "k8s.io/apimachinery/pkg/api/errors" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" + eventingcontroller "github.com/kyma-project/eventing-manager/internal/controller/operator/eventing" "github.com/kyma-project/eventing-manager/options" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/eventing" "github.com/kyma-project/eventing-manager/pkg/k8s" "github.com/kyma-project/eventing-manager/pkg/logger" + "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager" + "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager" + submgrmanagermocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/manager/mocks" + submgrmocks "github.com/kyma-project/eventing-manager/pkg/subscriptionmanager/mocks" + "github.com/kyma-project/eventing-manager/test" testutils "github.com/kyma-project/eventing-manager/test/utils" ) @@ -366,7 +355,7 @@ func (env TestEnvironment) TearDown() error { // clean-up created resources err := env.DeleteSecretFromK8s(getTestBackendConfig().WebhookSecretName, getTestBackendConfig().Namespace) if err != nil { - fmt.Printf("couldn't clean the webhook secret: %s", err) + log.Printf("couldn't clean the webhook secret: %s", err) } // retry to stop the api-server @@ -383,7 +372,8 @@ func (env TestEnvironment) TearDown() error { // GetEventingAssert fetches Eventing from k8s and allows making assertions on it. func (env TestEnvironment) GetEventingAssert(g *gomega.GomegaWithT, - eventing *v1alpha1.Eventing) gomega.AsyncAssertion { + eventing *v1alpha1.Eventing, +) gomega.AsyncAssertion { return g.Eventually(func() *v1alpha1.Eventing { gotEventing, err := env.GetEventingFromK8s(eventing.Name, eventing.Namespace) if err != nil { @@ -769,7 +759,8 @@ func (env TestEnvironment) EnsureEPPClusterRoleBindingOwnerReferenceSet(t *testi } func (env TestEnvironment) EnsureEPPPublishServiceCorrect(t *testing.T, eppDeployment *kappsv1.Deployment, - eventingCR v1alpha1.Eventing) { + eventingCR v1alpha1.Eventing, +) { require.Eventually(t, func() bool { result, err := env.GetServiceFromK8s(eventing.GetPublisherPublishServiceName(eventingCR), eventingCR.Namespace) if err != nil { @@ -781,7 +772,8 @@ func (env TestEnvironment) EnsureEPPPublishServiceCorrect(t *testing.T, eppDeplo } func (env TestEnvironment) EnsureEPPMetricsServiceCorrect(t *testing.T, eppDeployment *kappsv1.Deployment, - eventingCR v1alpha1.Eventing) { + eventingCR v1alpha1.Eventing, +) { require.Eventually(t, func() bool { result, err := env.GetServiceFromK8s(eventing.GetPublisherMetricsServiceName(eventingCR), eventingCR.Namespace) if err != nil { @@ -793,7 +785,8 @@ func (env TestEnvironment) EnsureEPPMetricsServiceCorrect(t *testing.T, eppDeplo } func (env TestEnvironment) EnsureEPPHealthServiceCorrect(t *testing.T, eppDeployment *kappsv1.Deployment, - eventingCR v1alpha1.Eventing) { + eventingCR v1alpha1.Eventing, +) { require.Eventually(t, func() bool { result, err := env.GetServiceFromK8s(eventing.GetPublisherHealthServiceName(eventingCR), eventingCR.Namespace) if err != nil { @@ -955,7 +948,7 @@ func (env TestEnvironment) makeNATSCrReady(t *testing.T, nats *natsv1alpha1.NATS err := env.UpdateNATSStatus(nats) if err != nil { - env.Logger.WithContext().Errorw("failed to update NATS CR status", err) + env.Logger.WithContext().Errorw("failed to update NATS CR status", "error", err) return false } return true @@ -968,7 +961,7 @@ func (env TestEnvironment) makeNatsCrError(t *testing.T, nats *natsv1alpha1.NATS err := env.UpdateNATSStatus(nats) if err != nil { - env.Logger.WithContext().Errorw("failed to update NATS CR status", err) + env.Logger.WithContext().Errorw("failed to update NATS CR status", "error", err) return false } return true diff --git a/test/utils/utils.go b/test/utils/utils.go index fe93d0a1..53e0411a 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -8,21 +8,17 @@ import ( "reflect" "time" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - - kapiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - kappsv1 "k8s.io/api/apps/v1" + kcorev1 "k8s.io/api/core/v1" krbacv1 "k8s.io/api/rbac/v1" + kapiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/util/intstr" "sigs.k8s.io/controller-runtime/pkg/client" - kcorev1 "k8s.io/api/core/v1" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" ) diff --git a/testing/eventmesh_unit_test.go b/testing/eventmesh_unit_test.go index 819b1efa..90bacc04 100644 --- a/testing/eventmesh_unit_test.go +++ b/testing/eventmesh_unit_test.go @@ -4,9 +4,9 @@ import ( "net/url" "testing" - . "github.com/onsi/gomega" - eventingtesting "github.com/kyma-project/eventing-manager/testing" + + . "github.com/onsi/gomega" ) func Test_GetRestAPIObject(t *testing.T) { diff --git a/testing/eventmeshmock.go b/testing/eventmeshmock.go index 1a46058e..99146735 100644 --- a/testing/eventmeshmock.go +++ b/testing/eventmeshmock.go @@ -11,16 +11,17 @@ import ( "strings" "github.com/go-logr/logr" - . "github.com/onsi/ginkgo" //nolint:revive,stylecheck // using . import for convenience - . "github.com/onsi/gomega" //nolint:revive,stylecheck // using . import for convenience "golang.org/x/oauth2" kctrllog "sigs.k8s.io/controller-runtime/pkg/log" + "github.com/kyma-project/eventing-manager/pkg/ems/api/events/client" + emstypes "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + // gcp auth etc. _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/client" - emstypes "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + . "github.com/onsi/ginkgo" //nolint:revive,stylecheck // using . import for convenience + . "github.com/onsi/gomega" //nolint:revive,stylecheck // using . import for convenience ) const ( @@ -68,11 +69,13 @@ func NewEventMeshMockResponseOverride() *EventMeshMockResponseOverride { } } -type ResponseUpdateReq func(w http.ResponseWriter, key string, webhookAuth *emstypes.WebhookAuth) -type ResponseUpdateStateReq func(w http.ResponseWriter, key string, state emstypes.State) -type ResponseWithSub func(w http.ResponseWriter, subscription emstypes.Subscription) -type ResponseWithName func(w http.ResponseWriter, subscriptionName string) -type Response func(w http.ResponseWriter) +type ( + ResponseUpdateReq func(w http.ResponseWriter, key string, webhookAuth *emstypes.WebhookAuth) + ResponseUpdateStateReq func(w http.ResponseWriter, key string, state emstypes.State) + ResponseWithSub func(w http.ResponseWriter, subscription emstypes.Subscription) + ResponseWithName func(w http.ResponseWriter, subscriptionName string) + Response func(w http.ResponseWriter) +) func (m *EventMeshMock) Reset() { m.log.Info("Initializing requests") diff --git a/testing/matchers.go b/testing/matchers.go index 7d461218..03adb9ad 100644 --- a/testing/matchers.go +++ b/testing/matchers.go @@ -5,18 +5,18 @@ import ( "reflect" "strconv" - . "github.com/onsi/gomega" //nolint:revive,stylecheck // using . import for convenience - . "github.com/onsi/gomega/gstruct" //nolint:revive,stylecheck // using . import for convenience + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" gomegatypes "github.com/onsi/gomega/types" kcorev1 "k8s.io/api/core/v1" kruntime "k8s.io/apimachinery/pkg/runtime" ktypes "k8s.io/apimachinery/pkg/types" - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/constants" "github.com/kyma-project/eventing-manager/pkg/object" + + . "github.com/onsi/gomega" //nolint:revive,stylecheck // using . import for convenience + . "github.com/onsi/gomega/gstruct" //nolint:revive,stylecheck // using . import for convenience ) // @@ -176,6 +176,7 @@ func HaveSubscriptionReady() gomegatypes.GomegaMatcher { return s.Status.Ready }, BeTrue()) } + func HaveTypes(types []string) gomegatypes.GomegaMatcher { return WithTransform( func(s *eventingv1alpha2.Subscription) []string { diff --git a/testing/subscriber.go b/testing/subscriber.go index 9a61ddb4..1d5dde12 100644 --- a/testing/subscriber.go +++ b/testing/subscriber.go @@ -10,12 +10,11 @@ import ( "strconv" "time" + "github.com/avast/retry-go/v3" + "github.com/pkg/errors" "go.uber.org/atomic" "github.com/kyma-project/eventing-manager/testing/event/cehelper" - - "github.com/avast/retry-go/v3" - "github.com/pkg/errors" ) const ( diff --git a/testing/test_helpers.go b/testing/test_helpers.go index 46e16764..493abe84 100644 --- a/testing/test_helpers.go +++ b/testing/test_helpers.go @@ -5,22 +5,20 @@ import ( "net" "net/http" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/client-go/dynamic" - kdynamicfake "k8s.io/client-go/dynamic/fake" - - eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/object" - - apigatewayv1beta1 "github.com/kyma-incubator/api-gateway/api/v1beta1" + apigatewayv1beta1 "github.com/kyma-project/api-gateway/apis/gateway/v1beta1" kcorev1 "k8s.io/api/core/v1" kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kunstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" kruntime "k8s.io/apimachinery/pkg/runtime" kschema "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/client-go/dynamic" + kdynamicfake "k8s.io/client-go/dynamic/fake" eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" + "github.com/kyma-project/eventing-manager/pkg/object" "github.com/kyma-project/eventing-manager/pkg/utils" ) @@ -289,7 +287,8 @@ func SubscriptionControllerDefaultReadyCondition() eventingv1alpha1.Condition { } func SubscriptionControllerReadyConditionWith(ready kcorev1.ConditionStatus, - reason eventingv1alpha1.ConditionReason) eventingv1alpha1.Condition { + reason eventingv1alpha1.ConditionReason, +) eventingv1alpha1.Condition { return eventingv1alpha1.MakeCondition(eventingv1alpha1.ConditionControllerReady, reason, ready, "") } @@ -412,7 +411,8 @@ func NewSubscription(name, namespace string, opts ...SubscriptionOpt) *eventingv } func NewEventMeshSubscription(name, contentMode string, webhookURL string, events types.Events, - webhookAuth *types.WebhookAuth) *types.Subscription { + webhookAuth *types.WebhookAuth, +) *types.Subscription { return &types.Subscription{ Name: name, ContentMode: contentMode, @@ -466,16 +466,19 @@ func WithSink(sink string) SubscriptionOpt { sub.Spec.Sink = sink } } + func WithConditions(conditions []eventingv1alpha2.Condition) SubscriptionOpt { return func(sub *eventingv1alpha2.Subscription) { sub.Status.Conditions = conditions } } + func WithStatus(status bool) SubscriptionOpt { return func(sub *eventingv1alpha2.Subscription) { sub.Status.Ready = status } } + func WithFinalizers(finalizers []string) SubscriptionOpt { return func(sub *eventingv1alpha2.Subscription) { sub.ObjectMeta.Finalizers = finalizers