@@ -257,7 +257,8 @@ func (r *Reconciler) reconcile(ctx context.Context, cluster *clusterv1.Cluster,
257
257
return ctrl.Result {}, errors .Wrapf (err , "error watching nodes on target cluster" )
258
258
}
259
259
260
- // If the Machine belongs to a cluster, add an owner reference.
260
+ // If the machine is a stand-alone one, meaning not originated from a MachineDeployment, then set it as directly
261
+ // owned by the Cluster (if not already present).
261
262
if r .shouldAdopt (m ) {
262
263
m .OwnerReferences = util .EnsureOwnerRef (m .OwnerReferences , metav1.OwnerReference {
263
264
APIVersion : clusterv1 .GroupVersion .String (),
@@ -738,8 +739,20 @@ func (r *Reconciler) reconcileDeleteExternal(ctx context.Context, m *clusterv1.M
738
739
return obj , nil
739
740
}
740
741
742
+ // shouldAdopt returns true if the Machine should be adopted as a stand-alone Machine directly owned by the Cluster.
741
743
func (r * Reconciler ) shouldAdopt (m * clusterv1.Machine ) bool {
742
- return metav1 .GetControllerOf (m ) == nil && ! util .HasOwner (m .OwnerReferences , clusterv1 .GroupVersion .String (), []string {"Cluster" })
744
+ // if the machine is controlled by something (MS or KCP), or if it is a stand-alone machine directly owned by the Cluster, then no-op.
745
+ if metav1 .GetControllerOf (m ) != nil || util .HasOwner (m .OwnerReferences , clusterv1 .GroupVersion .String (), []string {"Cluster" }) {
746
+ return false
747
+ }
748
+
749
+ // If the Machine is originated by a MachineDeployment, this prevents it from being adopted as a stand-alone Machine.
750
+ // Note: this is required because after restore from a backup both the Machine controller and the
751
+ // MachineSet controller are racing to adopt Machines, see https://github.com/kubernetes-sigs/cluster-api/issues/7529
752
+ if _ , ok := m .Labels [clusterv1 .MachineDeploymentUniqueLabel ]; ok {
753
+ return false
754
+ }
755
+ return true
743
756
}
744
757
745
758
func (r * Reconciler ) watchClusterNodes (ctx context.Context , cluster * clusterv1.Cluster ) error {
0 commit comments