From 789834423cdedd07d9123ec72daf990174f3909a Mon Sep 17 00:00:00 2001 From: Yauheni Kaliuta Date: Mon, 30 Sep 2024 11:53:20 +0300 Subject: [PATCH] controllers, monitoring: use local variable for logger Prepare to switch to dynamic logger. It can be k8s contextual logging [1] or some internal one. Copy reconciler's logger into local variables. Just to avoid polluting the other patch with the replacements. [1] https://www.kubernetes.dev/blog/2022/05/25/contextual-logging/ Signed-off-by: Yauheni Kaliuta --- .../certconfigmapgenerator_controller.go | 19 ++-- .../datasciencecluster_controller.go | 31 +++--- .../dscinitialization_controller.go | 44 ++++---- controllers/dscinitialization/monitoring.go | 104 +++++++++--------- .../dscinitialization/servicemesh_setup.go | 12 +- controllers/dscinitialization/utils.go | 44 ++++---- .../secretgenerator_controller.go | 19 ++-- 7 files changed, 149 insertions(+), 124 deletions(-) diff --git a/controllers/certconfigmapgenerator/certconfigmapgenerator_controller.go b/controllers/certconfigmapgenerator/certconfigmapgenerator_controller.go index 87fb116326b..a3ce257dcb3 100644 --- a/controllers/certconfigmapgenerator/certconfigmapgenerator_controller.go +++ b/controllers/certconfigmapgenerator/certconfigmapgenerator_controller.go @@ -33,7 +33,8 @@ type CertConfigmapGeneratorReconciler struct { // SetupWithManager sets up the controller with the Manager. func (r *CertConfigmapGeneratorReconciler) SetupWithManager(mgr ctrl.Manager) error { - r.Log.Info("Adding controller for Configmap Generation.") + log := r.Log + log.Info("Adding controller for Configmap Generation.") return ctrl.NewControllerManagedBy(mgr). Named("cert-configmap-generator-controller"). Watches(&corev1.ConfigMap{}, handler.EnqueueRequestsFromMapFunc(r.watchTrustedCABundleConfigMapResource), builder.WithPredicates(ConfigMapChangedPredicate)). @@ -44,8 +45,9 @@ func (r *CertConfigmapGeneratorReconciler) SetupWithManager(mgr ctrl.Manager) er // Reconcile will generate new configmap, odh-trusted-ca-bundle, that includes cluster-wide trusted-ca bundle and custom // ca bundle in every new namespace created. func (r *CertConfigmapGeneratorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := r.Log // Request includes namespace that is newly created or where odh-trusted-ca-bundle configmap is updated. - r.Log.Info("Reconciling CertConfigMapGenerator.", " Request.Namespace", req.NamespacedName) + log.Info("Reconciling CertConfigMapGenerator.", " Request.Namespace", req.NamespacedName) // Get namespace instance userNamespace := &corev1.Namespace{} if err := r.Client.Get(ctx, client.ObjectKey{Name: req.Namespace}, userNamespace); err != nil { @@ -55,7 +57,7 @@ func (r *CertConfigmapGeneratorReconciler) Reconcile(ctx context.Context, req ct // Get DSCI instance dsciInstances := &dsciv1.DSCInitializationList{} if err := r.Client.List(ctx, dsciInstances); err != nil { - r.Log.Error(err, "Failed to retrieve DSCInitialization resource for CertConfigMapGenerator ", "Request.Name", req.Name) + log.Error(err, "Failed to retrieve DSCInitialization resource for CertConfigMapGenerator ", "Request.Name", req.Name) return ctrl.Result{}, err } @@ -73,10 +75,10 @@ func (r *CertConfigmapGeneratorReconciler) Reconcile(ctx context.Context, req ct // Delete odh-trusted-ca-bundle Configmap if namespace has annotation set to opt-out CA bundle injection if trustedcabundle.HasCABundleAnnotationDisabled(userNamespace) { - r.Log.Info("Namespace has opted-out of CA bundle injection using annotation", "namespace", userNamespace.Name, + log.Info("Namespace has opted-out of CA bundle injection using annotation", "namespace", userNamespace.Name, "annotation", annotation.InjectionOfCABundleAnnotatoion) if err := trustedcabundle.DeleteOdhTrustedCABundleConfigMap(ctx, r.Client, req.Namespace); client.IgnoreNotFound(err) != nil { - r.Log.Error(err, "error deleting existing configmap from namespace", "name", trustedcabundle.CAConfigMapName, "namespace", userNamespace.Name) + log.Error(err, "error deleting existing configmap from namespace", "name", trustedcabundle.CAConfigMapName, "namespace", userNamespace.Name) return reconcile.Result{}, err } @@ -85,11 +87,11 @@ func (r *CertConfigmapGeneratorReconciler) Reconcile(ctx context.Context, req ct // Add odh-trusted-ca-bundle Configmap if trustedcabundle.ShouldInjectTrustedBundle(userNamespace) { - r.Log.Info("Adding trusted CA bundle configmap to the new or existing namespace ", "namespace", userNamespace.Name, + log.Info("Adding trusted CA bundle configmap to the new or existing namespace ", "namespace", userNamespace.Name, "configmap", trustedcabundle.CAConfigMapName) trustCAData := dsciInstance.Spec.TrustedCABundle.CustomCABundle if err := trustedcabundle.CreateOdhTrustedCABundleConfigMap(ctx, r.Client, req.Namespace, trustCAData); err != nil { - r.Log.Error(err, "error adding configmap to namespace", "name", trustedcabundle.CAConfigMapName, "namespace", userNamespace.Name) + log.Error(err, "error adding configmap to namespace", "name", trustedcabundle.CAConfigMapName, "namespace", userNamespace.Name) return reconcile.Result{}, err } } @@ -108,8 +110,9 @@ func (r *CertConfigmapGeneratorReconciler) watchNamespaceResource(_ context.Cont } func (r *CertConfigmapGeneratorReconciler) watchTrustedCABundleConfigMapResource(_ context.Context, a client.Object) []reconcile.Request { + log := r.Log if a.GetName() == trustedcabundle.CAConfigMapName { - r.Log.Info("Cert configmap has been updated, start reconcile") + log.Info("Cert configmap has been updated, start reconcile") return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: a.GetName(), Namespace: a.GetNamespace()}}} } return nil diff --git a/controllers/datasciencecluster/datasciencecluster_controller.go b/controllers/datasciencecluster/datasciencecluster_controller.go index 5df185a8793..ba89a3479b9 100644 --- a/controllers/datasciencecluster/datasciencecluster_controller.go +++ b/controllers/datasciencecluster/datasciencecluster_controller.go @@ -84,12 +84,13 @@ const ( // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { //nolint:maintidx,gocyclo - r.Log.Info("Reconciling DataScienceCluster resources", "Request.Name", req.Name) + log := r.Log + log.Info("Reconciling DataScienceCluster resources", "Request.Name", req.Name) // Get information on version and platform currentOperatorRelease, err := cluster.GetRelease(ctx, r.Client) if err != nil { - r.Log.Error(err, "failed to get operator release version") + log.Error(err, "failed to get operator release version") return ctrl.Result{}, err } // Set platform @@ -129,10 +130,10 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R if controllerutil.ContainsFinalizer(instance, finalizerName) { if controllerutil.RemoveFinalizer(instance, finalizerName) { if err := r.Update(ctx, instance); err != nil { - r.Log.Info("Error to remove DSC finalizer", "error", err) + log.Info("Error to remove DSC finalizer", "error", err) return ctrl.Result{}, err } - r.Log.Info("Removed finalizer for DataScienceCluster", "name", instance.Name, "finalizer", finalizerName) + log.Info("Removed finalizer for DataScienceCluster", "name", instance.Name, "finalizer", finalizerName) } } if err := r.Client.Delete(ctx, instance, []client.DeleteOption{}...); err != nil { @@ -152,7 +153,7 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R dsciInstances := &dsciv1.DSCInitializationList{} err = r.Client.List(ctx, dsciInstances) if err != nil { - r.Log.Error(err, "Failed to retrieve DSCInitialization resource.", "DSCInitialization Request.Name", req.Name) + log.Error(err, "Failed to retrieve DSCInitialization resource.", "DSCInitialization Request.Name", req.Name) r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "Failed to retrieve DSCInitialization instance") return ctrl.Result{}, err @@ -163,7 +164,7 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R case 0: reason := status.ReconcileFailed message := "Failed to get a valid DSCInitialization instance, please create a DSCI instance" - r.Log.Info(message) + log.Info(message) instance, err = status.UpdateWithRetry(ctx, r.Client, instance, func(saved *dscv1.DataScienceCluster) { status.SetProgressingCondition(&saved.Status.Conditions, reason, message) // Patch Degraded with True status @@ -183,14 +184,14 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R if instance.ObjectMeta.DeletionTimestamp.IsZero() { if !controllerutil.ContainsFinalizer(instance, finalizerName) { - r.Log.Info("Adding finalizer for DataScienceCluster", "name", instance.Name, "finalizer", finalizerName) + log.Info("Adding finalizer for DataScienceCluster", "name", instance.Name, "finalizer", finalizerName) controllerutil.AddFinalizer(instance, finalizerName) if err := r.Update(ctx, instance); err != nil { return ctrl.Result{}, err } } } else { - r.Log.Info("Finalization DataScienceCluster start deleting instance", "name", instance.Name, "finalizer", finalizerName) + log.Info("Finalization DataScienceCluster start deleting instance", "name", instance.Name, "finalizer", finalizerName) for _, component := range allComponents { if err := component.Cleanup(ctx, r.Client, instance, r.DataScienceCluster.DSCISpec); err != nil { return ctrl.Result{}, err @@ -252,14 +253,14 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R // Process errors for components if componentErrors != nil { - r.Log.Info("DataScienceCluster Deployment Incomplete.") + log.Info("DataScienceCluster Deployment Incomplete.") instance, err = status.UpdateWithRetry(ctx, r.Client, instance, func(saved *dscv1.DataScienceCluster) { status.SetCompleteCondition(&saved.Status.Conditions, status.ReconcileCompletedWithComponentErrors, fmt.Sprintf("DataScienceCluster resource reconciled with component errors: %v", componentErrors)) saved.Status.Phase = status.PhaseReady }) if err != nil { - r.Log.Error(err, "failed to update DataScienceCluster conditions with incompleted reconciliation") + log.Error(err, "failed to update DataScienceCluster conditions with incompleted reconciliation") return ctrl.Result{}, err } @@ -276,12 +277,12 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R }) if err != nil { - r.Log.Error(err, "failed to update DataScienceCluster conditions after successfully completed reconciliation") + log.Error(err, "failed to update DataScienceCluster conditions after successfully completed reconciliation") return ctrl.Result{}, err } - r.Log.Info("DataScienceCluster Deployment Completed.") + log.Info("DataScienceCluster Deployment Completed.") r.Recorder.Eventf(instance, corev1.EventTypeNormal, "DataScienceClusterCreationSuccessful", "DataScienceCluster instance %s created and deployed successfully", instance.Name) @@ -291,6 +292,7 @@ func (r *DataScienceClusterReconciler) Reconcile(ctx context.Context, req ctrl.R func (r *DataScienceClusterReconciler) reconcileSubComponent(ctx context.Context, instance *dscv1.DataScienceCluster, platform cluster.Platform, component components.ComponentInterface, ) (*dscv1.DataScienceCluster, error) { + log := r.Log componentName := component.GetComponentName() enabled := component.GetManagementState() == operatorv1.Managed @@ -312,7 +314,7 @@ func (r *DataScienceClusterReconciler) reconcileSubComponent(ctx context.Context } } // Reconcile component - componentLogger := newComponentLogger(r.Log, componentName, r.DataScienceCluster.DSCISpec) + componentLogger := newComponentLogger(log, componentName, r.DataScienceCluster.DSCISpec) err := component.ReconcileComponent(ctx, r.Client, componentLogger, instance, r.DataScienceCluster.DSCISpec, platform, installedComponentValue) // TODO: replace this hack with a full refactor of component status in the future @@ -373,7 +375,8 @@ func newComponentLogger(logger logr.Logger, componentName string, dscispec *dsci } func (r *DataScienceClusterReconciler) reportError(err error, instance *dscv1.DataScienceCluster, message string) *dscv1.DataScienceCluster { - r.Log.Error(err, message, "instance.Name", instance.Name) + log := r.Log + log.Error(err, message, "instance.Name", instance.Name) r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DataScienceClusterReconcileError", "%s for instance %s", message, instance.Name) return instance diff --git a/controllers/dscinitialization/dscinitialization_controller.go b/controllers/dscinitialization/dscinitialization_controller.go index 9c2efff2610..5c1a4bc9b20 100644 --- a/controllers/dscinitialization/dscinitialization_controller.go +++ b/controllers/dscinitialization/dscinitialization_controller.go @@ -76,11 +76,12 @@ type DSCInitializationReconciler struct { // Reconcile contains controller logic specific to DSCInitialization instance updates. func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { //nolint:funlen,gocyclo,maintidx - r.Log.Info("Reconciling DSCInitialization.", "DSCInitialization Request.Name", req.Name) + log := r.Log + log.Info("Reconciling DSCInitialization.", "DSCInitialization Request.Name", req.Name) currentOperatorRelease, err := cluster.GetRelease(ctx, r.Client) if err != nil { - r.Log.Error(err, "failed to get operator release version") + log.Error(err, "failed to get operator release version") return ctrl.Result{}, err } // Set platform @@ -88,7 +89,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re instances := &dsciv1.DSCInitializationList{} if err := r.Client.List(ctx, instances); err != nil { - r.Log.Error(err, "Failed to retrieve DSCInitialization resource.", "DSCInitialization Request.Name", req.Name) + log.Error(err, "Failed to retrieve DSCInitialization resource.", "DSCInitialization Request.Name", req.Name) r.Recorder.Eventf(instances, corev1.EventTypeWarning, "DSCInitializationReconcileError", "Failed to retrieve DSCInitialization instance") return ctrl.Result{}, err @@ -104,14 +105,14 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re if instance.ObjectMeta.DeletionTimestamp.IsZero() { if !controllerutil.ContainsFinalizer(instance, finalizerName) { - r.Log.Info("Adding finalizer for DSCInitialization", "name", instance.Name, "finalizer", finalizerName) + log.Info("Adding finalizer for DSCInitialization", "name", instance.Name, "finalizer", finalizerName) controllerutil.AddFinalizer(instance, finalizerName) if err := r.Update(ctx, instance); err != nil { return ctrl.Result{}, err } } } else { - r.Log.Info("Finalization DSCInitialization start deleting instance", "name", instance.Name, "finalizer", finalizerName) + log.Info("Finalization DSCInitialization start deleting instance", "name", instance.Name, "finalizer", finalizerName) if err := r.removeServiceMesh(ctx, instance); err != nil { return reconcile.Result{}, err } @@ -130,7 +131,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re return nil }) if err != nil { - r.Log.Error(err, "Failed to remove finalizer when deleting DSCInitialization instance") + log.Error(err, "Failed to remove finalizer when deleting DSCInitialization instance") return ctrl.Result{}, err } @@ -147,7 +148,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re saved.Status.Release = currentOperatorRelease }) if err != nil { - r.Log.Error(err, "Failed to add conditions to status of DSCInitialization resource.", "DSCInitialization", req.Namespace, "Request.Name", req.Name) + log.Error(err, "Failed to add conditions to status of DSCInitialization resource.", "DSCInitialization", req.Namespace, "Request.Name", req.Name) r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "%s for instance %s", message, instance.Name) @@ -164,7 +165,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re } // Check ManagementState to verify if odh-trusted-ca-bundle Configmap should be configured for namespaces - if err := trustedcabundle.ConfigureTrustedCABundle(ctx, r.Client, r.Log, instance, managementStateChangeTrustedCA); err != nil { + if err := trustedcabundle.ConfigureTrustedCABundle(ctx, r.Client, log, instance, managementStateChangeTrustedCA); err != nil { return reconcile.Result{}, err } managementStateChangeTrustedCA = false @@ -172,7 +173,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re switch req.Name { case "prometheus": // prometheus configmap if instance.Spec.Monitoring.ManagementState == operatorv1.Managed && platform == cluster.ManagedRhods { - r.Log.Info("Monitoring enabled to restart deployment", "cluster", "Managed Service Mode") + log.Info("Monitoring enabled to restart deployment", "cluster", "Managed Service Mode") err := r.configureManagedMonitoring(ctx, instance, "updates") if err != nil { return reconcile.Result{}, err @@ -182,7 +183,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re return ctrl.Result{}, nil case "addon-managed-odh-parameters": if instance.Spec.Monitoring.ManagementState == operatorv1.Managed && platform == cluster.ManagedRhods { - r.Log.Info("Monitoring enabled when notification updated", "cluster", "Managed Service Mode") + log.Info("Monitoring enabled when notification updated", "cluster", "Managed Service Mode") err := r.configureManagedMonitoring(ctx, instance, "updates") if err != nil { return reconcile.Result{}, err @@ -192,7 +193,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re return ctrl.Result{}, nil case "backup": // revert back to the original prometheus.yml if instance.Spec.Monitoring.ManagementState == operatorv1.Managed && platform == cluster.ManagedRhods { - r.Log.Info("Monitoring enabled to restore back", "cluster", "Managed Service Mode") + log.Info("Monitoring enabled to restore back", "cluster", "Managed Service Mode") err := r.configureManagedMonitoring(ctx, instance, "revertbackup") if err != nil { return reconcile.Result{}, err @@ -208,7 +209,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re return reconcile.Result{}, err } if instance.Spec.Monitoring.ManagementState == operatorv1.Managed { - r.Log.Info("Monitoring enabled, won't apply changes", "cluster", "Self-Managed RHODS Mode") + log.Info("Monitoring enabled, won't apply changes", "cluster", "Self-Managed RHODS Mode") err = r.configureCommonMonitoring(ctx, instance) if err != nil { return reconcile.Result{}, err @@ -218,13 +219,13 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re osdConfigsPath := filepath.Join(deploy.DefaultManifestPath, "osd-configs") err = deploy.DeployManifestsFromPath(ctx, r.Client, instance, osdConfigsPath, r.ApplicationsNamespace, "osd", true) if err != nil { - r.Log.Error(err, "Failed to apply osd specific configs from manifests", "Manifests path", osdConfigsPath) + log.Error(err, "Failed to apply osd specific configs from manifests", "Manifests path", osdConfigsPath) r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "Failed to apply "+osdConfigsPath) return reconcile.Result{}, err } if instance.Spec.Monitoring.ManagementState == operatorv1.Managed { - r.Log.Info("Monitoring enabled in initialization stage", "cluster", "Managed Service Mode") + log.Info("Monitoring enabled in initialization stage", "cluster", "Managed Service Mode") err := r.configureManagedMonitoring(ctx, instance, "init") if err != nil { return reconcile.Result{}, err @@ -240,7 +241,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re return reconcile.Result{}, err } if instance.Spec.Monitoring.ManagementState == operatorv1.Managed { - r.Log.Info("Monitoring enabled, won't apply changes", "cluster", "ODH Mode") + log.Info("Monitoring enabled, won't apply changes", "cluster", "ODH Mode") } } @@ -255,7 +256,7 @@ func (r *DSCInitializationReconciler) Reconcile(ctx context.Context, req ctrl.Re saved.Status.Phase = status.PhaseReady }) if err != nil { - r.Log.Error(err, "failed to update DSCInitialization status after successfully completed reconciliation") + log.Error(err, "failed to update DSCInitialization status after successfully completed reconciliation") r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "Failed to update DSCInitialization status") } @@ -365,8 +366,9 @@ var dsciPredicateStateChangeTrustedCA = predicate.Funcs{ } func (r *DSCInitializationReconciler) watchMonitoringConfigMapResource(_ context.Context, a client.Object) []reconcile.Request { + log := r.Log if a.GetName() == "prometheus" && a.GetNamespace() == "redhat-ods-monitoring" { - r.Log.Info("Found monitoring configmap has updated, start reconcile") + log.Info("Found monitoring configmap has updated, start reconcile") return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: "prometheus", Namespace: "redhat-ods-monitoring"}}} } @@ -374,13 +376,14 @@ func (r *DSCInitializationReconciler) watchMonitoringConfigMapResource(_ context } func (r *DSCInitializationReconciler) watchMonitoringSecretResource(_ context.Context, a client.Object) []reconcile.Request { + log := r.Log operatorNs, err := cluster.GetOperatorNamespace() if err != nil { return nil } if a.GetName() == "addon-managed-odh-parameters" && a.GetNamespace() == operatorNs { - r.Log.Info("Found monitoring secret has updated, start reconcile") + log.Info("Found monitoring secret has updated, start reconcile") return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: "addon-managed-odh-parameters", Namespace: operatorNs}}} } @@ -388,14 +391,15 @@ func (r *DSCInitializationReconciler) watchMonitoringSecretResource(_ context.Co } func (r *DSCInitializationReconciler) watchDSCResource(ctx context.Context) []reconcile.Request { + log := r.Log instanceList := &dscv1.DataScienceClusterList{} if err := r.Client.List(ctx, instanceList); err != nil { // do not handle if cannot get list - r.Log.Error(err, "Failed to get DataScienceClusterList") + log.Error(err, "Failed to get DataScienceClusterList") return nil } if len(instanceList.Items) == 0 && !upgrade.HasDeleteConfigMap(ctx, r.Client) { - r.Log.Info("Found no DSC instance in cluster but not in uninstalltion process, reset monitoring stack config") + log.Info("Found no DSC instance in cluster but not in uninstalltion process, reset monitoring stack config") return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: "backup"}}} } diff --git a/controllers/dscinitialization/monitoring.go b/controllers/dscinitialization/monitoring.go index 26946bdcd4c..cc5b7112175 100644 --- a/controllers/dscinitialization/monitoring.go +++ b/controllers/dscinitialization/monitoring.go @@ -39,6 +39,7 @@ var ( // only when reconcile on DSCI CR, initial set to true // if reconcile from monitoring, initial set to false, skip blackbox and rolebinding. func (r *DSCInitializationReconciler) configureManagedMonitoring(ctx context.Context, dscInit *dsciv1.DSCInitialization, initial string) error { + log := r.Log if initial == "init" { // configure Blackbox exporter if err := configureBlackboxExporter(ctx, dscInit, r); err != nil { @@ -61,7 +62,7 @@ func (r *DSCInitializationReconciler) configureManagedMonitoring(ctx context.Con "(.*)-(.*)trustyai(.*).rules": "", }) if err != nil { - r.Log.Error(err, "error to remove previous enabled component rules") + log.Error(err, "error to remove previous enabled component rules") return err } } @@ -83,34 +84,35 @@ func (r *DSCInitializationReconciler) configureManagedMonitoring(ctx context.Con } } - r.Log.Info("Success: finish config managed monitoring stack!") + log.Info("Success: finish config managed monitoring stack!") return nil } func configureAlertManager(ctx context.Context, dsciInit *dsciv1.DSCInitialization, r *DSCInitializationReconciler) error { + log := r.Log // Get Deadmansnitch secret deadmansnitchSecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-deadmanssnitch", dsciInit.Spec.Monitoring.Namespace) if err != nil { - r.Log.Error(err, "error getting deadmansnitch secret from namespace "+dsciInit.Spec.Monitoring.Namespace) + log.Error(err, "error getting deadmansnitch secret from namespace "+dsciInit.Spec.Monitoring.Namespace) return err } - // r.Log.Info("Success: got deadmansnitch secret") + // log.Info("Success: got deadmansnitch secret") // Get PagerDuty Secret pagerDutySecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-pagerduty", dsciInit.Spec.Monitoring.Namespace) if err != nil { - r.Log.Error(err, "error getting pagerduty secret from namespace "+dsciInit.Spec.Monitoring.Namespace) + log.Error(err, "error getting pagerduty secret from namespace "+dsciInit.Spec.Monitoring.Namespace) return err } - // r.Log.Info("Success: got pagerduty secret") + // log.Info("Success: got pagerduty secret") // Get Smtp Secret smtpSecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-smtp", dsciInit.Spec.Monitoring.Namespace) if err != nil { - r.Log.Error(err, "error getting smtp secret from namespace "+dsciInit.Spec.Monitoring.Namespace) + log.Error(err, "error getting smtp secret from namespace "+dsciInit.Spec.Monitoring.Namespace) return err } - // r.Log.Info("Success: got smtp secret") + // log.Info("Success: got smtp secret") // Replace variables in alertmanager configmap for the initial time // TODO: Following variables can later be exposed by the API @@ -124,10 +126,10 @@ func configureAlertManager(ctx context.Context, dsciInit *dsciv1.DSCInitializati "": string(smtpSecret.Data["password"]), }) if err != nil { - r.Log.Error(err, "error to inject data to alertmanager-configs.yaml") + log.Error(err, "error to inject data to alertmanager-configs.yaml") return err } - // r.Log.Info("Success: inject alertmanage-configs.yaml") + // log.Info("Success: inject alertmanage-configs.yaml") // special handling for dev-mod consolelinkDomain, err := cluster.GetDomain(ctx, r.Client) @@ -135,33 +137,33 @@ func configureAlertManager(ctx context.Context, dsciInit *dsciv1.DSCInitializati return fmt.Errorf("error getting console route URL : %w", err) } if strings.Contains(consolelinkDomain, "devshift.org") { - r.Log.Info("inject alertmanage-configs.yaml for dev mode1") + log.Info("inject alertmanage-configs.yaml for dev mode1") err = common.ReplaceStringsInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"), map[string]string{ "@devshift.net": "@rhmw.io", }) if err != nil { - r.Log.Error(err, "error to replace data for dev mode1 to alertmanager-configs.yaml") + log.Error(err, "error to replace data for dev mode1 to alertmanager-configs.yaml") return err } } if strings.Contains(consolelinkDomain, "aisrhods") { - r.Log.Info("inject alertmanage-configs.yaml for dev mode2") + log.Info("inject alertmanage-configs.yaml for dev mode2") err = common.ReplaceStringsInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"), map[string]string{ "receiver: PagerDuty": "receiver: alerts-sink", }) if err != nil { - r.Log.Error(err, "error to replace data for dev mode2 to alertmanager-configs.yaml") + log.Error(err, "error to replace data for dev mode2 to alertmanager-configs.yaml") return err } } - // r.Log.Info("Success: inject alertmanage-configs.yaml for dev mode") + // log.Info("Success: inject alertmanage-configs.yaml for dev mode") operatorNs, err := cluster.GetOperatorNamespace() if err != nil { - r.Log.Error(err, "error getting operator namespace for smtp secret") + log.Error(err, "error getting operator namespace for smtp secret") return err } @@ -170,41 +172,42 @@ func configureAlertManager(ctx context.Context, dsciInit *dsciv1.DSCInitializati if err != nil { return fmt.Errorf("error getting smtp receiver email secret: %w", err) } - // r.Log.Info("Success: got smpt email secret") + // log.Info("Success: got smpt email secret") // replace smtpEmailSecret in alertmanager-configs.yaml if err = common.MatchLineInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"), map[string]string{ "- to: ": "- to: " + string(smtpEmailSecret.Data["notification-email"]), }, ); err != nil { - r.Log.Error(err, "error to update with new notification-email") + log.Error(err, "error to update with new notification-email") return err } - // r.Log.Info("Success: update alertmanage-configs.yaml with email") + // log.Info("Success: update alertmanage-configs.yaml with email") err = deploy.DeployManifestsFromPath(ctx, r.Client, dsciInit, alertManagerPath, dsciInit.Spec.Monitoring.Namespace, "alertmanager", true) if err != nil { - r.Log.Error(err, "error to deploy manifests", "path", alertManagerPath) + log.Error(err, "error to deploy manifests", "path", alertManagerPath) return err } - // r.Log.Info("Success: update alertmanager with manifests") + // log.Info("Success: update alertmanager with manifests") // Create alertmanager-proxy secret if err := createMonitoringProxySecret(ctx, r.Client, "alertmanager-proxy", dsciInit); err != nil { - r.Log.Error(err, "error to create secret alertmanager-proxy") + log.Error(err, "error to create secret alertmanager-proxy") return err } - // r.Log.Info("Success: create alertmanager-proxy secret") + // log.Info("Success: create alertmanager-proxy secret") return nil } func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization, r *DSCInitializationReconciler) error { + log := r.Log // Update rolebinding-viewer err := common.ReplaceStringsInFile(filepath.Join(prometheusManifestsPath, "prometheus-rolebinding-viewer.yaml"), map[string]string{ "": dsciInit.Spec.Monitoring.Namespace, }) if err != nil { - r.Log.Error(err, "error to inject data to prometheus-rolebinding-viewer.yaml") + log.Error(err, "error to inject data to prometheus-rolebinding-viewer.yaml") return err } // Update prometheus-config for dashboard, dsp and workbench @@ -219,7 +222,7 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization "": consolelinkDomain, }) if err != nil { - r.Log.Error(err, "error to inject data to prometheus-configs.yaml") + log.Error(err, "error to inject data to prometheus-configs.yaml") return err } @@ -232,10 +235,10 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization dsciInit.Spec.Monitoring.Namespace, "prometheus", dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil { - r.Log.Error(err, "error to deploy manifests for prometheus configs", "path", prometheusConfigPath) + log.Error(err, "error to deploy manifests for prometheus configs", "path", prometheusConfigPath) return err } - // r.Log.Info("Success: create prometheus configmap 'prometheus'") + // log.Info("Success: create prometheus configmap 'prometheus'") // Get prometheus configmap prometheusConfigMap := &corev1.ConfigMap{} @@ -244,18 +247,18 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization Name: "prometheus", }, prometheusConfigMap) if err != nil { - r.Log.Error(err, "error to get configmap 'prometheus'") + log.Error(err, "error to get configmap 'prometheus'") return err } - // r.Log.Info("Success: got prometheus configmap") + // log.Info("Success: got prometheus configmap") // Get encoded prometheus data from configmap 'prometheus' prometheusData, err := common.GetMonitoringData(fmt.Sprint(prometheusConfigMap.Data)) if err != nil { - r.Log.Error(err, "error to get prometheus data") + log.Error(err, "error to get prometheus data") return err } - // r.Log.Info("Success: read encoded prometheus data from prometheus.yml in configmap") + // log.Info("Success: read encoded prometheus data from prometheus.yml in configmap") // Get alertmanager host alertmanagerRoute := &routev1.Route{} @@ -264,10 +267,10 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization Name: "alertmanager", }, alertmanagerRoute) if err != nil { - r.Log.Error(err, "error to get alertmanager route") + log.Error(err, "error to get alertmanager route") return err } - // r.Log.Info("Success: got alertmanager route") + // log.Info("Success: got alertmanager route") // Get alertmanager configmap alertManagerConfigMap := &corev1.ConfigMap{} @@ -276,17 +279,17 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization Name: "alertmanager", }, alertManagerConfigMap) if err != nil { - r.Log.Error(err, "error to get configmap 'alertmanager'") + log.Error(err, "error to get configmap 'alertmanager'") return err } - // r.Log.Info("Success: got configmap 'alertmanager'") + // log.Info("Success: got configmap 'alertmanager'") alertmanagerData, err := common.GetMonitoringData(alertManagerConfigMap.Data["alertmanager.yml"]) if err != nil { - r.Log.Error(err, "error to get encoded alertmanager data from alertmanager.yml") + log.Error(err, "error to get encoded alertmanager data from alertmanager.yml") return err } - // r.Log.Info("Success: read alertmanager data from alertmanage.yml") + // log.Info("Success: read alertmanager data from alertmanage.yml") // Update prometheus deployment with alertmanager and prometheus data err = common.ReplaceStringsInFile(filepath.Join(prometheusManifestsPath, "prometheus-deployment.yaml"), @@ -294,20 +297,20 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization "": alertmanagerRoute.Spec.Host, }) if err != nil { - r.Log.Error(err, "error to inject set_alertmanager_host to prometheus-deployment.yaml") + log.Error(err, "error to inject set_alertmanager_host to prometheus-deployment.yaml") return err } - // r.Log.Info("Success: update set_alertmanager_host in prometheus-deployment.yaml") + // log.Info("Success: update set_alertmanager_host in prometheus-deployment.yaml") err = common.MatchLineInFile(filepath.Join(prometheusManifestsPath, "prometheus-deployment.yaml"), map[string]string{ "alertmanager: ": "alertmanager: " + alertmanagerData, "prometheus: ": "prometheus: " + prometheusData, }) if err != nil { - r.Log.Error(err, "error to update annotations in prometheus-deployment.yaml") + log.Error(err, "error to update annotations in prometheus-deployment.yaml") return err } - // r.Log.Info("Success: update annotations in prometheus-deployment.yaml") + // log.Info("Success: update annotations in prometheus-deployment.yaml") // final apply prometheus manifests including prometheus deployment // Check if Prometheus deployment from legacy version exists(check for initContainer) @@ -332,7 +335,7 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization err = deploy.DeployManifestsFromPath(ctx, r.Client, dsciInit, prometheusManifestsPath, dsciInit.Spec.Monitoring.Namespace, "prometheus", true) if err != nil { - r.Log.Error(err, "error to deploy manifests for prometheus", "path", prometheusManifestsPath) + log.Error(err, "error to deploy manifests for prometheus", "path", prometheusManifestsPath) return err } @@ -340,11 +343,12 @@ func configurePrometheus(ctx context.Context, dsciInit *dsciv1.DSCInitialization if err := createMonitoringProxySecret(ctx, r.Client, "prometheus-proxy", dsciInit); err != nil { return err } - // r.Log.Info("Success: create prometheus-proxy secret") + // log.Info("Success: create prometheus-proxy secret") return nil } func configureBlackboxExporter(ctx context.Context, dsciInit *dsciv1.DSCInitialization, r *DSCInitializationReconciler) error { + log := r.Log consoleRoute := &routev1.Route{} err := r.Client.Get(ctx, client.ObjectKey{Name: "console", Namespace: "openshift-console"}, consoleRoute) if err != nil { @@ -380,7 +384,7 @@ func configureBlackboxExporter(ctx context.Context, dsciInit *dsciv1.DSCInitiali dsciInit.Spec.Monitoring.Namespace, "blackbox-exporter", dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil { - r.Log.Error(err, "error to deploy manifests: %w", "error", err) + log.Error(err, "error to deploy manifests: %w", "error", err) return err } } else { @@ -390,7 +394,7 @@ func configureBlackboxExporter(ctx context.Context, dsciInit *dsciv1.DSCInitiali dsciInit.Spec.Monitoring.Namespace, "blackbox-exporter", dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil { - r.Log.Error(err, "error to deploy manifests: %w", "error", err) + log.Error(err, "error to deploy manifests: %w", "error", err) return err } } @@ -434,6 +438,7 @@ func createMonitoringProxySecret(ctx context.Context, cli client.Client, name st } func (r *DSCInitializationReconciler) configureSegmentIO(ctx context.Context, dsciInit *dsciv1.DSCInitialization) error { + log := r.Log // create segment.io only when configmap does not exist in the cluster segmentioConfigMap := &corev1.ConfigMap{} if err := r.Client.Get(ctx, client.ObjectKey{ @@ -441,7 +446,7 @@ func (r *DSCInitializationReconciler) configureSegmentIO(ctx context.Context, ds Name: "odh-segment-key-config", }, segmentioConfigMap); err != nil { if !k8serr.IsNotFound(err) { - r.Log.Error(err, "error to get configmap 'odh-segment-key-config'") + log.Error(err, "error to get configmap 'odh-segment-key-config'") return err } else { segmentPath := filepath.Join(deploy.DefaultManifestPath, "monitoring", "segment") @@ -453,7 +458,7 @@ func (r *DSCInitializationReconciler) configureSegmentIO(ctx context.Context, ds dsciInit.Spec.ApplicationsNamespace, "segment-io", dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil { - r.Log.Error(err, "error to deploy manifests under "+segmentPath) + log.Error(err, "error to deploy manifests under "+segmentPath) return err } } @@ -462,6 +467,7 @@ func (r *DSCInitializationReconciler) configureSegmentIO(ctx context.Context, ds } func (r *DSCInitializationReconciler) configureCommonMonitoring(ctx context.Context, dsciInit *dsciv1.DSCInitialization) error { + log := r.Log if err := r.configureSegmentIO(ctx, dsciInit); err != nil { return err } @@ -473,7 +479,7 @@ func (r *DSCInitializationReconciler) configureCommonMonitoring(ctx context.Cont "": dsciInit.Spec.Monitoring.Namespace, }) if err != nil { - r.Log.Error(err, "error to inject namespace to common monitoring") + log.Error(err, "error to inject namespace to common monitoring") return err } @@ -486,7 +492,7 @@ func (r *DSCInitializationReconciler) configureCommonMonitoring(ctx context.Cont "", "monitoring-base", dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil { - r.Log.Error(err, "error to deploy manifests under "+monitoringBasePath) + log.Error(err, "error to deploy manifests under "+monitoringBasePath) return err } return nil diff --git a/controllers/dscinitialization/servicemesh_setup.go b/controllers/dscinitialization/servicemesh_setup.go index 4e45b96a0ca..aef6daba07b 100644 --- a/controllers/dscinitialization/servicemesh_setup.go +++ b/controllers/dscinitialization/servicemesh_setup.go @@ -19,11 +19,12 @@ import ( ) func (r *DSCInitializationReconciler) configureServiceMesh(ctx context.Context, instance *dsciv1.DSCInitialization) error { + log := r.Log serviceMeshManagementState := operatorv1.Removed if instance.Spec.ServiceMesh != nil { serviceMeshManagementState = instance.Spec.ServiceMesh.ManagementState } else { - r.Log.Info("ServiceMesh is not configured in DSCI, same as default to 'Removed'") + log.Info("ServiceMesh is not configured in DSCI, same as default to 'Removed'") } switch serviceMeshManagementState { @@ -42,16 +43,16 @@ func (r *DSCInitializationReconciler) configureServiceMesh(ctx context.Context, for _, capability := range capabilities { capabilityErr := capability.Apply(ctx, r.Client) if capabilityErr != nil { - r.Log.Error(capabilityErr, "failed applying service mesh resources") + log.Error(capabilityErr, "failed applying service mesh resources") r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "failed applying service mesh resources") return capabilityErr } } case operatorv1.Unmanaged: - r.Log.Info("ServiceMesh CR is not configured by the operator, we won't do anything") + log.Info("ServiceMesh CR is not configured by the operator, we won't do anything") case operatorv1.Removed: - r.Log.Info("existing ServiceMesh CR (owned by operator) will be removed") + log.Info("existing ServiceMesh CR (owned by operator) will be removed") if err := r.removeServiceMesh(ctx, instance); err != nil { return err } @@ -61,6 +62,7 @@ func (r *DSCInitializationReconciler) configureServiceMesh(ctx context.Context, } func (r *DSCInitializationReconciler) removeServiceMesh(ctx context.Context, instance *dsciv1.DSCInitialization) error { + log := r.Log // on condition of Managed, do not handle Removed when set to Removed it trigger DSCI reconcile to clean up if instance.Spec.ServiceMesh == nil { return nil @@ -80,7 +82,7 @@ func (r *DSCInitializationReconciler) removeServiceMesh(ctx context.Context, ins for _, capability := range capabilities { capabilityErr := capability.Delete(ctx, r.Client) if capabilityErr != nil { - r.Log.Error(capabilityErr, "failed deleting service mesh resources") + log.Error(capabilityErr, "failed deleting service mesh resources") r.Recorder.Eventf(instance, corev1.EventTypeWarning, "DSCInitializationReconcileError", "failed deleting service mesh resources") return capabilityErr diff --git a/controllers/dscinitialization/utils.go b/controllers/dscinitialization/utils.go index ccf1590f6ac..b2990c68ef3 100644 --- a/controllers/dscinitialization/utils.go +++ b/controllers/dscinitialization/utils.go @@ -37,6 +37,7 @@ var ( // - Network Policies 'opendatahub' that allow traffic between the ODH namespaces // - RoleBinding 'opendatahub'. func (r *DSCInitializationReconciler) createOdhNamespace(ctx context.Context, dscInit *dsciv1.DSCInitialization, name string, platform cluster.Platform) error { + log := r.Log // Expected application namespace for the given name desiredNamespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ @@ -53,25 +54,25 @@ func (r *DSCInitializationReconciler) createOdhNamespace(ctx context.Context, ds err := r.Get(ctx, client.ObjectKey{Name: name}, foundNamespace) if err != nil { if k8serr.IsNotFound(err) { - r.Log.Info("Creating namespace", "name", name) + log.Info("Creating namespace", "name", name) // Set Controller reference // err = ctrl.SetControllerReference(dscInit, desiredNamespace, r.Scheme) // if err != nil { - // r.Log.Error(err, "Unable to add OwnerReference to the Namespace") + // log.Error(err, "Unable to add OwnerReference to the Namespace") // return err // } err = r.Create(ctx, desiredNamespace) if err != nil && !k8serr.IsAlreadyExists(err) { - r.Log.Error(err, "Unable to create namespace", "name", name) + log.Error(err, "Unable to create namespace", "name", name) return err } } else { - r.Log.Error(err, "Unable to fetch namespace", "name", name) + log.Error(err, "Unable to fetch namespace", "name", name) return err } // Patch Application Namespace if it exists } else if dscInit.Spec.Monitoring.ManagementState == operatorv1.Managed { - r.Log.Info("Patching application namespace for Managed cluster", "name", name) + log.Info("Patching application namespace for Managed cluster", "name", name) labelPatch := `{"metadata":{"labels":{"openshift.io/cluster-monitoring":"true","pod-security.kubernetes.io/enforce":"baseline","opendatahub.io/generated-namespace": "true"}}}` err = r.Patch(ctx, foundNamespace, client.RawPatch(types.MergePatchType, []byte(labelPatch))) @@ -86,7 +87,7 @@ func (r *DSCInitializationReconciler) createOdhNamespace(ctx context.Context, ds err := r.Get(ctx, client.ObjectKey{Name: monitoringName}, foundMonitoringNamespace) if err != nil { if k8serr.IsNotFound(err) { - r.Log.Info("Not found monitoring namespace", "name", monitoringName) + log.Info("Not found monitoring namespace", "name", monitoringName) desiredMonitoringNamespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: monitoringName, @@ -99,15 +100,15 @@ func (r *DSCInitializationReconciler) createOdhNamespace(ctx context.Context, ds } err = r.Create(ctx, desiredMonitoringNamespace) if err != nil && !k8serr.IsAlreadyExists(err) { - r.Log.Error(err, "Unable to create namespace", "name", monitoringName) + log.Error(err, "Unable to create namespace", "name", monitoringName) return err } } else { - r.Log.Error(err, "Unable to fetch monitoring namespace", "name", monitoringName) + log.Error(err, "Unable to fetch monitoring namespace", "name", monitoringName) return err } } else { // force to patch monitoring namespace with label for cluster-monitoring - r.Log.Info("Patching monitoring namespace", "name", monitoringName) + log.Info("Patching monitoring namespace", "name", monitoringName) labelPatch := `{"metadata":{"labels":{"openshift.io/cluster-monitoring":"true", "pod-security.kubernetes.io/enforce":"baseline","opendatahub.io/generated-namespace": "true"}}}` err = r.Patch(ctx, foundMonitoringNamespace, client.RawPatch(types.MergePatchType, []byte(labelPatch))) @@ -120,27 +121,28 @@ func (r *DSCInitializationReconciler) createOdhNamespace(ctx context.Context, ds // Create default NetworkPolicy for the namespace err = r.reconcileDefaultNetworkPolicy(ctx, name, dscInit, platform) if err != nil { - r.Log.Error(err, "error reconciling network policy ", "name", name) + log.Error(err, "error reconciling network policy ", "name", name) return err } // Create odh-common-config Configmap for the Namespace err = r.createOdhCommonConfigMap(ctx, name, dscInit) if err != nil { - r.Log.Error(err, "error creating configmap", "name", "odh-common-config") + log.Error(err, "error creating configmap", "name", "odh-common-config") return err } // Create default Rolebinding for the namespace err = r.createDefaultRoleBinding(ctx, name, dscInit) if err != nil { - r.Log.Error(err, "error creating rolebinding", "name", name) + log.Error(err, "error creating rolebinding", "name", name) return err } return nil } func (r *DSCInitializationReconciler) createDefaultRoleBinding(ctx context.Context, name string, dscInit *dsciv1.DSCInitialization) error { + log := r.Log // Expected namespace for the given name desiredRoleBinding := &rbacv1.RoleBinding{ TypeMeta: metav1.TypeMeta{ @@ -176,7 +178,7 @@ func (r *DSCInitializationReconciler) createDefaultRoleBinding(ctx context.Conte // Set Controller reference err = ctrl.SetControllerReference(dscInit, desiredRoleBinding, r.Scheme) if err != nil { - r.Log.Error(err, "Unable to add OwnerReference to the rolebinding") + log.Error(err, "Unable to add OwnerReference to the rolebinding") return err } err = r.Client.Create(ctx, desiredRoleBinding) @@ -191,23 +193,24 @@ func (r *DSCInitializationReconciler) createDefaultRoleBinding(ctx context.Conte } func (r *DSCInitializationReconciler) reconcileDefaultNetworkPolicy(ctx context.Context, name string, dscInit *dsciv1.DSCInitialization, platform cluster.Platform) error { + log := r.Log if platform == cluster.ManagedRhods || platform == cluster.SelfManagedRhods { // Deploy networkpolicy for operator namespace err := deploy.DeployManifestsFromPath(ctx, r.Client, dscInit, networkpolicyPath+"/operator", "redhat-ods-operator", "networkpolicy", true) if err != nil { - r.Log.Error(err, "error to set networkpolicy in operator namespace", "path", networkpolicyPath) + log.Error(err, "error to set networkpolicy in operator namespace", "path", networkpolicyPath) return err } // Deploy networkpolicy for monitoring namespace err = deploy.DeployManifestsFromPath(ctx, r.Client, dscInit, networkpolicyPath+"/monitoring", dscInit.Spec.Monitoring.Namespace, "networkpolicy", true) if err != nil { - r.Log.Error(err, "error to set networkpolicy in monitroing namespace", "path", networkpolicyPath) + log.Error(err, "error to set networkpolicy in monitroing namespace", "path", networkpolicyPath) return err } // Deploy networkpolicy for applications namespace err = deploy.DeployManifestsFromPath(ctx, r.Client, dscInit, networkpolicyPath+"/applications", dscInit.Spec.ApplicationsNamespace, "networkpolicy", true) if err != nil { - r.Log.Error(err, "error to set networkpolicy in applications namespace", "path", networkpolicyPath) + log.Error(err, "error to set networkpolicy in applications namespace", "path", networkpolicyPath) return err } } else { // Expected namespace for the given name in ODH @@ -292,7 +295,7 @@ func (r *DSCInitializationReconciler) reconcileDefaultNetworkPolicy(ctx context. // Set Controller reference err = ctrl.SetControllerReference(dscInit, desiredNetworkPolicy, r.Scheme) if err != nil { - r.Log.Error(err, "Unable to add OwnerReference to the Network policy") + log.Error(err, "Unable to add OwnerReference to the Network policy") return err } err = r.Client.Create(ctx, desiredNetworkPolicy) @@ -307,7 +310,7 @@ func (r *DSCInitializationReconciler) reconcileDefaultNetworkPolicy(ctx context. // Reconcile the NetworkPolicy spec if it has been manually modified if !justCreated && !CompareNotebookNetworkPolicies(*desiredNetworkPolicy, *foundNetworkPolicy) { - r.Log.Info("Reconciling Network policy", "name", foundNetworkPolicy.Name) + log.Info("Reconciling Network policy", "name", foundNetworkPolicy.Name) // Retry the update operation when the ingress controller eventually // updates the resource version field err := retry.RetryOnConflict(retry.DefaultRetry, func() error { @@ -324,7 +327,7 @@ func (r *DSCInitializationReconciler) reconcileDefaultNetworkPolicy(ctx context. return r.Update(ctx, foundNetworkPolicy) }) if err != nil { - r.Log.Error(err, "Unable to reconcile the Network Policy") + log.Error(err, "Unable to reconcile the Network Policy") return err } } @@ -372,6 +375,7 @@ func GenerateRandomHex(length int) ([]byte, error) { } func (r *DSCInitializationReconciler) createOdhCommonConfigMap(ctx context.Context, name string, dscInit *dsciv1.DSCInitialization) error { + log := r.Log // Expected configmap for the given namespace desiredConfigMap := &corev1.ConfigMap{ TypeMeta: metav1.TypeMeta{ @@ -396,7 +400,7 @@ func (r *DSCInitializationReconciler) createOdhCommonConfigMap(ctx context.Conte // Set Controller reference err = ctrl.SetControllerReference(dscInit, foundConfigMap, r.Scheme) if err != nil { - r.Log.Error(err, "Unable to add OwnerReference to the odh-common-config ConfigMap") + log.Error(err, "Unable to add OwnerReference to the odh-common-config ConfigMap") return err } err = r.Client.Create(ctx, desiredConfigMap) diff --git a/controllers/secretgenerator/secretgenerator_controller.go b/controllers/secretgenerator/secretgenerator_controller.go index 49790806c3f..957e02fe4ae 100644 --- a/controllers/secretgenerator/secretgenerator_controller.go +++ b/controllers/secretgenerator/secretgenerator_controller.go @@ -57,7 +57,8 @@ type SecretGeneratorReconciler struct { // SetupWithManager sets up the controller with the Manager. func (r *SecretGeneratorReconciler) SetupWithManager(mgr ctrl.Manager) error { - r.Log.Info("Adding controller for Secret Generation.") + log := r.Log + log.Info("Adding controller for Secret Generation.") // Watch only new secrets with the corresponding annotation predicates := predicate.Funcs{ @@ -105,6 +106,7 @@ func (r *SecretGeneratorReconciler) SetupWithManager(mgr ctrl.Manager) error { // based on the specified type and complexity. This will avoid possible race // conditions when a deployment mounts the secret before it is reconciled. func (r *SecretGeneratorReconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) { + log := r.Log foundSecret := &corev1.Secret{} err := r.Client.Get(ctx, request.NamespacedName, foundSecret) if err != nil { @@ -136,12 +138,12 @@ func (r *SecretGeneratorReconciler) Reconcile(ctx context.Context, request ctrl. if err != nil { if k8serr.IsNotFound(err) { // Generate secret random value - r.Log.Info("Generating a random value for a secret in a namespace", + log.Info("Generating a random value for a secret in a namespace", "secret", generatedSecret.Name, "namespace", generatedSecret.Namespace) secret, err := NewSecretFrom(foundSecret.GetAnnotations()) if err != nil { - r.Log.Error(err, "error creating secret %s in %s", generatedSecret.Name, generatedSecret.Namespace) + log.Error(err, "error creating secret %s in %s", generatedSecret.Name, generatedSecret.Namespace) return ctrl.Result{}, err } @@ -153,21 +155,21 @@ func (r *SecretGeneratorReconciler) Reconcile(ctx context.Context, request ctrl. if err != nil { return ctrl.Result{}, err } - r.Log.Info("Done generating secret in namespace", + log.Info("Done generating secret in namespace", "secret", generatedSecret.Name, "namespace", generatedSecret.Namespace) // check if annotation oauth-client-route exists if secret.OAuthClientRoute != "" { // Get OauthClient Route oauthClientRoute, err := r.getRoute(ctx, secret.OAuthClientRoute, request.Namespace) if err != nil { - r.Log.Error(err, "Unable to retrieve route from OAuthClient", "route-name", secret.OAuthClientRoute) + log.Error(err, "Unable to retrieve route from OAuthClient", "route-name", secret.OAuthClientRoute) return ctrl.Result{}, err } // Generate OAuthClient for the generated secret - r.Log.Info("Generating an OAuthClient CR for route", "route-name", oauthClientRoute.Name) + log.Info("Generating an OAuthClient CR for route", "route-name", oauthClientRoute.Name) err = r.createOAuthClient(ctx, foundSecret.Name, secret.Value, oauthClientRoute.Spec.Host) if err != nil { - r.Log.Error(err, "error creating oauth client resource. Recreate the Secret", "secret-name", + log.Error(err, "error creating oauth client resource. Recreate the Secret", "secret-name", foundSecret.Name) return ctrl.Result{}, err @@ -207,6 +209,7 @@ func (r *SecretGeneratorReconciler) getRoute(ctx context.Context, name string, n } func (r *SecretGeneratorReconciler) createOAuthClient(ctx context.Context, name string, secretName string, uri string) error { + log := r.Log // Create OAuthClient resource oauthClient := &oauthv1.OAuthClient{ TypeMeta: metav1.TypeMeta{ @@ -224,7 +227,7 @@ func (r *SecretGeneratorReconciler) createOAuthClient(ctx context.Context, name err := r.Client.Create(ctx, oauthClient) if err != nil { if k8serr.IsAlreadyExists(err) { - r.Log.Info("OAuth client resource already exists, patch it", "name", oauthClient.Name) + log.Info("OAuth client resource already exists, patch it", "name", oauthClient.Name) data, err := json.Marshal(oauthClient) if err != nil { return fmt.Errorf("failed to get DataScienceCluster custom resource data: %w", err)