diff --git a/klt-cert-manager/main.go b/klt-cert-manager/main.go index 15b352c5778..814ca728e0b 100644 --- a/klt-cert-manager/main.go +++ b/klt-cert-manager/main.go @@ -36,7 +36,7 @@ func init() { } type envConfig struct { - KLTNamespace string `envconfig:"NAMESPACE" default:"keptn-lifecycle-toolkit-system"` + KeptnNamespace string `envconfig:"NAMESPACE" default:"keptn-lifecycle-toolkit-system"` KLTLabelSelectorKey string `envconfig:"LABEL_SELECTOR_KEY" default:"keptn.sh/inject-cert"` KLTLabelSelectorValue string `envconfig:"LABEL_SELECTOR_VALUE" default:"true"` } @@ -66,7 +66,7 @@ func main() { Scheme: scheme, Cache: cache.Options{ DefaultNamespaces: map[string]cache.Config{ - env.KLTNamespace: {}, + env.KeptnNamespace: {}, }, }, Metrics: metricsserver.Options{ @@ -99,7 +99,7 @@ func main() { Scheme: mgr.GetScheme(), CancelMgrFunc: nil, Log: ctrl.Log.WithName("KeptnWebhookCert Controller"), - Namespace: env.KLTNamespace, + Namespace: env.KeptnNamespace, MatchLabels: map[string]string{ env.KLTLabelSelectorKey: env.KLTLabelSelectorValue, }, diff --git a/lifecycle-operator/controllers/common/config/config.go b/lifecycle-operator/controllers/common/config/config.go index 043edb4348a..3d194b3f05c 100644 --- a/lifecycle-operator/controllers/common/config/config.go +++ b/lifecycle-operator/controllers/common/config/config.go @@ -13,11 +13,14 @@ type IConfig interface { GetCreationRequestTimeout() time.Duration SetCloudEventsEndpoint(endpoint string) GetCloudEventsEndpoint() string + SetDefaultNamespace(namespace string) + GetDefaultNamespace() string } type ControllerConfig struct { keptnAppCreationRequestTimeout time.Duration cloudEventsEndpoint string + defaultNamespace string } var instance *ControllerConfig @@ -45,3 +48,11 @@ func (o *ControllerConfig) SetCloudEventsEndpoint(endpoint string) { func (o *ControllerConfig) GetCloudEventsEndpoint() string { return o.cloudEventsEndpoint } + +func (o *ControllerConfig) SetDefaultNamespace(ns string) { + o.defaultNamespace = ns +} + +func (o *ControllerConfig) GetDefaultNamespace() string { + return o.defaultNamespace +} diff --git a/lifecycle-operator/controllers/common/config/config_test.go b/lifecycle-operator/controllers/common/config/config_test.go index bdaeaeb8773..40b4c9787ae 100644 --- a/lifecycle-operator/controllers/common/config/config_test.go +++ b/lifecycle-operator/controllers/common/config/config_test.go @@ -36,3 +36,22 @@ func TestGetOptionsInstance(t *testing.T) { timeout := o2.GetCreationRequestTimeout() require.Equal(t, 5*time.Second, timeout) } + +func TestConfig_SetAndGetDefaultNamespace(t *testing.T) { + i := Instance() + + ns := i.GetDefaultNamespace() + + require.Empty(t, ns) + i.SetDefaultNamespace("test") + require.Equal(t, "test", i.GetDefaultNamespace()) +} + +func TestConfig_SetAndGetCloudEventEndpoint(t *testing.T) { + i := Instance() + + ns := i.GetCloudEventsEndpoint() + require.Empty(t, ns) + i.SetCloudEventsEndpoint("mytestendpoint") + require.Equal(t, "mytestendpoint", i.GetCloudEventsEndpoint()) +} diff --git a/lifecycle-operator/controllers/common/config/fake/config_mock.go b/lifecycle-operator/controllers/common/config/fake/config_mock.go index 0bbe4fc0093..ef66114648d 100644 --- a/lifecycle-operator/controllers/common/config/fake/config_mock.go +++ b/lifecycle-operator/controllers/common/config/fake/config_mock.go @@ -20,12 +20,18 @@ import ( // GetCreationRequestTimeoutFunc: func() time.Duration { // panic("mock out the GetCreationRequestTimeout method") // }, +// GetDefaultNamespaceFunc: func() string { +// panic("mock out the GetDefaultNamespace method") +// }, // SetCloudEventsEndpointFunc: func(endpoint string) { // panic("mock out the SetCloudEventsEndpoint method") // }, // SetCreationRequestTimeoutFunc: func(value time.Duration) { // panic("mock out the SetCreationRequestTimeout method") // }, +// SetDefaultNamespaceFunc: func(namespace string) { +// panic("mock out the SetDefaultNamespace method") +// }, // } // // // use mockedIConfig in code that requires config.IConfig @@ -39,12 +45,18 @@ type MockConfig struct { // GetCreationRequestTimeoutFunc mocks the GetCreationRequestTimeout method. GetCreationRequestTimeoutFunc func() time.Duration + // GetDefaultNamespaceFunc mocks the GetDefaultNamespace method. + GetDefaultNamespaceFunc func() string + // SetCloudEventsEndpointFunc mocks the SetCloudEventsEndpoint method. SetCloudEventsEndpointFunc func(endpoint string) // SetCreationRequestTimeoutFunc mocks the SetCreationRequestTimeout method. SetCreationRequestTimeoutFunc func(value time.Duration) + // SetDefaultNamespaceFunc mocks the SetDefaultNamespace method. + SetDefaultNamespaceFunc func(namespace string) + // calls tracks calls to the methods. calls struct { // GetCloudEventsEndpoint holds details about calls to the GetCloudEventsEndpoint method. @@ -53,6 +65,9 @@ type MockConfig struct { // GetCreationRequestTimeout holds details about calls to the GetCreationRequestTimeout method. GetCreationRequestTimeout []struct { } + // GetDefaultNamespace holds details about calls to the GetDefaultNamespace method. + GetDefaultNamespace []struct { + } // SetCloudEventsEndpoint holds details about calls to the SetCloudEventsEndpoint method. SetCloudEventsEndpoint []struct { // Endpoint is the endpoint argument value. @@ -63,11 +78,18 @@ type MockConfig struct { // Value is the value argument value. Value time.Duration } + // SetDefaultNamespace holds details about calls to the SetDefaultNamespace method. + SetDefaultNamespace []struct { + // Namespace is the namespace argument value. + Namespace string + } } lockGetCloudEventsEndpoint sync.RWMutex lockGetCreationRequestTimeout sync.RWMutex + lockGetDefaultNamespace sync.RWMutex lockSetCloudEventsEndpoint sync.RWMutex lockSetCreationRequestTimeout sync.RWMutex + lockSetDefaultNamespace sync.RWMutex } // GetCloudEventsEndpoint calls GetCloudEventsEndpointFunc. @@ -124,6 +146,33 @@ func (mock *MockConfig) GetCreationRequestTimeoutCalls() []struct { return calls } +// GetDefaultNamespace calls GetDefaultNamespaceFunc. +func (mock *MockConfig) GetDefaultNamespace() string { + if mock.GetDefaultNamespaceFunc == nil { + panic("MockConfig.GetDefaultNamespaceFunc: method is nil but IConfig.GetDefaultNamespace was just called") + } + callInfo := struct { + }{} + mock.lockGetDefaultNamespace.Lock() + mock.calls.GetDefaultNamespace = append(mock.calls.GetDefaultNamespace, callInfo) + mock.lockGetDefaultNamespace.Unlock() + return mock.GetDefaultNamespaceFunc() +} + +// GetDefaultNamespaceCalls gets all the calls that were made to GetDefaultNamespace. +// Check the length with: +// +// len(mockedIConfig.GetDefaultNamespaceCalls()) +func (mock *MockConfig) GetDefaultNamespaceCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDefaultNamespace.RLock() + calls = mock.calls.GetDefaultNamespace + mock.lockGetDefaultNamespace.RUnlock() + return calls +} + // SetCloudEventsEndpoint calls SetCloudEventsEndpointFunc. func (mock *MockConfig) SetCloudEventsEndpoint(endpoint string) { if mock.SetCloudEventsEndpointFunc == nil { @@ -187,3 +236,35 @@ func (mock *MockConfig) SetCreationRequestTimeoutCalls() []struct { mock.lockSetCreationRequestTimeout.RUnlock() return calls } + +// SetDefaultNamespace calls SetDefaultNamespaceFunc. +func (mock *MockConfig) SetDefaultNamespace(namespace string) { + if mock.SetDefaultNamespaceFunc == nil { + panic("MockConfig.SetDefaultNamespaceFunc: method is nil but IConfig.SetDefaultNamespace was just called") + } + callInfo := struct { + Namespace string + }{ + Namespace: namespace, + } + mock.lockSetDefaultNamespace.Lock() + mock.calls.SetDefaultNamespace = append(mock.calls.SetDefaultNamespace, callInfo) + mock.lockSetDefaultNamespace.Unlock() + mock.SetDefaultNamespaceFunc(namespace) +} + +// SetDefaultNamespaceCalls gets all the calls that were made to SetDefaultNamespace. +// Check the length with: +// +// len(mockedIConfig.SetDefaultNamespaceCalls()) +func (mock *MockConfig) SetDefaultNamespaceCalls() []struct { + Namespace string +} { + var calls []struct { + Namespace string + } + mock.lockSetDefaultNamespace.RLock() + calls = mock.calls.SetDefaultNamespace + mock.lockSetDefaultNamespace.RUnlock() + return calls +} diff --git a/lifecycle-operator/controllers/common/helperfunctions.go b/lifecycle-operator/controllers/common/helperfunctions.go index 333f0be7d22..54cb9916d17 100644 --- a/lifecycle-operator/controllers/common/helperfunctions.go +++ b/lifecycle-operator/controllers/common/helperfunctions.go @@ -7,14 +7,13 @@ import ( "github.com/go-logr/logr" klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/interfaces" k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" ) -const KLTNamespace = "keptn-lifecycle-toolkit-system" - // GetItemStatus retrieves the state of the task/evaluation, if it does not exists, it creates a default one func GetItemStatus(name string, instanceStatus []klcv1alpha3.ItemStatus) klcv1alpha3.ItemStatus { for _, status := range instanceStatus { @@ -96,7 +95,7 @@ func getObject(k8sclient client.Client, log logr.Logger, ctx context.Context, de if err != nil { log.Info("Failed to get resource from application namespace", "resource type", fmt.Sprintf("%T", definition), "Definition name", definitionName, "namespace", namespace) if k8serrors.IsNotFound(err) { - if err := k8sclient.Get(ctx, types.NamespacedName{Name: definitionName, Namespace: KLTNamespace}, definition); err != nil { + if err := k8sclient.Get(ctx, types.NamespacedName{Name: definitionName, Namespace: config.Instance().GetDefaultNamespace()}, definition); err != nil { log.Info("Failed to get resource from default KLT namespace", "resource type", fmt.Sprintf("%T", definition), "definition name", definitionName) return err } diff --git a/lifecycle-operator/controllers/common/helperfunctions_test.go b/lifecycle-operator/controllers/common/helperfunctions_test.go index 0d34aeea82c..5987ed2e4e4 100644 --- a/lifecycle-operator/controllers/common/helperfunctions_test.go +++ b/lifecycle-operator/controllers/common/helperfunctions_test.go @@ -6,6 +6,7 @@ import ( klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/stretchr/testify/require" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/scheme" @@ -14,6 +15,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) +const KeptnNamespace = "keptn" + func Test_GetItemStatus(t *testing.T) { tests := []struct { name string @@ -402,7 +405,7 @@ func Test_GetTaskDefinition(t *testing.T) { taskDef: &klcv1alpha3.KeptnTaskDefinition{ ObjectMeta: v1.ObjectMeta{ Name: "taskDef", - Namespace: KLTNamespace, + Namespace: KeptnNamespace, }, }, taskDefName: "taskDef", @@ -410,7 +413,7 @@ func Test_GetTaskDefinition(t *testing.T) { out: &klcv1alpha3.KeptnTaskDefinition{ ObjectMeta: v1.ObjectMeta{ Name: "taskDef", - Namespace: KLTNamespace, + Namespace: KeptnNamespace, }, }, wantError: false, @@ -420,6 +423,8 @@ func Test_GetTaskDefinition(t *testing.T) { err := klcv1alpha3.AddToScheme(scheme.Scheme) require.Nil(t, err) + config.Instance().SetDefaultNamespace(KeptnNamespace) + for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := fake.NewClientBuilder().WithObjects(tt.taskDef).Build() @@ -484,7 +489,7 @@ func Test_GetEvaluationDefinition(t *testing.T) { evalDef: &klcv1alpha3.KeptnEvaluationDefinition{ ObjectMeta: v1.ObjectMeta{ Name: "evalDef", - Namespace: KLTNamespace, + Namespace: KeptnNamespace, }, }, evalDefName: "evalDef", @@ -492,7 +497,7 @@ func Test_GetEvaluationDefinition(t *testing.T) { out: &klcv1alpha3.KeptnEvaluationDefinition{ ObjectMeta: v1.ObjectMeta{ Name: "evalDef", - Namespace: KLTNamespace, + Namespace: KeptnNamespace, }, }, wantError: false, @@ -501,6 +506,7 @@ func Test_GetEvaluationDefinition(t *testing.T) { err := klcv1alpha3.AddToScheme(scheme.Scheme) require.Nil(t, err) + config.Instance().SetDefaultNamespace(KeptnNamespace) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric.go b/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric.go index 5baf001e0ee..26d3d71a88c 100644 --- a/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric.go +++ b/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric.go @@ -6,7 +6,7 @@ import ( "github.com/go-logr/logr" klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" - "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -57,8 +57,9 @@ func (p *KeptnMetricProvider) GetKeptnMetric(ctx context.Context, objective klcv } else { if err := p.K8sClient.Get(ctx, types.NamespacedName{Name: objective.KeptnMetricRef.Name, Namespace: namespace}, metric); err != nil { p.Log.Error(err, "Failed to get KeptnMetric from KeptnEvaluation resource namespace") - if err := p.K8sClient.Get(ctx, types.NamespacedName{Name: objective.KeptnMetricRef.Name, Namespace: common.KLTNamespace}, metric); err != nil { - p.Log.Error(err, "Failed to get KeptnMetric from "+common.KLTNamespace+" namespace") + defaultNamespace := config.Instance().GetDefaultNamespace() + if err := p.K8sClient.Get(ctx, types.NamespacedName{Name: objective.KeptnMetricRef.Name, Namespace: defaultNamespace}, metric); err != nil { + p.Log.Error(err, "Failed to get KeptnMetric from "+defaultNamespace+" namespace") return nil, err } } diff --git a/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric_test.go b/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric_test.go index 23830973433..23d59383867 100644 --- a/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric_test.go +++ b/lifecycle-operator/controllers/common/providers/keptnmetric/keptnmetric_test.go @@ -5,7 +5,7 @@ import ( "testing" klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" - "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" metricsapi "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/api/metrics/v1alpha3" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -15,6 +15,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) +const KeptnNamespace = "test" + func Test_keptnmetric(t *testing.T) { tests := []struct { name string @@ -74,6 +76,7 @@ func Test_keptnmetric(t *testing.T) { wantError: false, }, } + config.Instance().SetDefaultNamespace(KeptnNamespace) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -187,14 +190,14 @@ func Test_Getkeptnmetric(t *testing.T) { metric: &metricsapi.KeptnMetric{ ObjectMeta: metav1.ObjectMeta{ Name: "metric", - Namespace: common.KLTNamespace, + Namespace: KeptnNamespace, }, }, namespace: "my-other-namespace", out: &metricsapi.KeptnMetric{ ObjectMeta: metav1.ObjectMeta{ Name: "metric", - Namespace: common.KLTNamespace, + Namespace: KeptnNamespace, }, }, wantError: false, @@ -204,6 +207,7 @@ func Test_Getkeptnmetric(t *testing.T) { err := metricsapi.AddToScheme(scheme.Scheme) require.Nil(t, err) + config.Instance().SetDefaultNamespace(KeptnNamespace) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := fake.NewClientBuilder().WithObjects(tt.metric).Build() diff --git a/lifecycle-operator/controllers/common/taskhandler_test.go b/lifecycle-operator/controllers/common/taskhandler_test.go index f71a76ca62d..54156faedd9 100644 --- a/lifecycle-operator/controllers/common/taskhandler_test.go +++ b/lifecycle-operator/controllers/common/taskhandler_test.go @@ -7,6 +7,7 @@ import ( "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" kltfake "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/fake" controllererrors "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/errors" "github.com/stretchr/testify/require" @@ -101,7 +102,7 @@ func TestTaskHandler(t *testing.T) { }, taskDef: &v1alpha3.KeptnTaskDefinition{ ObjectMeta: v1.ObjectMeta{ - Namespace: KLTNamespace, + Namespace: KeptnNamespace, Name: "task-def", }, }, @@ -141,7 +142,7 @@ func TestTaskHandler(t *testing.T) { }, taskDef: &v1alpha3.KeptnTaskDefinition{ ObjectMeta: v1.ObjectMeta{ - Namespace: KLTNamespace, + Namespace: KeptnNamespace, Name: "task-def", }, }, @@ -353,6 +354,7 @@ func TestTaskHandler(t *testing.T) { unbindSpanCalls: 1, }, } + config.Instance().SetDefaultNamespace(KeptnNamespace) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/lifecycle-operator/controllers/lifecycle/keptnappcreationrequest/controller_test.go b/lifecycle-operator/controllers/lifecycle/keptnappcreationrequest/controller_test.go index 8c85f953b1c..45d183093a7 100644 --- a/lifecycle-operator/controllers/lifecycle/keptnappcreationrequest/controller_test.go +++ b/lifecycle-operator/controllers/lifecycle/keptnappcreationrequest/controller_test.go @@ -20,6 +20,8 @@ import ( k8sfake "sigs.k8s.io/controller-runtime/pkg/client/fake" ) +const KeptnNamespace = "test" + func TestKeptnAppCreationRequestReconciler_CreateAppAfterTimeout_SingleWorkload(t *testing.T) { r, fakeClient, theClock := setupReconcilerAndClient(t) @@ -666,6 +668,9 @@ func setupReconcilerAndClient(t *testing.T) (*KeptnAppCreationRequestReconciler, GetCreationRequestTimeoutFunc: func() time.Duration { return 30 * time.Second }, + GetDefaultNamespaceFunc: func() string { + return KeptnNamespace + }, }, } return r, fakeClient, theClock diff --git a/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller.go b/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller.go index 44423c7179a..7b7cae48a78 100644 --- a/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller.go +++ b/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller.go @@ -51,7 +51,6 @@ type KeptnEvaluationReconciler struct { Log logr.Logger Meters apicommon.KeptnMeters TracerFactory telemetry.TracerFactory - Namespace string } // clusterrole diff --git a/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller_test.go b/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller_test.go index 771effd2249..ec657cdf785 100644 --- a/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller_test.go +++ b/lifecycle-operator/controllers/lifecycle/keptnevaluation/controller_test.go @@ -9,6 +9,7 @@ import ( klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/fake" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/telemetry" metricsapi "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/api/metrics/v1alpha3" @@ -24,8 +25,6 @@ import ( k8sfake "sigs.k8s.io/controller-runtime/pkg/client/fake" ) -const KltNamespace = "klt-namespace" - func TestKeptnEvaluationReconciler_Reconcile_FailEvaluation(t *testing.T) { const namespace = "my-namespace" @@ -164,7 +163,7 @@ func TestKeptnEvaluationReconciler_Reconcile_SucceedEvaluation(t *testing.T) { require.Equal(t, "value '10' met objective '<11'", updatedEvaluation.Status.EvaluationStatus[metric.Name].Message) } -func TestKeptnEvaluationReconciler_Reconcile_SucceedEvaluation_withDefinitionInDefaultKLTNamespace(t *testing.T) { +func TestKeptnEvaluationReconciler_Reconcile_SucceedEvaluation_withDefinitionInDefaultKeptnNamespace(t *testing.T) { const namespace = "my-namespace" metric := &metricsapi.KeptnMetric{ @@ -181,7 +180,7 @@ func TestKeptnEvaluationReconciler_Reconcile_SucceedEvaluation_withDefinitionInD evaluationDefinition := &klcv1alpha3.KeptnEvaluationDefinition{ ObjectMeta: metav1.ObjectMeta{ Name: "my-definition", - Namespace: controllercommon.KLTNamespace, + Namespace: "keptn", }, Spec: klcv1alpha3.KeptnEvaluationDefinitionSpec{ Objectives: []klcv1alpha3.Objective{ @@ -256,6 +255,8 @@ func setupReconcilerAndClient(t *testing.T, objects ...client.Object) (*KeptnEva provider := metric.NewMeterProvider() meter := provider.Meter("keptn/task") + config.Instance().SetDefaultNamespace("keptn") + r := &KeptnEvaluationReconciler{ Client: fakeClient, Scheme: fakeClient.Scheme(), diff --git a/lifecycle-operator/controllers/lifecycle/keptntask/job_utils_test.go b/lifecycle-operator/controllers/lifecycle/keptntask/job_utils_test.go index 3f97ff5999e..791e003537a 100644 --- a/lifecycle-operator/controllers/lifecycle/keptntask/job_utils_test.go +++ b/lifecycle-operator/controllers/lifecycle/keptntask/job_utils_test.go @@ -6,8 +6,8 @@ import ( klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" - "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" fakeclient "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/fake" "github.com/stretchr/testify/require" batchv1 "k8s.io/api/batch/v1" @@ -19,6 +19,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" ) +const KeptnNamespace = "mynamespace" + func TestKeptnTaskReconciler_createJob(t *testing.T) { namespace := "default" cmName := "my-cmd" @@ -90,7 +92,7 @@ func TestKeptnTaskReconciler_createJob_withTaskDefInDefaultNamespace(t *testing. taskDefinitionName := "my-task-definition" cm := makeConfigMap(cmName, namespace) - taskDefinition := makeTaskDefinitionWithConfigmapRef(taskDefinitionName, common.KLTNamespace, cmName) + taskDefinition := makeTaskDefinitionWithConfigmapRef(taskDefinitionName, KeptnNamespace, cmName) fakeClient := fakeclient.NewClient(cm, taskDefinition) @@ -98,6 +100,7 @@ func TestKeptnTaskReconciler_createJob_withTaskDefInDefaultNamespace(t *testing. err := fakeClient.Status().Update(context.TODO(), taskDefinition) require.Nil(t, err) + config.Instance().SetDefaultNamespace(KeptnNamespace) r := &KeptnTaskReconciler{ Client: fakeClient, EventSender: controllercommon.NewK8sSender(record.NewFakeRecorder(100)), diff --git a/lifecycle-operator/main.go b/lifecycle-operator/main.go index 08df8a96e62..2696070a626 100644 --- a/lifecycle-operator/main.go +++ b/lifecycle-operator/main.go @@ -34,6 +34,7 @@ import ( lifecyclev1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" optionsv1alpha1 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/options/v1alpha1" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/telemetry" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptnapp" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptnappcreationrequest" @@ -136,6 +137,9 @@ func main() { // parse the flags, so we ensure they can be set to something else than their default values flag.Parse() + // inject pod namespace into common configs + config.Instance().SetDefaultNamespace(env.PodNamespace) + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) disableCacheFor := []ctrlclient.Object{&corev1.Secret{}} @@ -293,7 +297,6 @@ func main() { EventSender: controllercommon.NewEventMultiplexer(evaluationLogger, evaluationRecorder, ceClient), TracerFactory: telemetry.GetOtelInstance(), Meters: keptnMeters, - Namespace: env.PodNamespace, } if err = (evaluationReconciler).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "KeptnEvaluation") diff --git a/lifecycle-operator/test/component/appversion/appversion_suite_test.go b/lifecycle-operator/test/component/appversion/appversion_suite_test.go index 5ea53119496..6510d3a16c1 100644 --- a/lifecycle-operator/test/component/appversion/appversion_suite_test.go +++ b/lifecycle-operator/test/component/appversion/appversion_suite_test.go @@ -7,6 +7,7 @@ import ( "time" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/telemetry" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptnappversion" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" @@ -33,10 +34,14 @@ var ( spanRecorder *sdktest.SpanRecorder ) +const KeptnNamespace = "keptnlifecycle" + var _ = BeforeSuite(func() { var readyToStart chan struct{} ctx, k8sManager, tracer, spanRecorder, k8sClient, readyToStart = common.InitSuite() + config.Instance().SetDefaultNamespace(KeptnNamespace) + // //setup controllers here controller := &keptnappversion.KeptnAppVersionReconciler{ Client: k8sManager.GetClient(), diff --git a/lifecycle-operator/test/component/evaluation/evaluation_suite_test.go b/lifecycle-operator/test/component/evaluation/evaluation_suite_test.go index 855c25ce7a9..a64ed60251b 100644 --- a/lifecycle-operator/test/component/evaluation/evaluation_suite_test.go +++ b/lifecycle-operator/test/component/evaluation/evaluation_suite_test.go @@ -7,6 +7,7 @@ import ( "time" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptnevaluation" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" . "github.com/onsi/ginkgo/v2" @@ -34,12 +35,13 @@ var ( ns *v1.Namespace ) -const KLTnamespace = "keptnlifecycle" +const KeptnNamespace = "keptnlifecycle" var _ = BeforeSuite(func() { var readyToStart chan struct{} ctx, k8sManager, tracer, spanRecorder, k8sClient, readyToStart = common.InitSuite() + config.Instance().SetDefaultNamespace(KeptnNamespace) // //setup controllers here controller := &keptnevaluation.KeptnEvaluationReconciler{ Client: k8sManager.GetClient(), @@ -48,11 +50,10 @@ var _ = BeforeSuite(func() { Log: GinkgoLogr, Meters: common.InitKeptnMeters(), TracerFactory: &common.TracerFactory{Tracer: tracer}, - Namespace: KLTnamespace, } Eventually(controller.SetupWithManager(k8sManager)).WithTimeout(30 * time.Second).WithPolling(time.Second).Should(Succeed()) - ns = common.MakeKLTDefaultNamespace(k8sClient, KLTnamespace) + ns = common.MakeKLTDefaultNamespace(k8sClient, KeptnNamespace) close(readyToStart) }) diff --git a/lifecycle-operator/test/component/evaluation/evaluation_test.go b/lifecycle-operator/test/component/evaluation/evaluation_test.go index da0a442c436..d94fa2274e4 100644 --- a/lifecycle-operator/test/component/evaluation/evaluation_test.go +++ b/lifecycle-operator/test/component/evaluation/evaluation_test.go @@ -7,7 +7,6 @@ import ( klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" - controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" metricsapi "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/api/metrics/v1alpha3" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" . "github.com/onsi/ginkgo/v2" @@ -110,29 +109,19 @@ var _ = Describe("Evaluation", Ordered, func() { common.LogErrorIfPresent(err) }) It("KeptnEvaluationController Should succeed, as it finds KeptnEvaluationDefinition in default KLT namespace", func() { - By("create default KLT namespace") - - ns := &v1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: controllercommon.KLTNamespace, - }, - } - err := k8sClient.Create(context.TODO(), ns) - Expect(err).To(BeNil()) - By("Create EvaluationDefiniton") - evaluationDefinition = makeEvaluationDefinition(evaluationDefinitionName, controllercommon.KLTNamespace, metricName) + evaluationDefinition = makeEvaluationDefinition(evaluationDefinitionName, KeptnNamespace, metricName) By("Create KeptnMetric") - metric := makeKeptnMetric(metricName, controllercommon.KLTNamespace) + metric := makeKeptnMetric(metricName, KeptnNamespace) By("Update KeptnMetric to have status") metric2 := &metricsapi.KeptnMetric{} - err = k8sClient.Get(context.TODO(), types.NamespacedName{ - Namespace: controllercommon.KLTNamespace, + err := k8sClient.Get(context.TODO(), types.NamespacedName{ + Namespace: KeptnNamespace, Name: metric.Name, }, metric2) Expect(err).To(BeNil()) @@ -149,14 +138,14 @@ var _ = Describe("Evaluation", Ordered, func() { evaluationdef := &klcv1alpha3.KeptnEvaluationDefinition{} Eventually(func(g Gomega) { err := k8sClient.Get(context.TODO(), types.NamespacedName{ - Namespace: controllercommon.KLTNamespace, + Namespace: KeptnNamespace, Name: evaluationDefinitionName, }, evaluationdef) g.Expect(err).To(BeNil()) g.Expect(evaluationdef.Spec.Objectives[0]).To(Equal(klcv1alpha3.Objective{ KeptnMetricRef: klcv1alpha3.KeptnMetricReference{ Name: metricName, - Namespace: controllercommon.KLTNamespace, + Namespace: KeptnNamespace, }, EvaluationTarget: "<10", })) diff --git a/lifecycle-operator/test/component/task/task_suite_test.go b/lifecycle-operator/test/component/task/task_suite_test.go index ee71257483b..cc7c3ab75c5 100644 --- a/lifecycle-operator/test/component/task/task_suite_test.go +++ b/lifecycle-operator/test/component/task/task_suite_test.go @@ -7,6 +7,7 @@ import ( "time" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptntask" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" . "github.com/onsi/ginkgo/v2" @@ -30,6 +31,8 @@ var ( ctx context.Context ) +const KeptnNamespace = "keptnlifecycle" + var _ = BeforeSuite(func() { var readyToStart chan struct{} ctx, k8sManager, tracer, _, k8sClient, readyToStart = common.InitSuite() @@ -37,6 +40,8 @@ var _ = BeforeSuite(func() { _ = os.Setenv(controllercommon.FunctionRuntimeImageKey, "my-image-js") _ = os.Setenv(controllercommon.PythonRuntimeImageKey, "my-image-py") + config.Instance().SetDefaultNamespace(KeptnNamespace) + // //setup controllers here controller := &keptntask.KeptnTaskReconciler{ Client: k8sManager.GetClient(), diff --git a/lifecycle-operator/test/component/task/task_test.go b/lifecycle-operator/test/component/task/task_test.go index 03cd4b4625a..e2c009dca8f 100644 --- a/lifecycle-operator/test/component/task/task_test.go +++ b/lifecycle-operator/test/component/task/task_test.go @@ -5,7 +5,6 @@ import ( klcv1alpha3 "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3" apicommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common" - controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -83,13 +82,13 @@ var _ = Describe("Task", Ordered, func() { ns := &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ - Name: controllercommon.KLTNamespace, + Name: KeptnNamespace, }, } err := k8sClient.Create(context.TODO(), ns) Expect(err).To(BeNil()) - taskDefinition = makeTaskDefinition(taskDefinitionName, controllercommon.KLTNamespace) + taskDefinition = makeTaskDefinition(taskDefinitionName, KeptnNamespace) task = makeTask(name, namespace, taskDefinition.Name) By("Verifying that a job has been created") @@ -136,13 +135,13 @@ var _ = Describe("Task", Ordered, func() { ns := &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ - Name: controllercommon.KLTNamespace, + Name: KeptnNamespace, }, } err := k8sClient.Create(context.TODO(), ns) Expect(common.IgnoreAlreadyExists(err)).To(BeNil()) - taskDefinition = makeContainerTaskDefinition(taskDefinitionName, controllercommon.KLTNamespace) + taskDefinition = makeContainerTaskDefinition(taskDefinitionName, KeptnNamespace) task = makeTask(name, namespace, taskDefinition.Name) By("Verifying that a job has been created") diff --git a/lifecycle-operator/test/component/workloadinstance/workloadinstance_suite_test.go b/lifecycle-operator/test/component/workloadinstance/workloadinstance_suite_test.go index 91da1a60e15..2d3bb0678ba 100644 --- a/lifecycle-operator/test/component/workloadinstance/workloadinstance_suite_test.go +++ b/lifecycle-operator/test/component/workloadinstance/workloadinstance_suite_test.go @@ -7,6 +7,7 @@ import ( "time" controllercommon "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common" + "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/telemetry" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/lifecycle/keptnworkloadinstance" "github.com/keptn/lifecycle-toolkit/lifecycle-operator/test/component/common" @@ -33,11 +34,14 @@ var ( spanRecorder *sdktest.SpanRecorder ) +const KeptnNamespace = "keptnlifecycle" + var _ = BeforeSuite(func() { var readyToStart chan struct{} ctx, k8sManager, tracer, spanRecorder, k8sClient, readyToStart = common.InitSuite() // //setup controllers here + config.Instance().SetDefaultNamespace(KeptnNamespace) controller := &keptnworkloadinstance.KeptnWorkloadInstanceReconciler{ Client: k8sManager.GetClient(), Scheme: k8sManager.GetScheme(), diff --git a/metrics-operator/cmd/metrics/adapter/adapter.go b/metrics-operator/cmd/metrics/adapter/adapter.go index 3a2106a08d2..c7563ba4b56 100644 --- a/metrics-operator/cmd/metrics/adapter/adapter.go +++ b/metrics-operator/cmd/metrics/adapter/adapter.go @@ -26,7 +26,7 @@ var ( type MetricsAdapter struct { basecmd.AdapterBase - KltNamespace string + KeptnNamespace string } // RunAdapter starts the Keptn Metrics adapter to provide KeptnMetrics via the Kubernetes Custom Metrics API. @@ -70,7 +70,7 @@ func (a *MetricsAdapter) makeProviderOrDie(ctx context.Context) provider.CustomM klog.Fatalf("unable to construct dynamic client: %v", err) } - return kmprovider.NewProvider(ctx, client, a.KltNamespace) + return kmprovider.NewProvider(ctx, client, a.KeptnNamespace) } func addFlags() { diff --git a/metrics-operator/cmd/metrics/adapter/provider/provider.go b/metrics-operator/cmd/metrics/adapter/provider/provider.go index e4f47b592ab..19ca2ae521d 100644 --- a/metrics-operator/cmd/metrics/adapter/provider/provider.go +++ b/metrics-operator/cmd/metrics/adapter/provider/provider.go @@ -32,10 +32,10 @@ var providerInstance *keptnMetricsProvider var providerOnce sync.Once type keptnMetricsProvider struct { - client dynamic.Interface - scheme *runtime.Scheme - logger logr.Logger - KltNamespace string + client dynamic.Interface + scheme *runtime.Scheme + logger logr.Logger + KeptnNamespace string // cache is being populated via the updates received by the provider's dynamic informer // this way, we avoid sending a request to the Kubernetes API each time a custom metric value should be retrieved @@ -54,8 +54,8 @@ func NewProvider(ctx context.Context, client dynamic.Interface, namespace string cache: CustomMetricsCache{ metrics: map[metricKey]CustomMetricValue{}, }, - logger: ctrl.Log.WithName("provider"), - KltNamespace: namespace, + logger: ctrl.Log.WithName("provider"), + KeptnNamespace: namespace, } if err := providerInstance.watchMetrics(ctx); err != nil { diff --git a/metrics-operator/cmd/metrics/adapter/provider/provider_test.go b/metrics-operator/cmd/metrics/adapter/provider/provider_test.go index 98ebaefcefc..d3ff7d17138 100644 --- a/metrics-operator/cmd/metrics/adapter/provider/provider_test.go +++ b/metrics-operator/cmd/metrics/adapter/provider/provider_test.go @@ -15,7 +15,7 @@ import ( provider2 "sigs.k8s.io/custom-metrics-apiserver/pkg/provider" ) -const kltNamespace = "my-namespace" +const KeptnNamespace = "my-namespace" func TestProvider(t *testing.T) { metricObj1 := getSampleKeptnMetric("my-metric", map[string]interface{}{}) @@ -26,7 +26,7 @@ func TestProvider(t *testing.T) { scheme := runtime.NewScheme() fakeClient := fake.NewSimpleDynamicClient(scheme, km) - provider := NewProvider(context.TODO(), fakeClient, kltNamespace) + provider := NewProvider(context.TODO(), fakeClient, KeptnNamespace) require.NotNil(t, provider) @@ -43,14 +43,14 @@ func TestProvider(t *testing.T) { "value": "10.0", } km.SetUnstructuredContent(metricObj1) - _, err := fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(kltNamespace).UpdateStatus(context.TODO(), km, metav1.UpdateOptions{}) + _, err := fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(KeptnNamespace).UpdateStatus(context.TODO(), km, metav1.UpdateOptions{}) require.Nil(t, err) // eventually the updated value should be reflected require.Eventually(t, func() bool { metricValue, err := provider.GetMetricByName(context.TODO(), types.NamespacedName{ - Namespace: kltNamespace, + Namespace: KeptnNamespace, Name: "my-metric", }, provider2.CustomMetricInfo{}, nil) @@ -62,7 +62,7 @@ func TestProvider(t *testing.T) { // look for an unknown metric metricValue, err := provider.GetMetricByName(context.TODO(), types.NamespacedName{ - Namespace: kltNamespace, + Namespace: KeptnNamespace, Name: "my-unknown-metric", }, provider2.CustomMetricInfo{}, labels.Set{}.AsSelector()) @@ -72,7 +72,7 @@ func TestProvider(t *testing.T) { // look for metrics based on a label selector metrics, err := provider.GetMetricBySelector( context.TODO(), - kltNamespace, + KeptnNamespace, labels.Set(map[string]string{"app": "frontend"}).AsSelector(), provider2.CustomMetricInfo{}, nil, @@ -86,7 +86,7 @@ func TestProvider(t *testing.T) { km2 := &unstructured.Unstructured{} km2.SetUnstructuredContent(metricObj2) - _, err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(kltNamespace).Create(context.TODO(), km2, metav1.CreateOptions{}) + _, err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(KeptnNamespace).Create(context.TODO(), km2, metav1.CreateOptions{}) require.Nil(t, err) // wait for the new metric to be registered @@ -99,7 +99,7 @@ func TestProvider(t *testing.T) { // retrieve based on the selector again metrics, err = provider.GetMetricBySelector( context.TODO(), - kltNamespace, + KeptnNamespace, labels.Set(map[string]string{"app": "frontend"}).AsSelector(), provider2.CustomMetricInfo{}, nil, @@ -109,9 +109,9 @@ func TestProvider(t *testing.T) { require.Len(t, metrics.Items, 1) // delete the metrics again - err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(kltNamespace).Delete(context.TODO(), "my-metric", metav1.DeleteOptions{}) + err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(KeptnNamespace).Delete(context.TODO(), "my-metric", metav1.DeleteOptions{}) require.Nil(t, err) - err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(kltNamespace).Delete(context.TODO(), "my-metric-2", metav1.DeleteOptions{}) + err = fakeClient.Resource(keptnMetricGroupVersionResource).Namespace(KeptnNamespace).Delete(context.TODO(), "my-metric-2", metav1.DeleteOptions{}) require.Nil(t, err) // wait for the length of the returned list to be 0 @@ -128,7 +128,7 @@ func getSampleKeptnMetric(metricName string, labels map[string]interface{}) map[ "kind": "KeptnMetric", "metadata": map[string]interface{}{ "name": metricName, - "namespace": kltNamespace, + "namespace": KeptnNamespace, "labels": labels, }, "spec": map[string]interface{}{ diff --git a/metrics-operator/main.go b/metrics-operator/main.go index 0e4c6635f25..12621b0bb7f 100644 --- a/metrics-operator/main.go +++ b/metrics-operator/main.go @@ -278,7 +278,7 @@ func startCustomMetricsAdapter(namespace string) { ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM) defer cancel() - metricsAdapter := adapter.MetricsAdapter{KltNamespace: namespace} + metricsAdapter := adapter.MetricsAdapter{KeptnNamespace: namespace} metricsAdapter.RunAdapter(ctx) }