From 22a29b8f68c67508e05d55606605b78b5878fa68 Mon Sep 17 00:00:00 2001 From: sophon Date: Thu, 14 Nov 2024 20:51:09 +0800 Subject: [PATCH] chore: refine ut --- controllers/apps/suite_test.go | 26 +++++ controllers/apps/transformer_component_tls.go | 5 + .../apps/transformer_component_tls_test.go | 38 +++++--- controllers/operations/suite_test.go | 5 + .../componentdrivenparameter_controller.go | 18 +++- .../componentparameter_controller_test.go | 54 +++-------- controllers/parameters/configuration_test.go | 77 +++++++-------- .../parametersdefinition_controller_test.go | 39 ++------ controllers/parameters/reconcile_task.go | 80 ++++++++++++---- controllers/parameters/suite_test.go | 9 ++ pkg/controller/configuration/config_utils.go | 28 +----- .../configuration/configuration_test.go | 2 +- .../configuration/envfrom_utils_test.go | 2 +- pkg/controllerutil/config_util.go | 7 +- .../apps/componentdefinition_factory.go | 3 +- .../parameters/componenttemplate_factory.go | 73 ++++++++++++++ .../parameterdrivenconfigrenders_factory.go | 96 +++++++++++++++++++ 17 files changed, 379 insertions(+), 183 deletions(-) create mode 100644 pkg/testutil/parameters/componenttemplate_factory.go create mode 100644 pkg/testutil/parameters/parameterdrivenconfigrenders_factory.go diff --git a/controllers/apps/suite_test.go b/controllers/apps/suite_test.go index 1483551742e..a0b3da464be 100644 --- a/controllers/apps/suite_test.go +++ b/controllers/apps/suite_test.go @@ -47,6 +47,7 @@ import ( appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" dpv1alpha1 "github.com/apecloud/kubeblocks/apis/dataprotection/v1alpha1" opsv1alpha1 "github.com/apecloud/kubeblocks/apis/operations/v1alpha1" + parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" workloadsv1 "github.com/apecloud/kubeblocks/apis/workloads/v1" "github.com/apecloud/kubeblocks/controllers/dataprotection" "github.com/apecloud/kubeblocks/controllers/k8score" @@ -150,6 +151,10 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) model.AddScheme(workloadsv1.AddToScheme) + err = parametersv1alpha1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + model.AddScheme(parametersv1alpha1.AddToScheme) + // +kubebuilder:scaffold:rscheme k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) @@ -244,6 +249,27 @@ var _ = BeforeSuite(func() { }).SetupWithManager(k8sManager, nil) Expect(err).ToNot(HaveOccurred()) + err = (¶meters.ComponentDrivenParameterReconciler{ + Client: k8sManager.GetClient(), + Scheme: k8sManager.GetScheme(), + Recorder: k8sManager.GetEventRecorderFor("component-parameter-controller"), + }).SetupWithManager(k8sManager) + Expect(err).ToNot(HaveOccurred()) + + err = (¶meters.ParametersDefinitionReconciler{ + Client: k8sManager.GetClient(), + Scheme: k8sManager.GetScheme(), + Recorder: k8sManager.GetEventRecorderFor("parameters-definition-controller"), + }).SetupWithManager(k8sManager) + Expect(err).ToNot(HaveOccurred()) + + err = (¶meters.ParameterDrivenConfigRenderReconciler{ + Client: k8sManager.GetClient(), + Scheme: k8sManager.GetScheme(), + Recorder: k8sManager.GetEventRecorderFor("parameter-driven-config-render-controller"), + }).SetupWithManager(k8sManager) + Expect(err).ToNot(HaveOccurred()) + err = (&dataprotection.BackupPolicyTemplateReconciler{ Client: k8sManager.GetClient(), Scheme: k8sManager.GetScheme(), diff --git a/controllers/apps/transformer_component_tls.go b/controllers/apps/transformer_component_tls.go index a58d9bd6f1f..091c412dccf 100644 --- a/controllers/apps/transformer_component_tls.go +++ b/controllers/apps/transformer_component_tls.go @@ -52,6 +52,10 @@ func (t *componentTLSTransformer) Transform(ctx graph.TransformContext, dag *gra transCtx, _ := ctx.(*componentTransformContext) synthesizedComp := transCtx.SynthesizeComponent + if model.IsObjectDeleting(transCtx.ComponentOrig) { + return nil + } + // update podSpec tls volume and volumeMount if err := updateTLSVolumeAndVolumeMount(synthesizedComp.PodSpec, synthesizedComp.ClusterName, *synthesizedComp); err != nil { return err @@ -62,6 +66,7 @@ func (t *componentTLSTransformer) Transform(ctx graph.TransformContext, dag *gra return err } + // TODO: removed if err := checkAndTriggerReRender(transCtx.Context, *synthesizedComp, t.Client); err != nil { return err } diff --git a/controllers/apps/transformer_component_tls_test.go b/controllers/apps/transformer_component_tls_test.go index 139882e5463..610ef308791 100644 --- a/controllers/apps/transformer_component_tls_test.go +++ b/controllers/apps/transformer_component_tls_test.go @@ -32,7 +32,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" appsv1 "github.com/apecloud/kubeblocks/apis/apps/v1" - appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" cfgcore "github.com/apecloud/kubeblocks/pkg/configuration/core" "github.com/apecloud/kubeblocks/pkg/constant" "github.com/apecloud/kubeblocks/pkg/controller/component" @@ -41,6 +40,7 @@ import ( "github.com/apecloud/kubeblocks/pkg/generics" testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" testk8s "github.com/apecloud/kubeblocks/pkg/testutil/k8s" + testparameters "github.com/apecloud/kubeblocks/pkg/testutil/parameters" ) var _ = Describe("TLS self-signed cert function", func() { @@ -50,6 +50,8 @@ var _ = Describe("TLS self-signed cert function", func() { serviceKind = "mysql" defaultCompName = "mysql" configTemplateName = "mysql-config-tpl" + paramsDef = "mysql-pd" + pdcrName = "mysql-pd" ) var ( @@ -67,13 +69,18 @@ var _ = Describe("TLS self-signed cert function", func() { // create the new objects. By("clean resources") + inNs := client.InNamespace(testCtx.DefaultNamespace) + hasLabels := client.HasLabels{testCtx.TestObjLabelKey} + // delete cluster(and all dependent sub-resources), cluster definition testapps.ClearClusterResourcesWithRemoveFinalizerOption(&testCtx) // delete rest configurations + testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ConfigMapSignature, true, inNs, hasLabels) ml := client.HasLabels{testCtx.TestObjLabelKey} // non-namespaced - testapps.ClearResources(&testCtx, generics.ConfigConstraintSignature, ml) + testapps.ClearResources(&testCtx, generics.ParameterDrivenConfigRenderSignature, ml) + testapps.ClearResources(&testCtx, generics.ParametersDefinitionSignature, ml) testapps.ClearResources(&testCtx, generics.BackupPolicyTemplateSignature, ml) } @@ -83,15 +90,14 @@ var _ = Describe("TLS self-signed cert function", func() { Context("tls is enabled/disabled", func() { BeforeEach(func() { - configMapObj := testapps.CheckedCreateCustomizedObj(&testCtx, - "resources/mysql-tls-config-template.yaml", - &corev1.ConfigMap{}, - testCtx.UseDefaultNamespace(), - testapps.WithAnnotations(constant.CMInsEnableRerenderTemplateKey, "true")) + configMapObj := testparameters.NewComponentTemplateFactory(configTemplateName, testCtx.DefaultNamespace). + Create(&testCtx). + GetObject() - configConstraintObj := testapps.CheckedCreateCustomizedObj(&testCtx, - "resources/mysql-config-constraint.yaml", - &appsv1beta1.ConfigConstraint{}) + paramsdef := testparameters.NewParametersDefinitionFactory(paramsDef). + SetReloadAction(testparameters.WithNoneAction()). + Create(&testCtx). + GetObject() By("Create a componentDefinition obj") compDefObj = testapps.NewComponentDefinitionFactory(compDefName). @@ -99,10 +105,16 @@ var _ = Describe("TLS self-signed cert function", func() { AddAnnotations(constant.SkipImmutableCheckAnnotationKey, "true"). SetDefaultSpec(). SetServiceKind(serviceKind). - AddConfigTemplate(configTemplateName, configMapObj.Name, configConstraintObj.Name, testCtx.DefaultNamespace, testapps.ConfVolumeName). + AddConfigTemplate(configTemplateName, configMapObj.Name, testCtx.DefaultNamespace, testapps.ConfVolumeName). AddEnv(testapps.DefaultMySQLContainerName, corev1.EnvVar{Name: "MYSQL_ALLOW_EMPTY_PASSWORD", Value: "yes"}). Create(&testCtx). GetObject() + + testparameters.NewParametersDrivenConfigFactory(pdcrName). + SetParametersDefs(paramsdef.Name). + SetComponentDefinition(compDefObj.GetName()). + SetTemplateName(configTemplateName). + Create(&testCtx) }) Context("when issuer is UserProvided", func() { @@ -215,8 +227,8 @@ var _ = Describe("TLS self-signed cert function", func() { Expect(k8sClient.Patch(ctx, clusterObj, patch)).Should(Succeed()) Eventually(hasTLSSettings).Should(BeTrue()) - testapps.DeleteObject(&testCtx, clusterKey, &appsv1.Cluster{}) - Eventually(testapps.CheckObjExists(&testCtx, clusterKey, &appsv1.Cluster{}, false)).Should(Succeed()) + // testapps.DeleteObject(&testCtx, clusterKey, &appsv1.Cluster{}) + // Eventually(testapps.CheckObjExists(&testCtx, clusterKey, &appsv1.Cluster{}, false)).Should(Succeed()) }) }) diff --git a/controllers/operations/suite_test.go b/controllers/operations/suite_test.go index 00228de13e9..1c371a0802c 100644 --- a/controllers/operations/suite_test.go +++ b/controllers/operations/suite_test.go @@ -47,6 +47,7 @@ import ( appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" dpv1alpha1 "github.com/apecloud/kubeblocks/apis/dataprotection/v1alpha1" opsv1alpha1 "github.com/apecloud/kubeblocks/apis/operations/v1alpha1" + parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" workloadsv1 "github.com/apecloud/kubeblocks/apis/workloads/v1" "github.com/apecloud/kubeblocks/controllers/apps" "github.com/apecloud/kubeblocks/controllers/dataprotection" @@ -151,6 +152,10 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) model.AddScheme(workloadsv1.AddToScheme) + err = parametersv1alpha1.AddToScheme(scheme.Scheme) + Expect(err).NotTo(HaveOccurred()) + model.AddScheme(parametersv1alpha1.AddToScheme) + // +kubebuilder:scaffold:rscheme k8sClient, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) diff --git a/controllers/parameters/componentdrivenparameter_controller.go b/controllers/parameters/componentdrivenparameter_controller.go index cb368d349e7..5dea8034565 100644 --- a/controllers/parameters/componentdrivenparameter_controller.go +++ b/controllers/parameters/componentdrivenparameter_controller.go @@ -117,6 +117,7 @@ func (r *ComponentDrivenParameterReconciler) create(reqCtx intctrlutil.RequestCt return intctrlutil.CheckedRequeueWithError(err, reqCtx.Log, "") } reqCtx.Log.Info("ComponentParameter created") + intctrlutil.RecordCreatedEvent(r.Recorder, object) return intctrlutil.Reconciled() } @@ -204,7 +205,9 @@ func buildComponentParameter(reqCtx intctrlutil.RequestCtx, reader client.Reader if err = intctrlutil.SetOwnerReference(comp, parameterObj); err != nil { return nil, err } - _, err = configctrl.UpdateConfigPayload(¶meterObj.Spec, &comp.Spec, &configRender.Spec) + if configRender != nil { + _, err = configctrl.UpdateConfigPayload(¶meterObj.Spec, &comp.Spec, &configRender.Spec) + } return parameterObj, err } @@ -225,5 +228,18 @@ func (r *ComponentDrivenParameterReconciler) mergeComponentParameter(expected *p if len(dest.ConfigFileParams) == 0 && len(expected.ConfigFileParams) != 0 { dest.ConfigFileParams = expected.ConfigFileParams } + payload := expected.Payload + // TODO: removed tls + if tls, ok := dest.Payload.Data[constant.TLSPayload]; ok { + mergeTLSPayload(&payload, tls) + } + dest.Payload = payload }) } + +func mergeTLSPayload(payload *parametersv1alpha1.Payload, tls interface{}) { + if payload.Data == nil { + payload.Data = make(map[string]interface{}) + } + payload.Data[constant.TLSPayload] = tls +} diff --git a/controllers/parameters/componentparameter_controller_test.go b/controllers/parameters/componentparameter_controller_test.go index 52fa904d544..f17ede81c4f 100644 --- a/controllers/parameters/componentparameter_controller_test.go +++ b/controllers/parameters/componentparameter_controller_test.go @@ -27,9 +27,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" - appsv1alpha1 "github.com/apecloud/kubeblocks/apis/apps/v1alpha1" + parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" "github.com/apecloud/kubeblocks/pkg/configuration/core" cfgutil "github.com/apecloud/kubeblocks/pkg/configuration/util" + intctrlutil "github.com/apecloud/kubeblocks/pkg/controllerutil" testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" ) @@ -47,30 +48,21 @@ var _ = Describe("ComponentParameter Controller", func() { Name: core.GenerateComponentParameterName(clusterName, defaultCompName), Namespace: testCtx.DefaultNamespace, } - checkCfgStatus := func(phase appsv1alpha1.ConfigurationPhase) func() bool { + checkCfgStatus := func(phase parametersv1alpha1.ParameterPhase) func() bool { return func() bool { - cfg := &appsv1alpha1.Configuration{} + cfg := ¶metersv1alpha1.ComponentParameter{} Expect(k8sClient.Get(ctx, cfgKey, cfg)).Should(Succeed()) - itemStatus := cfg.Status.GetItemStatus(configSpecName) + itemStatus := intctrlutil.GetItemStatus(&cfg.Status, configSpecName) return itemStatus != nil && itemStatus.Phase == phase } } - By("wait for configuration status to be init phase.") - Eventually(checkCfgStatus(appsv1alpha1.CInitPhase)).Should(BeFalse()) - // Expect(initConfiguration(&configctrl.ResourceCtx{ - // Client: k8sClient, - // Context: ctx, - // Namespace: testCtx.DefaultNamespace, - // ClusterName: clusterName, - // ComponentName: defaultCompName, - // }, synthesizedComp, clusterObj, componentObj)).Should(Succeed()) - - Eventually(checkCfgStatus(appsv1alpha1.CFinishedPhase)).Should(BeTrue()) + Eventually(checkCfgStatus(parametersv1alpha1.CFinishedPhase)).Should(BeTrue()) By("reconfiguring parameters.") - Eventually(testapps.GetAndChangeObj(&testCtx, cfgKey, func(cfg *appsv1alpha1.Configuration) { - cfg.Spec.GetConfigurationItem(configSpecName).ConfigFileParams = map[string]appsv1alpha1.ConfigParams{ + Eventually(testapps.GetAndChangeObj(&testCtx, cfgKey, func(cfg *parametersv1alpha1.ComponentParameter) { + item := intctrlutil.GetConfigTemplateItem(&cfg.Spec, configSpecName) + item.ConfigFileParams = map[string]parametersv1alpha1.ParametersInFile{ "my.cnf": { Parameters: map[string]*string{ "max_connections": cfgutil.ToPointer("1000"), @@ -81,37 +73,15 @@ var _ = Describe("ComponentParameter Controller", func() { })).Should(Succeed()) Eventually(func(g Gomega) { - cfg := &appsv1alpha1.Configuration{} + cfg := ¶metersv1alpha1.ComponentParameter{} g.Expect(k8sClient.Get(ctx, cfgKey, cfg)).Should(Succeed()) - itemStatus := cfg.Status.GetItemStatus(configSpecName) + itemStatus := intctrlutil.GetItemStatus(&cfg.Status, configSpecName) g.Expect(itemStatus).ShouldNot(BeNil()) g.Expect(itemStatus.UpdateRevision).Should(BeEquivalentTo("2")) - g.Expect(itemStatus.Phase).Should(BeEquivalentTo(appsv1alpha1.CFinishedPhase)) + g.Expect(itemStatus.Phase).Should(BeEquivalentTo(parametersv1alpha1.CFinishedPhase)) }, time.Second*60, time.Second*1).Should(Succeed()) }) - It("Invalid component test", func() { - mockReconcileResource() - - cfgKey := client.ObjectKey{ - Name: core.GenerateComponentParameterName(clusterName, "invalid-component"), - Namespace: testCtx.DefaultNamespace, - } - - // Expect(initConfiguration(&configctrl.ResourceCtx{ - // Client: k8sClient, - // Context: ctx, - // Namespace: testCtx.DefaultNamespace, - // ClusterName: clusterName, - // ComponentName: "invalid-component", - // }, synthesizedComp, clusterObj, componentObj)).Should(Succeed()) - - Eventually(func(g Gomega) { - cfg := &appsv1alpha1.Configuration{} - g.Expect(k8sClient.Get(ctx, cfgKey, cfg)).Should(Succeed()) - g.Expect(cfg.Status.Message).Should(ContainSubstring("not found cluster component")) - }, time.Second*60, time.Second*1).Should(Succeed()) - }) }) // Context("When updating configuration with injectEnvTo", func() { diff --git a/controllers/parameters/configuration_test.go b/controllers/parameters/configuration_test.go index 39aa29d1ea5..4270b21d769 100644 --- a/controllers/parameters/configuration_test.go +++ b/controllers/parameters/configuration_test.go @@ -30,14 +30,14 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" appsv1 "github.com/apecloud/kubeblocks/apis/apps/v1" - appsv1alpha1 "github.com/apecloud/kubeblocks/apis/apps/v1alpha1" - appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" + parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" "github.com/apecloud/kubeblocks/pkg/configuration/core" "github.com/apecloud/kubeblocks/pkg/constant" "github.com/apecloud/kubeblocks/pkg/controller/builder" "github.com/apecloud/kubeblocks/pkg/controller/component" "github.com/apecloud/kubeblocks/pkg/generics" testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" + testparameters "github.com/apecloud/kubeblocks/pkg/testutil/parameters" ) const ( @@ -47,15 +47,15 @@ const ( defaultITSName = "mysql-statefulset" configSpecName = "mysql-config-tpl" configVolumeName = "mysql-config" + paramsDefName = "mysql-params-def" + pdcrName = "config-test-pdcr" cmName = "mysql-tree-node-template-8.0" ) -func mockConfigResource() (*corev1.ConfigMap, *appsv1beta1.ConfigConstraint) { +func mockConfigResource() (*corev1.ConfigMap, *parametersv1alpha1.ParametersDefinition) { By("Create a config template obj") - configmap := testapps.CreateCustomizedObj(&testCtx, - "resources/mysql-config-template.yaml", &corev1.ConfigMap{}, - testCtx.UseDefaultNamespace(), - testapps.WithLabels( + configmap := testparameters.NewComponentTemplateFactory(configSpecName, testCtx.DefaultNamespace). + AddLabels( constant.AppNameLabelKey, clusterName, constant.AppInstanceLabelKey, clusterName, constant.KBAppComponentLabelKey, defaultCompName, @@ -63,21 +63,19 @@ func mockConfigResource() (*corev1.ConfigMap, *appsv1beta1.ConfigConstraint) { constant.CMConfigurationConstraintsNameLabelKey, cmName, constant.CMConfigurationSpecProviderLabelKey, configSpecName, constant.CMConfigurationTypeLabelKey, constant.ConfigInstanceType, - ), - testapps.WithAnnotations( + ). + AddAnnotations( constant.KBParameterUpdateSourceAnnotationKey, constant.ReconfigureManagerSource, constant.ConfigurationRevision, "1", - constant.CMInsEnableRerenderTemplateKey, "true")) - - By("Create a config constraint obj") - constraint := testapps.CreateCustomizedObj(&testCtx, - "resources/mysql-config-constraint.yaml", - &appsv1beta1.ConfigConstraint{}) + constant.CMInsEnableRerenderTemplateKey, "true"). + Create(&testCtx). + GetObject() - By("check config constraint") - Eventually(testapps.CheckObj(&testCtx, client.ObjectKeyFromObject(constraint), func(g Gomega, tpl *appsv1beta1.ConfigConstraint) { - g.Expect(tpl.Status.Phase).Should(BeEquivalentTo(appsv1alpha1.AvailablePhase)) - })).Should(Succeed()) + By("Create a parameters definition obj") + paramsdef := testparameters.NewParametersDefinitionFactory(paramsDefName). + SetReloadAction(testparameters.WithNoneAction()). + Create(&testCtx). + GetObject() By("Create a configuration obj") // test-cluster-mysql-mysql-config-tpl @@ -93,25 +91,29 @@ func mockConfigResource() (*corev1.ConfigMap, *appsv1beta1.ConfigConstraint) { GetObject() Expect(testCtx.CreateObj(testCtx.Ctx, configuration)).Should(Succeed()) - return configmap, constraint + return configmap, paramsdef } -func mockReconcileResource() (*corev1.ConfigMap, *appsv1beta1.ConfigConstraint, *appsv1.Cluster, *appsv1.Component, *component.SynthesizedComponent) { - configmap, constraint := mockConfigResource() +func mockReconcileResource() (*corev1.ConfigMap, *parametersv1alpha1.ParametersDefinition, *appsv1.Cluster, *appsv1.Component, *component.SynthesizedComponent) { + configmap, paramsDef := mockConfigResource() By("Create a component definition obj and mock to available") compDefObj := testapps.NewComponentDefinitionFactory(compDefName). WithRandomName(). SetDefaultSpec(). - AddConfigTemplate(configSpecName, configmap.Name, constraint.Name, testCtx.DefaultNamespace, configVolumeName). - AddLabels(core.GenerateTPLUniqLabelKeyWithConfig(configSpecName), configmap.Name, - core.GenerateConstraintsUniqLabelKeyWithConfig(constraint.Name), constraint.Name). + AddConfigTemplate(configSpecName, configmap.Name, testCtx.DefaultNamespace, configVolumeName). Create(&testCtx). GetObject() Expect(testapps.GetAndChangeObjStatus(&testCtx, client.ObjectKeyFromObject(compDefObj), func(obj *appsv1.ComponentDefinition) { obj.Status.Phase = appsv1.AvailablePhase })()).Should(Succeed()) + testparameters.NewParametersDrivenConfigFactory(pdcrName). + SetParametersDefs(paramsDef.Name). + SetComponentDefinition(compDefObj.GetName()). + SetTemplateName(configSpecName). + Create(&testCtx) + By("Creating a cluster") clusterObj := testapps.NewClusterFactory(testCtx.DefaultNamespace, clusterName, ""). AddComponent(defaultCompName, compDefObj.GetName()). @@ -148,26 +150,9 @@ func mockReconcileResource() (*corev1.ConfigMap, *appsv1beta1.ConfigConstraint, synthesizedComp, err := component.BuildSynthesizedComponent(testCtx.Ctx, testCtx.Cli, compDefObj, compObj, clusterObj) Expect(err).ShouldNot(HaveOccurred()) - return configmap, constraint, clusterObj, compObj, synthesizedComp + return configmap, paramsDef, clusterObj, compObj, synthesizedComp } -// func initConfiguration(resourceCtx *configctrl.ResourceCtx, -// synthesizedComponent *component.SynthesizedComponent, -// clusterObj *appsv1.Cluster, -// componentObj *appsv1.Component) error { -// return configctrl.NewReloadActionBuilderHelper(configctrl.ReconcileCtx{ -// ResourceCtx: resourceCtx, -// Component: componentObj, -// SynthesizedComponent: synthesizedComponent, -// Cluster: clusterObj, -// PodSpec: synthesizedComponent.PodSpec, -// }). -// Prepare(). -// ComponentParameter(). // sync Configuration -// InitConfigRelatedObject(). -// Complete() -// } - func cleanEnv() { // must wait till resources deleted and no longer existed before the testcases start, // otherwise if later it needs to create some new resource objects with the same name, @@ -183,6 +168,8 @@ func cleanEnv() { ml := client.HasLabels{testCtx.TestObjLabelKey} // non-namespaced testapps.ClearResources(&testCtx, generics.ConfigConstraintSignature, ml) + testapps.ClearResources(&testCtx, generics.ParametersDefinitionSignature, ml) + testapps.ClearResources(&testCtx, generics.ParameterDrivenConfigRenderSignature, ml) // namespaced testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ComponentSignature, true, inNS, ml) testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ConfigMapSignature, true, inNS) @@ -190,6 +177,6 @@ func cleanEnv() { testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.InstanceSetSignature, true, inNS, ml) testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ConfigurationSignature, false, inNS, ml) testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ParametersDefinitionSignature, false, inNS, ml) - testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ComponentParameterSignature, false, inNS, ml) - testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ParameterDrivenConfigRenderSignature, false, inNS, ml) + testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ComponentParameterSignature, true, inNS, ml) + testapps.ClearResourcesWithRemoveFinalizerOption(&testCtx, generics.ParameterSignature, true, inNS, ml) } diff --git a/controllers/parameters/parametersdefinition_controller_test.go b/controllers/parameters/parametersdefinition_controller_test.go index c89df95dda2..28d2fd81e5f 100644 --- a/controllers/parameters/parametersdefinition_controller_test.go +++ b/controllers/parameters/parametersdefinition_controller_test.go @@ -22,14 +22,10 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - corev1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" appsv1alpha1 "github.com/apecloud/kubeblocks/apis/apps/v1alpha1" - appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" - cfgcore "github.com/apecloud/kubeblocks/pkg/configuration/core" "github.com/apecloud/kubeblocks/pkg/constant" intctrlutil "github.com/apecloud/kubeblocks/pkg/generics" testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" @@ -63,9 +59,10 @@ var _ = Describe("ConfigConstraint Controller", func() { Context("Create config constraint with cue validate", func() { It("Should ready", func() { By("creating a configmap and a config parametersDef") - configmap := testapps.CreateCustomizedObj(&testCtx, - "resources/mysql-config-template.yaml", &corev1.ConfigMap{}, - testCtx.UseDefaultNamespace()) + testparameters.NewComponentTemplateFactory(configSpecName, + testCtx.DefaultNamespace). + Create(&testCtx) + parametersDef := testparameters.NewParametersDefinitionFactory("mysql-parameters-8.0"). StaticParameters([]string{"automatic_sp_privileges"}). DynamicParameters([]string{"innodb_autoinc_lock_mode"}). @@ -95,16 +92,6 @@ client?: { GetObject() parametersDefKey := client.ObjectKeyFromObject(parametersDef) - By("Create a componentDefinition obj") - compDefObj := testapps.NewComponentDefinitionFactory(compDefName). - WithRandomName(). - SetDefaultSpec(). - AddConfigTemplate(configSpecName, configmap.Name, parametersDef.Name, testCtx.DefaultNamespace, configVolumeName). - AddLabels(cfgcore.GenerateTPLUniqLabelKeyWithConfig(configSpecName), configmap.Name, - cfgcore.GenerateConstraintsUniqLabelKeyWithConfig(parametersDef.Name), parametersDef.Name). - Create(&testCtx). - GetObject() - By("check ParametersDefinition(template) status and finalizer") Eventually(testapps.CheckObj(&testCtx, parametersDefKey, func(g Gomega, tpl *parametersv1alpha1.ParametersDefinition) { @@ -115,19 +102,6 @@ client?: { By("By delete ParametersDefinition") Expect(k8sClient.Delete(testCtx.Ctx, parametersDef)).Should(Succeed()) - By("check ParametersDefinition should not be deleted") - log.Log.Info("expect that ParametersDefinition is not deleted.") - Consistently(testapps.CheckObjExists(&testCtx, parametersDefKey, ¶metersv1alpha1.ParametersDefinition{}, true)).Should(Succeed()) - - By("check ParametersDefinition status should be deleting") - Eventually(testapps.CheckObj(&testCtx, parametersDefKey, - func(g Gomega, tpl *parametersv1alpha1.ParametersDefinition) { - g.Expect(tpl.Status.Phase).To(BeEquivalentTo(appsv1beta1.CCDeletingPhase)) - })).Should(Succeed()) - - By("By delete referencing componentdefinition") - Expect(k8sClient.Delete(testCtx.Ctx, compDefObj)).Should(Succeed()) - By("check ParametersDefinition should be deleted") Eventually(testapps.CheckObjExists(&testCtx, parametersDefKey, ¶metersv1alpha1.ParametersDefinition{}, false), time.Second*60, time.Second*1).Should(Succeed()) }) @@ -137,8 +111,9 @@ client?: { It("Should ready", func() { By("creating a configmap and a config constraint") - _ = testapps.CreateCustomizedObj(&testCtx, "resources/mysql-config-template.yaml", &corev1.ConfigMap{}, - testCtx.UseDefaultNamespace()) + testparameters.NewComponentTemplateFactory(configSpecName, + testCtx.DefaultNamespace). + Create(&testCtx) parametersDef := testparameters.NewParametersDefinitionFactory("mysql-parameters-8.0"). StaticParameters([]string{"automatic_sp_privileges"}). diff --git a/controllers/parameters/reconcile_task.go b/controllers/parameters/reconcile_task.go index 81492d4d1ad..06babfcf45f 100644 --- a/controllers/parameters/reconcile_task.go +++ b/controllers/parameters/reconcile_task.go @@ -22,6 +22,7 @@ package parameters import ( "context" "encoding/json" + "reflect" "strconv" corev1 "k8s.io/api/core/v1" @@ -111,14 +112,15 @@ func NewTask(item parametersv1alpha1.ConfigTemplateItemDetail, status *parameter return core.MakeError("not found config spec: %s", item.Name) } if err := resource.ConfigMap(item.Name).Complete(); err != nil { - return err + return syncImpl(taskCtx, resource, item, status, revision, nil) } // Do reconcile for config template configMap := resource.ConfigMapObj switch intctrlutil.GetConfigSpecReconcilePhase(configMap, item, status) { default: return syncStatus(configMap, status) - case parametersv1alpha1.CPendingPhase, + case parametersv1alpha1.CInitPhase, + parametersv1alpha1.CPendingPhase, parametersv1alpha1.CMergeFailedPhase: return syncImpl(taskCtx, resource, item, status, revision, configMap) case parametersv1alpha1.CCreatingPhase: @@ -177,34 +179,76 @@ func syncImpl(taskCtx *TaskContext, return nil } -func mergeAndUpdate(resourceCtx *configctrl.ResourceCtx, expected *corev1.ConfigMap, running *corev1.ConfigMap, owner client.Object, item parametersv1alpha1.ConfigTemplateItemDetail, revision string) error { - if expected == nil { - expected = running +func mergeAndUpdate(resourceCtx *configctrl.ResourceCtx, + expected *corev1.ConfigMap, + running *corev1.ConfigMap, + owner client.Object, + item parametersv1alpha1.ConfigTemplateItemDetail, + revision string) error { + switch { + case expected == nil: // not update + return update(resourceCtx.Context, resourceCtx.Client, running, running, updateReconcileObject(item, owner, revision)) + case running == nil: // cm been deleted + return create(resourceCtx.Context, resourceCtx.Client, expected, updateReconcileObject(item, owner, revision)) + default: + return update(resourceCtx.Context, resourceCtx.Client, running, running, mergedConfigmap(expected, updateReconcileObject(item, owner, revision))) } +} - configmapDeep := running.DeepCopy() - configmapDeep.Data = expected.Data - configmapDeep.Labels = intctrlutil.MergeMetadataMaps(expected.Labels, running.Labels) - configmapDeep.Annotations = intctrlutil.MergeMetadataMaps(expected.Annotations, running.Annotations) - if err := updateConfigMeta(configmapDeep, item, revision); err != nil { +func mergedConfigmap(expected *corev1.ConfigMap, setter func(*corev1.ConfigMap) error) func(*corev1.ConfigMap) error { + return func(cmObj *corev1.ConfigMap) error { + cmObj.Data = expected.Data + cmObj.Labels = intctrlutil.MergeMetadataMaps(expected.Labels, cmObj.Labels) + cmObj.Annotations = intctrlutil.MergeMetadataMaps(expected.Annotations, cmObj.Annotations) + return setter(cmObj) + } +} + +func update(ctx context.Context, cli client.Client, expected, origin *corev1.ConfigMap, setter func(*corev1.ConfigMap) error) error { + objectDeep := expected.DeepCopy() + if err := setter(objectDeep); err != nil { return err } - if !controllerutil.ContainsFinalizer(configmapDeep, constant.ConfigFinalizerName) { - controllerutil.AddFinalizer(configmapDeep, constant.ConfigFinalizerName) + if reflect.DeepEqual(objectDeep.Data, origin.Data) && + reflect.DeepEqual(objectDeep.Annotations, origin.Annotations) && + reflect.DeepEqual(objectDeep.Labels, origin.Labels) && + reflect.DeepEqual(objectDeep.Finalizers, origin.Finalizers) && + reflect.DeepEqual(objectDeep.OwnerReferences, origin.OwnerReferences) { + return nil } - if !model.IsOwnerOf(owner, configmapDeep) { - if err := intctrlutil.SetControllerReference(owner, configmapDeep); err != nil { - return err + return cli.Patch(ctx, objectDeep, client.MergeFrom(origin)) +} + +func create(ctx context.Context, cli client.Client, expected *corev1.ConfigMap, setter func(*corev1.ConfigMap) error) error { + if err := setter(expected); err != nil { + return err + } + return cli.Create(ctx, expected) +} + +func updateReconcileObject(item parametersv1alpha1.ConfigTemplateItemDetail, + owner client.Object, + revision string) func(*corev1.ConfigMap) error { + return func(cmObj *corev1.ConfigMap) error { + if !controllerutil.ContainsFinalizer(cmObj, constant.ConfigFinalizerName) { + controllerutil.AddFinalizer(cmObj, constant.ConfigFinalizerName) } + if !model.IsOwnerOf(owner, cmObj) { + if err := intctrlutil.SetControllerReference(owner, cmObj); err != nil { + return err + } + } + return updateConfigLabels(cmObj, item, revision) } - return resourceCtx.Client.Patch(resourceCtx.Context, configmapDeep, client.MergeFrom(running)) } -func updateConfigMeta(obj *corev1.ConfigMap, item parametersv1alpha1.ConfigTemplateItemDetail, revision string) error { +func updateConfigLabels(obj *corev1.ConfigMap, + item parametersv1alpha1.ConfigTemplateItemDetail, + revision string) error { if obj.Annotations == nil { obj.Annotations = make(map[string]string) } - b, err := json.Marshal(item) + b, err := json.Marshal(&item) if err != nil { return err } diff --git a/controllers/parameters/suite_test.go b/controllers/parameters/suite_test.go index 6489bb39b8d..3f29db0717c 100644 --- a/controllers/parameters/suite_test.go +++ b/controllers/parameters/suite_test.go @@ -43,6 +43,7 @@ import ( appsv1beta1 "github.com/apecloud/kubeblocks/apis/apps/v1beta1" parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" workloadsv1 "github.com/apecloud/kubeblocks/apis/workloads/v1" + "github.com/apecloud/kubeblocks/pkg/controller/model" intctrlutil "github.com/apecloud/kubeblocks/pkg/controllerutil" "github.com/apecloud/kubeblocks/pkg/testutil" viper "github.com/apecloud/kubeblocks/pkg/viperx" @@ -99,6 +100,7 @@ var _ = BeforeSuite(func() { Expect(err).NotTo(HaveOccurred()) err = workloadsv1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) + model.AddScheme(parametersv1alpha1.AddToScheme) // +kubebuilder:scaffold:scheme @@ -139,6 +141,13 @@ var _ = BeforeSuite(func() { }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) + err = (&ComponentDrivenParameterReconciler{ + Client: k8sManager.GetClient(), + Scheme: k8sManager.GetScheme(), + Recorder: k8sManager.GetEventRecorderFor("component-parameter-controller"), + }).SetupWithManager(k8sManager) + Expect(err).ToNot(HaveOccurred()) + err = (&ParametersDefinitionReconciler{ Client: k8sManager.GetClient(), Scheme: k8sManager.GetScheme(), diff --git a/pkg/controller/configuration/config_utils.go b/pkg/controller/configuration/config_utils.go index 3e8d0c2d83d..a82f4847c1f 100644 --- a/pkg/controller/configuration/config_utils.go +++ b/pkg/controller/configuration/config_utils.go @@ -26,12 +26,10 @@ import ( "strings" corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" appsv1 "github.com/apecloud/kubeblocks/apis/apps/v1" - appsv1alpha1 "github.com/apecloud/kubeblocks/apis/apps/v1alpha1" parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" cfgcm "github.com/apecloud/kubeblocks/pkg/configuration/config_manager" "github.com/apecloud/kubeblocks/pkg/configuration/core" @@ -137,16 +135,9 @@ func handleInjectEnv(ctx context.Context, if err != nil { return err } - for _, obj := range envObjs { - var cm = &corev1.ConfigMap{} - if err := cli.Get(ctx, client.ObjectKeyFromObject(obj), cm, inDataContext()); err != nil { - if !apierrors.IsNotFound(err) { - return err - } - if err := cli.Create(ctx, obj); err != nil { - return err - } + if err = intctrlutil.IgnoreIsAlreadyExists(cli.Create(ctx, obj)); err != nil { + return err } } return nil @@ -188,13 +179,6 @@ func updateCfgManagerVolumes(podSpec *corev1.PodSpec, configManager *cfgcm.CfgMa } } podSpec.Volumes = podVolumes - - // for volumeName, volume := range configManager.ConfigLazyRenderedVolumes { - // usingContainers := intctrlutil.GetPodContainerWithVolumeMount(podSpec, volumeName) - // for _, container := range usingContainers { - // container.VolumeMounts = append(container.VolumeMounts, volume) - // } - // } } func getUsingVolumesByConfigSpecs(podSpec *corev1.PodSpec, configSpecs []appsv1.ComponentTemplateSpec) ([]corev1.VolumeMount, []appsv1.ComponentTemplateSpec) { @@ -337,11 +321,3 @@ func enableHScaleTrigger(configDescs []parametersv1alpha1.ComponentConfigDescrip func enableVScaleTrigger(configDescs []parametersv1alpha1.ComponentConfigDescription) bool { return rerenderConfigEnabled(configDescs, parametersv1alpha1.ComponentVScaleType) } - -func configSetFromComponent(templates []appsv1.ComponentTemplateSpec) []string { - configSet := make([]string, 0) - for _, template := range templates { - configSet = append(configSet, template.Name) - } - return configSet -} diff --git a/pkg/controller/configuration/configuration_test.go b/pkg/controller/configuration/configuration_test.go index df13f4715f5..5eb3a1a79f4 100644 --- a/pkg/controller/configuration/configuration_test.go +++ b/pkg/controller/configuration/configuration_test.go @@ -47,7 +47,7 @@ const ( func allFieldsCompDefObj(create bool) *appsv1.ComponentDefinition { compDef := testapps.NewComponentDefinitionFactory(compDefName). SetDefaultSpec(). - AddConfigTemplate(configTemplateName, mysqlConfigName, mysqlConfigConstraintName, testCtx.DefaultNamespace, testapps.ConfVolumeName). + AddConfigTemplate(configTemplateName, mysqlConfigName, testCtx.DefaultNamespace, testapps.ConfVolumeName). AddScriptTemplate(scriptTemplateName, mysqlScriptsTemplateName, testCtx.DefaultNamespace, testapps.ScriptsVolumeName, nil). GetObject() if create { diff --git a/pkg/controller/configuration/envfrom_utils_test.go b/pkg/controller/configuration/envfrom_utils_test.go index 910620c28f4..396ff0adba5 100644 --- a/pkg/controller/configuration/envfrom_utils_test.go +++ b/pkg/controller/configuration/envfrom_utils_test.go @@ -58,7 +58,7 @@ var _ = Describe("ConfigEnvFrom test", func() { compDef = testapps.NewComponentDefinitionFactory(compDefName). SetDefaultSpec(). - AddConfigTemplate(cm.Name, cm.Name, configConstraint.Name, testCtx.DefaultNamespace, "mysql-config", testapps.DefaultMySQLContainerName). + AddConfigTemplate(cm.Name, cm.Name, testCtx.DefaultNamespace, "mysql-config"). GetObject() pvcSpec := testapps.NewPVCSpec("1Gi") diff --git a/pkg/controllerutil/config_util.go b/pkg/controllerutil/config_util.go index 5b927a71306..1d96e18b39e 100644 --- a/pkg/controllerutil/config_util.go +++ b/pkg/controllerutil/config_util.go @@ -126,8 +126,11 @@ func IsApplyConfigChanged(configMap *corev1.ConfigMap, item parametersv1alpha1.C if !ok { return false } - b, err := json.Marshal(item) - return err == nil && string(b) == lastAppliedVersion + lastItem := parametersv1alpha1.ConfigTemplateItemDetail{} + if err := json.Unmarshal([]byte(lastAppliedVersion), &lastItem); err != nil { + return false + } + return reflect.DeepEqual(lastItem, item) } // IsRerender checks if the configuration template is changed diff --git a/pkg/testutil/apps/componentdefinition_factory.go b/pkg/testutil/apps/componentdefinition_factory.go index a6ba8a556c8..7af84f844f1 100644 --- a/pkg/testutil/apps/componentdefinition_factory.go +++ b/pkg/testutil/apps/componentdefinition_factory.go @@ -169,8 +169,7 @@ func (f *MockComponentDefinitionFactory) AddServiceExt(name, serviceName string, return f } -func (f *MockComponentDefinitionFactory) AddConfigTemplate(name, configTemplateRef, configConstraintRef, - namespace, volumeName string, injectEnvTo ...string) *MockComponentDefinitionFactory { +func (f *MockComponentDefinitionFactory) AddConfigTemplate(name, configTemplateRef, namespace, volumeName string) *MockComponentDefinitionFactory { config := kbappsv1.ComponentTemplateSpec{ Name: name, TemplateRef: configTemplateRef, diff --git a/pkg/testutil/parameters/componenttemplate_factory.go b/pkg/testutil/parameters/componenttemplate_factory.go new file mode 100644 index 00000000000..b1e0a83b99b --- /dev/null +++ b/pkg/testutil/parameters/componenttemplate_factory.go @@ -0,0 +1,73 @@ +/* +Copyright (C) 2022-2024 ApeCloud Co., Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package parameters + +import ( + corev1 "k8s.io/api/core/v1" + + testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" +) + +type MockComponentTemplateFactory struct { + testapps.BaseFactory[corev1.ConfigMap, *corev1.ConfigMap, MockComponentTemplateFactory] +} + +func NewComponentTemplateFactory(name, ns string) *MockComponentTemplateFactory { + f := &MockComponentTemplateFactory{} + f.Init(ns, name, &corev1.ConfigMap{ + Data: map[string]string{ + MysqlConfigFile: mysqConfig, + }, + }, f) + return f +} + +func (f *MockComponentTemplateFactory) AddConfigFile(key, value string) *MockComponentTemplateFactory { + f.Get().Data[key] = value + return f +} + +var MysqlConfigFile = "my.cnf" +var mysqConfig = ` +[mysqld] +innodb-buffer-pool-size=512M +log-bin=master-bin +gtid_mode=OFF +consensus_auto_leader_transfer=ON + +pid-file=/var/run/mysqld/mysqld.pid +socket=/var/run/mysqld/mysqld.sock + +port=3306 +general_log=0 +server-id=1 +slow_query_log=0 + +[client] +socket=/var/run/mysqld/mysqld.sock +host=localhost +{{- if $.component.tlsConfig }} +{{- $ca_file := getCAFile }} +{{- $cert_file := getCertFile }} +{{- $key_file := getKeyFile }} +# tls +require_secure_transport=ON +ssl_ca={{ $ca_file }} +ssl_cert={{ $cert_file }} +ssl_key={{ $key_file }} +{{- end }} +` diff --git a/pkg/testutil/parameters/parameterdrivenconfigrenders_factory.go b/pkg/testutil/parameters/parameterdrivenconfigrenders_factory.go new file mode 100644 index 00000000000..c4ad562d619 --- /dev/null +++ b/pkg/testutil/parameters/parameterdrivenconfigrenders_factory.go @@ -0,0 +1,96 @@ +/* +Copyright (C) 2022-2024 ApeCloud Co., Ltd + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package parameters + +import ( + parametersv1alpha1 "github.com/apecloud/kubeblocks/apis/parameters/v1alpha1" + intctrlutil "github.com/apecloud/kubeblocks/pkg/controllerutil" + testapps "github.com/apecloud/kubeblocks/pkg/testutil/apps" +) + +type MockParametersDrivenConfigFactory struct { + testapps.BaseFactory[parametersv1alpha1.ParameterDrivenConfigRender, *parametersv1alpha1.ParameterDrivenConfigRender, MockParametersDrivenConfigFactory] +} + +func NewParametersDrivenConfigFactory(name string) *MockParametersDrivenConfigFactory { + f := &MockParametersDrivenConfigFactory{} + f.Init("", name, ¶metersv1alpha1.ParameterDrivenConfigRender{ + Spec: parametersv1alpha1.ParameterDrivenConfigRenderSpec{ + Configs: []parametersv1alpha1.ComponentConfigDescription{ + { + Name: MysqlConfigFile, + FileFormatConfig: ¶metersv1alpha1.FileFormatConfig{ + Format: parametersv1alpha1.Ini, + }, + }, + }, + }, + }, f) + return f +} + +func (f *MockParametersDrivenConfigFactory) SetParametersDefs(paramsDefs ...string) *MockParametersDrivenConfigFactory { + f.Get().Spec.ParametersDefs = paramsDefs + return f +} + +func (f *MockParametersDrivenConfigFactory) SetComponentDefinition(cmpd string) *MockParametersDrivenConfigFactory { + f.Get().Spec.ComponentDef = cmpd + return f +} + +func (f *MockParametersDrivenConfigFactory) safeGetConfigDescription(key string) *parametersv1alpha1.ComponentConfigDescription { + desc := intctrlutil.GetComponentConfigDescription(&f.Get().Spec, key) + if desc != nil { + return desc + } + f.Get().Spec.Configs = append(f.Get().Spec.Configs, parametersv1alpha1.ComponentConfigDescription{ + Name: key, + }) + return intctrlutil.GetComponentConfigDescription(&f.Get().Spec, key) +} + +func (f *MockParametersDrivenConfigFactory) SetConfigDescription(key, tpl string, formatter parametersv1alpha1.FileFormatConfig) *MockParametersDrivenConfigFactory { + desc := f.safeGetConfigDescription(key) + desc.TemplateName = tpl + desc.FileFormatConfig = formatter.DeepCopy() + return f +} + +func (f *MockParametersDrivenConfigFactory) SetTemplateName(tpl string) *MockParametersDrivenConfigFactory { + desc := f.safeGetConfigDescription(MysqlConfigFile) + desc.TemplateName = tpl + return f +} + +func (f *MockParametersDrivenConfigFactory) HScaleEnabled() *MockParametersDrivenConfigFactory { + desc := f.safeGetConfigDescription(MysqlConfigFile) + desc.ReRenderResourceTypes = append(desc.ReRenderResourceTypes, parametersv1alpha1.ComponentHScaleType) + return f +} + +func (f *MockParametersDrivenConfigFactory) VScaleEnabled() *MockParametersDrivenConfigFactory { + desc := f.safeGetConfigDescription(MysqlConfigFile) + desc.ReRenderResourceTypes = append(desc.ReRenderResourceTypes, parametersv1alpha1.ComponentVScaleType) + return f +} + +func (f *MockParametersDrivenConfigFactory) SetInjectEnv(containers ...string) *MockParametersDrivenConfigFactory { + desc := f.safeGetConfigDescription(MysqlConfigFile) + desc.InjectEnvTo = containers + return f +}