@@ -30,6 +30,7 @@ import (
3030 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3131 "k8s.io/klog/v2"
3232 "k8s.io/utils/integer"
33+ "sigs.k8s.io/controller-runtime/pkg/client"
3334
3435 rolloutsv1alpha1 "github.com/openkruise/rollouts/api/v1alpha1"
3536 deploymentutil "github.com/openkruise/rollouts/pkg/controller/deployment/util"
@@ -118,7 +119,14 @@ func (dc *DeploymentController) getNewReplicaSet(ctx context.Context, d *apps.De
118119 minReadySecondsNeedsUpdate := rsCopy .Spec .MinReadySeconds != d .Spec .MinReadySeconds
119120 if annotationsUpdated || minReadySecondsNeedsUpdate {
120121 rsCopy .Spec .MinReadySeconds = d .Spec .MinReadySeconds
121- return dc .client .AppsV1 ().ReplicaSets (rsCopy .ObjectMeta .Namespace ).Update (ctx , rsCopy , metav1.UpdateOptions {})
122+
123+ // Use controller-runtime's MergeFrom for more concise and resilient patching
124+ // This automatically handles strategic merge patches and is more maintainable
125+ err := dc .runtimeClient .Patch (ctx , rsCopy , client .MergeFrom (existingNewRS ))
126+ if err != nil {
127+ return nil , err
128+ }
129+ return rsCopy , nil
122130 }
123131
124132 // Should use the revision in existingNewRS's annotation, since it set by before
@@ -410,11 +418,29 @@ func (dc *DeploymentController) scaleReplicaSet(ctx context.Context, rs *apps.Re
410418 var err error
411419 if sizeNeedsUpdate || annotationsNeedUpdate {
412420 oldScale := * (rs .Spec .Replicas )
421+
422+ // Create a copy to modify without affecting the original
413423 rsCopy := rs .DeepCopy ()
414- * (rsCopy .Spec .Replicas ) = newScale
415- deploymentutil .SetReplicasAnnotations (rsCopy , * (deployment .Spec .Replicas ), * (deployment .Spec .Replicas )+ deploymentutil .MaxSurge (deployment , & dc .strategy ))
416- rs , err = dc .client .AppsV1 ().ReplicaSets (rsCopy .Namespace ).Update (ctx , rsCopy , metav1.UpdateOptions {})
417- if err == nil && sizeNeedsUpdate {
424+
425+ if sizeNeedsUpdate {
426+ rsCopy .Spec .Replicas = & newScale
427+ }
428+ if annotationsNeedUpdate {
429+ // Set the annotations that need to be updated
430+ desiredReplicas := * (deployment .Spec .Replicas )
431+ maxReplicas := * (deployment .Spec .Replicas ) + deploymentutil .MaxSurge (deployment , & dc .strategy )
432+ deploymentutil .SetReplicasAnnotations (rsCopy , desiredReplicas , maxReplicas )
433+ }
434+
435+ // Use controller-runtime's MergeFrom for more concise and resilient patching
436+ // This automatically handles strategic merge patches and is more maintainable
437+ err = dc .runtimeClient .Patch (ctx , rsCopy , client .MergeFrom (rs ))
438+ if err != nil {
439+ return scaled , rs , err
440+ }
441+
442+ rs = rsCopy
443+ if sizeNeedsUpdate {
418444 scaled = true
419445 dc .eventRecorder .Eventf (deployment , v1 .EventTypeNormal , "ScalingReplicaSet" , "Scaled %s replica set %s to %d from %d" , scalingOperation , rs .Name , newScale , oldScale )
420446 }
0 commit comments