/
deployment_rolling.go
489 lines (431 loc) · 19.3 KB
/
deployment_rolling.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file was copied and modified from the kubernetes/kubernetes project
https://github.com/kubernetes/kubernetes/release-1.8/pkg/controller/deployment/rolling.go
Modifications Copyright SAP SE or an SAP affiliate company and Gardener contributors
*/
// Package controller is used to provide the core functionalities of machine-controller-manager
package controller
import (
"context"
"fmt"
"sort"
"time"
"github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
"github.com/gardener/machine-controller-manager/pkg/controller/autoscaler"
"github.com/gardener/machine-controller-manager/pkg/util/nodeops"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
"k8s.io/utils/integer"
)
var (
maxRetryDeadline = 1 * time.Minute
conflictRetryInterval = 5 * time.Second
)
// rolloutRolling implements the logic for rolling a new machine set.
func (dc *controller) rolloutRolling(ctx context.Context, d *v1alpha1.MachineDeployment, isList []*v1alpha1.MachineSet, machineMap map[types.UID]*v1alpha1.MachineList) error {
clusterAutoscalerScaleDownAnnotations := make(map[string]string)
clusterAutoscalerScaleDownAnnotations[autoscaler.ClusterAutoscalerScaleDownDisabledAnnotationKey] = autoscaler.ClusterAutoscalerScaleDownDisabledAnnotationValue
// We do this to avoid accidentally deleting the user provided annotations.
clusterAutoscalerScaleDownAnnotations[autoscaler.ClusterAutoscalerScaleDownDisabledAnnotationByMCMKey] = autoscaler.ClusterAutoscalerScaleDownDisabledAnnotationByMCMValue
newIS, oldISs, err := dc.getAllMachineSetsAndSyncRevision(ctx, d, isList, machineMap, true)
if err != nil {
return err
}
allISs := append(oldISs, newIS)
err = dc.taintNodesBackingMachineSets(
ctx,
oldISs, &v1.Taint{
Key: PreferNoScheduleKey,
Value: "True",
Effect: "PreferNoSchedule",
},
)
if dc.autoscalerScaleDownAnnotationDuringRollout {
// Add the annotation on the all machinesets if there are any old-machinesets and not scaled-to-zero.
// This also helps in annotating the node under new-machineset, incase the reconciliation is failing in next
// status-rollout steps.
if len(oldISs) > 0 && !dc.machineSetsScaledToZero(oldISs) {
// Annotate all the nodes under this machine-deployment, as roll-out is on-going.
err := dc.annotateNodesBackingMachineSets(ctx, allISs, clusterAutoscalerScaleDownAnnotations)
if err != nil {
klog.Errorf("Failed to add %s on all nodes. Error: %s", clusterAutoscalerScaleDownAnnotations, err)
return err
}
}
}
if err != nil {
klog.Warningf("Failed to add %s on all nodes. Error: %s", PreferNoScheduleKey, err)
}
// Scale up, if we can.
scaledUp, err := dc.reconcileNewMachineSet(ctx, allISs, newIS, d)
if err != nil {
return err
}
if scaledUp {
// Update DeploymentStatus
return dc.syncRolloutStatus(ctx, allISs, newIS, d)
}
// Scale down, if we can.
scaledDown, err := dc.reconcileOldMachineSets(ctx, allISs, FilterActiveMachineSets(oldISs), newIS, d)
if err != nil {
return err
}
if scaledDown {
// Update DeploymentStatus
return dc.syncRolloutStatus(ctx, allISs, newIS, d)
}
if MachineDeploymentComplete(d, &d.Status) {
if dc.autoscalerScaleDownAnnotationDuringRollout {
// Check if any of the machine under this MachineDeployment contains the by-mcm annotation, and
// remove the original autoscaler annotation only after.
err := dc.removeAutoscalerAnnotationsIfRequired(ctx, allISs, clusterAutoscalerScaleDownAnnotations)
if err != nil {
return err
}
}
if err := dc.cleanupMachineDeployment(ctx, oldISs, d); err != nil {
return err
}
}
// Sync deployment status
return dc.syncRolloutStatus(ctx, allISs, newIS, d)
}
func (dc *controller) reconcileNewMachineSet(ctx context.Context, allISs []*v1alpha1.MachineSet, newIS *v1alpha1.MachineSet, deployment *v1alpha1.MachineDeployment) (bool, error) {
if (newIS.Spec.Replicas) == (deployment.Spec.Replicas) {
// Scaling not required.
return false, nil
}
if (newIS.Spec.Replicas) > (deployment.Spec.Replicas) {
// Scale down.
scaled, _, err := dc.scaleMachineSetAndRecordEvent(ctx, newIS, (deployment.Spec.Replicas), deployment)
return scaled, err
}
newReplicasCount, err := NewISNewReplicas(deployment, allISs, newIS)
if err != nil {
return false, err
}
scaled, _, err := dc.scaleMachineSetAndRecordEvent(ctx, newIS, newReplicasCount, deployment)
return scaled, err
}
func (dc *controller) reconcileOldMachineSets(ctx context.Context, allISs []*v1alpha1.MachineSet, oldISs []*v1alpha1.MachineSet, newIS *v1alpha1.MachineSet, deployment *v1alpha1.MachineDeployment) (bool, error) {
oldMachinesCount := GetReplicaCountForMachineSets(oldISs)
if oldMachinesCount == 0 {
// Can't scale down further
return false, nil
}
allMachinesCount := GetReplicaCountForMachineSets(allISs)
klog.V(3).Infof("New machine set %s has %d available machines.", newIS.Name, newIS.Status.AvailableReplicas)
maxUnavailable := MaxUnavailable(*deployment)
// Check if we can scale down. We can scale down in the following 2 cases:
// * Some old machine sets have unhealthy replicas, we could safely scale down those unhealthy replicas since that won't further
// increase unavailability.
// * New machine set has scaled up and it's replicas becomes ready, then we can scale down old machine sets in a further step.
//
// maxScaledDown := allmachinesCount - minAvailable - newReplicaSetmachinesUnavailable
// take into account not only maxUnavailable and any surge machines that have been created, but also unavailable machines from
// the newRS, so that the unavailable machines from the newRS would not make us scale down old machine sets in a further
// step(that will increase unavailability).
//
// Concrete example:
//
// * 10 replicas
// * 2 maxUnavailable (absolute number, not percent)
// * 3 maxSurge (absolute number, not percent)
//
// case 1:
// * Deployment is updated, newRS is created with 3 replicas, oldRS is scaled down to 8, and newRS is scaled up to 5.
// * The new machine set machines crashloop and never become available.
// * allmachinesCount is 13. minAvailable is 8. newRSmachinesUnavailable is 5.
// * A node fails and causes one of the oldRS machines to become unavailable. However, 13 - 8 - 5 = 0, so the oldRS won't be scaled down.
// * The user notices the crashloop and does kubectl rollout undo to rollback.
// * newRSmachinesUnavailable is 1, since we rolled back to the good machine set, so maxScaledDown = 13 - 8 - 1 = 4. 4 of the crashlooping machines will be scaled down.
// * The total number of machines will then be 9 and the newRS can be scaled up to 10.
//
// case 2:
// Same example, but pushing a new machine template instead of rolling back (aka "roll over"):
// * The new machine set created must start with 0 replicas because allmachinesCount is already at 13.
// * However, newRSmachinesUnavailable would also be 0, so the 2 old machine sets could be scaled down by 5 (13 - 8 - 0), which would then
// allow the new machine set to be scaled up by 5.
minAvailable := (deployment.Spec.Replicas) - maxUnavailable
newISUnavailableMachineCount := (newIS.Spec.Replicas) - newIS.Status.AvailableReplicas
maxScaledDown := allMachinesCount - minAvailable - newISUnavailableMachineCount
if maxScaledDown <= 0 {
return false, nil
}
// Clean up unhealthy replicas first, otherwise unhealthy replicas will block deployment
// and cause timeout. See https://github.com/kubernetes/kubernetes/issues/16737
oldISs, cleanupCount, err := dc.cleanupUnhealthyReplicas(ctx, oldISs, deployment, maxScaledDown)
if err != nil {
return false, nil
}
klog.V(3).Infof("Cleaned up unhealthy replicas from old ISes by %d", cleanupCount)
// Scale down old machine sets, need check maxUnavailable to ensure we can scale down
allISs = append(oldISs, newIS)
scaledDownCount, err := dc.scaleDownOldMachineSetsForRollingUpdate(ctx, allISs, oldISs, deployment)
if err != nil {
return false, nil
}
klog.V(3).Infof("Scaled down old ISes of deployment %s by %d", deployment.Name, scaledDownCount)
totalScaledDown := cleanupCount + scaledDownCount
return totalScaledDown > 0, nil
}
// cleanupUnhealthyReplicas will scale down old machine sets with unhealthy replicas, so that all unhealthy replicas will be deleted.
func (dc *controller) cleanupUnhealthyReplicas(ctx context.Context, oldISs []*v1alpha1.MachineSet, deployment *v1alpha1.MachineDeployment, maxCleanupCount int32) ([]*v1alpha1.MachineSet, int32, error) {
sort.Sort(MachineSetsByCreationTimestamp(oldISs))
// Safely scale down all old machine sets with unhealthy replicas. machine set will sort the machines in the order
// such that not-ready < ready, unscheduled < scheduled, and pending < running. This ensures that unhealthy replicas will
// been deleted first and won't increase unavailability.
totalScaledDown := int32(0)
for i, targetIS := range oldISs {
if totalScaledDown >= maxCleanupCount {
break
}
if (targetIS.Spec.Replicas) == 0 {
// cannot scale down this machine set.
continue
}
klog.V(4).Infof("Found %d available machine in old IS %s", targetIS.Status.AvailableReplicas, targetIS.Name)
if (targetIS.Spec.Replicas) == targetIS.Status.AvailableReplicas {
// no unhealthy replicas found, no scaling required.
continue
}
scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int((targetIS.Spec.Replicas)-targetIS.Status.AvailableReplicas)))
newReplicasCount := (targetIS.Spec.Replicas) - scaledDownCount
if newReplicasCount > (targetIS.Spec.Replicas) {
return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s %d -> %d", targetIS.Name, (targetIS.Spec.Replicas), newReplicasCount)
}
_, updatedOldIS, err := dc.scaleMachineSetAndRecordEvent(ctx, targetIS, newReplicasCount, deployment)
if err != nil {
return nil, totalScaledDown, err
}
totalScaledDown += scaledDownCount
oldISs[i] = updatedOldIS
}
return oldISs, totalScaledDown, nil
}
// scaleDownOldReplicaSetsForRollingUpdate scales down old machine sets when deployment strategy is "RollingUpdate".
// Need check maxUnavailable to ensure availability
func (dc *controller) scaleDownOldMachineSetsForRollingUpdate(ctx context.Context, allISs []*v1alpha1.MachineSet, oldISs []*v1alpha1.MachineSet, deployment *v1alpha1.MachineDeployment) (int32, error) {
maxUnavailable := MaxUnavailable(*deployment)
// Check if we can scale down.
minAvailable := (deployment.Spec.Replicas) - maxUnavailable
// Find the number of available machines.
availableMachineCount := GetAvailableReplicaCountForMachineSets(allISs)
if availableMachineCount <= minAvailable {
// Cannot scale down.
return 0, nil
}
klog.V(4).Infof("Found %d available machines in deployment %s, scaling down old ISes", availableMachineCount, deployment.Name)
sort.Sort(MachineSetsByCreationTimestamp(oldISs))
totalScaledDown := int32(0)
totalScaleDownCount := availableMachineCount - minAvailable
for _, targetIS := range oldISs {
if totalScaledDown >= totalScaleDownCount {
// No further scaling required.
break
}
if (targetIS.Spec.Replicas) == 0 {
// cannot scale down this ReplicaSet.
continue
}
// Scale down.
scaleDownCount := int32(integer.IntMin(int((targetIS.Spec.Replicas)), int(totalScaleDownCount-totalScaledDown)))
newReplicasCount := (targetIS.Spec.Replicas) - scaleDownCount
if newReplicasCount > (targetIS.Spec.Replicas) {
return 0, fmt.Errorf("when scaling down old IS, got invalid request to scale down %s %d -> %d", targetIS.Name, (targetIS.Spec.Replicas), newReplicasCount)
}
_, _, err := dc.scaleMachineSetAndRecordEvent(ctx, targetIS, newReplicasCount, deployment)
if err != nil {
return totalScaledDown, err
}
totalScaledDown += scaleDownCount
}
return totalScaledDown, nil
}
// taintNodesBackingMachineSets taints all nodes backing the machineSets
func (dc *controller) taintNodesBackingMachineSets(ctx context.Context, MachineSets []*v1alpha1.MachineSet, taint *v1.Taint) error {
for _, machineSet := range MachineSets {
if _, exists := machineSet.Annotations[taint.Key]; exists {
// Taint exists, hence just continue
continue
}
klog.V(3).Infof("Trying to taint MachineSet object %q with %s to avoid scheduling of pods", machineSet.Name, taint.Key)
selector, err := metav1.LabelSelectorAsSelector(machineSet.Spec.Selector)
if err != nil {
return err
}
// list all machines to include the machines that don't match the ms`s selector
// anymore but has the stale controller ref.
// TODO: Do the List and Filter in a single pass, or use an index.
filteredMachines, err := dc.machineLister.List(labels.Everything())
if err != nil {
return err
}
// NOTE: filteredMachines are pointing to objects from cache - if you need to
// modify them, you need to copy it first.
filteredMachines, err = dc.claimMachines(ctx, machineSet, selector, filteredMachines)
if err != nil {
return err
}
// Iterate through all machines and place the PreferNoSchedule taint
// to avoid scheduling on older machines
for _, machine := range filteredMachines {
if machine.Labels[v1alpha1.NodeLabelKey] != "" {
err = nodeops.AddOrUpdateTaintOnNode(
ctx,
dc.targetCoreClient,
machine.Labels[v1alpha1.NodeLabelKey],
taint,
)
if err != nil {
klog.Warningf("Node tainting failed for node: %s, %s", machine.Labels[v1alpha1.NodeLabelKey], err)
}
}
}
retryDeadline := time.Now().Add(maxRetryDeadline)
for {
machineSet, err = dc.controlMachineClient.MachineSets(machineSet.Namespace).Get(ctx, machineSet.Name, metav1.GetOptions{})
if err != nil && time.Now().Before(retryDeadline) {
klog.Warningf("Unable to fetch MachineSet object %s, Error: %+v", machineSet.Name, err)
time.Sleep(conflictRetryInterval)
continue
} else if err != nil {
// Timeout occurred
klog.Errorf("Timeout occurred: Unable to fetch MachineSet object %s, Error: %+v", machineSet.Name, err)
return err
}
msCopy := machineSet.DeepCopy()
if msCopy.Annotations == nil {
msCopy.Annotations = make(map[string]string, 0)
}
msCopy.Annotations[taint.Key] = "True"
_, err = dc.controlMachineClient.MachineSets(msCopy.Namespace).Update(ctx, msCopy, metav1.UpdateOptions{})
if err != nil && time.Now().Before(retryDeadline) {
klog.Warningf("Unable to update MachineSet object %s, Error: %+v", machineSet.Name, err)
time.Sleep(conflictRetryInterval)
continue
} else if err != nil {
// Timeout occurred
klog.Errorf("Timeout occurred: Unable to update MachineSet object %s, Error: %+v", machineSet.Name, err)
return err
}
// Break out of loop when update succeeds
break
}
klog.V(2).Infof("Tainted MachineSet object %q with %s to avoid scheduling of pods", machineSet.Name, taint.Key)
}
return nil
}
// annotateNodesBackingMachineSets annotates all nodes backing the machineSets
func (dc *controller) annotateNodesBackingMachineSets(ctx context.Context, MachineSets []*v1alpha1.MachineSet, annotations map[string]string) error {
for _, machineSet := range MachineSets {
if machineSet == nil {
continue
}
klog.V(4).Infof("Trying to annotate nodes under the MachineSet object %q with %s", machineSet.Name, annotations)
selector, err := metav1.LabelSelectorAsSelector(machineSet.Spec.Selector)
if err != nil {
return err
}
// list all machines to include the machines that don't match the ms`s selector
// anymore but has the stale controller ref.
// TODO: Do the List and Filter in a single pass, or use an index.
filteredMachines, err := dc.machineLister.List(labels.Everything())
if err != nil {
return err
}
// NOTE: filteredMachines are pointing to objects from cache - if you need to
// modify them, you need to copy it first.
filteredMachines, err = dc.claimMachines(ctx, machineSet, selector, filteredMachines)
if err != nil {
return err
}
for _, machine := range filteredMachines {
if machine.Labels[v1alpha1.NodeLabelKey] != "" {
err = AddOrUpdateAnnotationOnNode(
ctx,
dc.targetCoreClient,
machine.Labels[v1alpha1.NodeLabelKey],
annotations,
)
if err != nil {
klog.Warningf("Adding annotation failed for node: %s, %s", machine.Labels[v1alpha1.NodeLabelKey], err)
}
}
}
klog.V(3).Infof("Annotated the nodes backed by MachineSet %q with %s", machineSet.Name, annotations)
}
return nil
}
func (dc *controller) machineSetsScaledToZero(MachineSets []*v1alpha1.MachineSet) bool {
for _, machineSet := range MachineSets {
if machineSet.Spec.Replicas != 0 && machineSet.Status.AvailableReplicas != 0 && machineSet.Status.FullyLabeledReplicas != 0 && machineSet.Status.ReadyReplicas != 0 && machineSet.Status.Replicas != 0 {
return false
}
}
return true
}
// removeAutoscalerAnnotationsIfRequired removes the annotations if needed from nodes backing machinesets.
func (dc *controller) removeAutoscalerAnnotationsIfRequired(ctx context.Context, MachineSets []*v1alpha1.MachineSet, annotations map[string]string) error {
for _, machineSet := range MachineSets {
selector, err := metav1.LabelSelectorAsSelector(machineSet.Spec.Selector)
if err != nil {
return err
}
// list all machines to include the machines that don't match the ms`s selector
// anymore but has the stale controller ref.
// TODO: Do the List and Filter in a single pass, or use an index.
filteredMachines, err := dc.machineLister.List(labels.Everything())
if err != nil {
return err
}
// NOTE: filteredMachines are pointing to objects from cache - if you need to
// modify them, you need to copy it first.
filteredMachines, err = dc.claimMachines(ctx, machineSet, selector, filteredMachines)
if err != nil {
return err
}
for _, machine := range filteredMachines {
if machine.Labels[v1alpha1.NodeLabelKey] != "" {
nodeAnnotations, err := GetAnnotationsFromNode(
ctx,
dc.targetCoreClient,
machine.Labels[v1alpha1.NodeLabelKey],
)
if err != nil {
klog.Warningf("Get annotations failed for node: %s, %s", machine.Labels[v1alpha1.NodeLabelKey], err)
return err
}
// Remove the autoscaler-related annotation only if the by-mcm annotation is already set. If
// by-mcm annotation is not set, the original annotation is likely be put by the end-user for their usecases.
if _, exists := nodeAnnotations[autoscaler.ClusterAutoscalerScaleDownDisabledAnnotationByMCMKey]; exists {
err = RemoveAnnotationsOffNode(
ctx,
dc.targetCoreClient,
machine.Labels[v1alpha1.NodeLabelKey],
annotations,
)
if err != nil {
klog.Warningf("Removing annotation failed for node: %s, %s", machine.Labels[v1alpha1.NodeLabelKey], err)
return err
}
klog.V(3).Infof("De-annotated the node %q backed by MachineSet %q with %s", machine.Labels[v1alpha1.NodeLabelKey], machineSet.Name, annotations)
}
}
}
}
return nil
}