diff --git a/controllers/cluster_controller.go b/controllers/cluster_controller.go index fba466acf..ae742798f 100644 --- a/controllers/cluster_controller.go +++ b/controllers/cluster_controller.go @@ -18,6 +18,7 @@ package controllers import ( "context" + "fmt" "reflect" "github.com/presslabs/controller-util/syncer" @@ -30,11 +31,13 @@ import ( "k8s.io/client-go/tools/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" apiv1alpha1 "github.com/radondb/radondb-mysql-kubernetes/api/v1alpha1" "github.com/radondb/radondb-mysql-kubernetes/cluster" clustersyncer "github.com/radondb/radondb-mysql-kubernetes/cluster/syncer" + "github.com/radondb/radondb-mysql-kubernetes/utils" ) // ClusterReconciler reconciles a Cluster object @@ -93,6 +96,31 @@ func (r *ClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct } }() + // if the cluster is not been deleted + if instance.ObjectMeta.DeletionTimestamp.IsZero() { + // if do not have, add it, then update + if !controllerutil.ContainsFinalizer(instance.Unwrap(), string(utils.ClusterFinalizer)) { + controllerutil.AddFinalizer(instance.Unwrap(), string(utils.ClusterFinalizer)) + if err := r.Update(ctx, instance.Unwrap()); err != nil { + log.Error(err, "failed to update cluster status") + return ctrl.Result{}, err + } + } + } else { // if the cluster is been deleted + //check the Cluster status is ready + if status.State == apiv1alpha1.ClusterReady || status.State == apiv1alpha1.ClusterError { + controllerutil.RemoveFinalizer(instance.Unwrap(), string(utils.ClusterFinalizer)) + if err := r.Update(ctx, instance.Unwrap()); err != nil { + log.Error(err, "failed to update cluster status") + return ctrl.Result{}, err + } + } else { + //return error, reconcile again + return ctrl.Result{}, fmt.Errorf("Is not ready, reconcile again") + } + + } + configMapSyncer := clustersyncer.NewConfigMapSyncer(r.Client, instance) if err = syncer.Sync(ctx, configMapSyncer, r.Recorder); err != nil { return ctrl.Result{}, err diff --git a/utils/constants.go b/utils/constants.go index 4bca925d3..85b7f597c 100644 --- a/utils/constants.go +++ b/utils/constants.go @@ -89,6 +89,9 @@ const ( // preUpdate file FileIndicateUpdate = "PreUpdating" + + // ClusterFinalizer Name + ClusterFinalizer ResourceName = "clusers.radondb-mysql-kubernetes" ) // ResourceName is the type for aliasing resources that will be created.