Skip to content

Commit

Permalink
Update status in reconcile loop, not in defer
Browse files Browse the repository at this point in the history
  • Loading branch information
sircthulhu committed Mar 20, 2024
1 parent 878826c commit e8d85c1
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions internal/controller/etcdcluster_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,6 @@ func (r *EtcdClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request)
Message: "Cluster initialization has started",
})
}
defer func() {
if err := r.Status().Update(ctx, instance); err != nil && !errors.IsConflict(err) {
logger.Error(err, "unable to update cluster")
}
}()

// check sts condition
isClusterReady := false
Expand All @@ -99,7 +94,11 @@ func (r *EtcdClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request)
}

if err := r.ensureClusterObjects(ctx, instance, isClusterReady); err != nil {
return ctrl.Result{}, fmt.Errorf("cannot create Cluster auxiliary objects: %w", err)
res, err2 := r.updateStatus(ctx, instance)
if err2 != nil {
return res, err2
}
return res, fmt.Errorf("cannot create Cluster auxiliary objects: %w", err)
}

r.updateClusterState(instance, metav1.Condition{
Expand Down Expand Up @@ -127,7 +126,7 @@ func (r *EtcdClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request)
})
}

return ctrl.Result{}, nil
return r.updateStatus(ctx, instance)
}

// ensureClusterObjects creates or updates all objects owned by cluster CR
Expand Down Expand Up @@ -474,6 +473,18 @@ func (r *EtcdClusterReconciler) getClientServiceName(cluster *etcdaenixiov1alpha
return cluster.Name + "-client"
}

func (r *EtcdClusterReconciler) updateStatus(ctx context.Context, cluster *etcdaenixiov1alpha1.EtcdCluster) (ctrl.Result, error) {
logger := log.FromContext(ctx)
if err := r.Status().Update(ctx, cluster); err != nil {
logger.Error(err, "unable to update cluster status")
if errors.IsConflict(err) {
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}

// updateClusterState patches status condition in cluster using merge by Type
func (r *EtcdClusterReconciler) updateClusterState(cluster *etcdaenixiov1alpha1.EtcdCluster, state metav1.Condition) {
if initIdx := slices.IndexFunc(cluster.Status.Conditions, func(condition metav1.Condition) bool {
Expand Down

0 comments on commit e8d85c1

Please sign in to comment.