forked from kubernetes-sigs/cluster-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmachinedeployment_rolling.go
More file actions
383 lines (315 loc) · 14.6 KB
/
Copy pathmachinedeployment_rolling.go
File metadata and controls
383 lines (315 loc) · 14.6 KB
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
/*
Copyright 2018 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.
*/
package machinedeployment
import (
"context"
"fmt"
"sort"
"github.com/pkg/errors"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2"
"sigs.k8s.io/cluster-api/internal/controllers/machinedeployment/mdutil"
"sigs.k8s.io/cluster-api/util/patch"
)
// rolloutRolling implements the logic for rolling a new MachineSet.
func (r *Reconciler) rolloutRolling(ctx context.Context, md *clusterv1.MachineDeployment, msList []*clusterv1.MachineSet, templateExists bool) error {
// TODO(in-place): move create newMS into rolloutPlanner
newMS, oldMSs, err := r.getAllMachineSetsAndSyncRevision(ctx, md, msList, true, templateExists)
if err != nil {
return err
}
// newMS can be nil in case there is already a MachineSet associated with this deployment,
// but there are only either changes in annotations or MinReadySeconds. Or in other words,
// this can be nil if there are changes, but no replacement of existing machines is needed.
if newMS == nil {
return nil
}
allMSs := append(oldMSs, newMS)
// TODO(in-place): also apply/remove labels to MS should go into rolloutPlanner
if err := r.cleanupDisableMachineCreateAnnotation(ctx, newMS); err != nil {
return err
}
planner := newRolloutPlanner()
planner.md = md
planner.newMS = newMS
planner.oldMSs = oldMSs
if err := planner.Plan(ctx); err != nil {
return err
}
// TODO(in-place): this should be changed as soon as rolloutPlanner support MS creation and adding/removing labels from MS
for _, ms := range allMSs {
scaleIntent := ptr.Deref(ms.Spec.Replicas, 0)
if v, ok := planner.scaleIntents[ms.Name]; ok {
scaleIntent = v
}
if err := r.scaleMachineSet(ctx, ms, scaleIntent, md); err != nil {
return err
}
}
if err := r.syncDeploymentStatus(allMSs, newMS, md); err != nil {
return err
}
if mdutil.DeploymentComplete(md, &md.Status) {
if err := r.cleanupDeployment(ctx, oldMSs, md); err != nil {
return err
}
}
return nil
}
type rolloutPlanner struct {
md *clusterv1.MachineDeployment
newMS *clusterv1.MachineSet
oldMSs []*clusterv1.MachineSet
scaleIntents map[string]int32
}
func newRolloutPlanner() *rolloutPlanner {
return &rolloutPlanner{
scaleIntents: make(map[string]int32),
}
}
// Plan determine how to proceed with the rollout if we are not yet at the desired state.
func (p *rolloutPlanner) Plan(ctx context.Context) error {
if p.md.Spec.Replicas == nil {
return errors.Errorf("spec.replicas for MachineDeployment %v is nil, this is unexpected", client.ObjectKeyFromObject(p.md))
}
if p.newMS.Spec.Replicas == nil {
return errors.Errorf("spec.replicas for MachineSet %v is nil, this is unexpected", client.ObjectKeyFromObject(p.newMS))
}
for _, oldMS := range p.oldMSs {
if oldMS.Spec.Replicas == nil {
return errors.Errorf("spec.replicas for MachineSet %v is nil, this is unexpected", client.ObjectKeyFromObject(oldMS))
}
}
// Scale up, if we can.
if err := p.reconcileNewMachineSet(ctx); err != nil {
return err
}
// Scale down, if we can.
return p.reconcileOldMachineSets(ctx)
}
func (p *rolloutPlanner) reconcileNewMachineSet(ctx context.Context) error {
log := ctrl.LoggerFrom(ctx)
allMSs := append(p.oldMSs, p.newMS)
if *(p.newMS.Spec.Replicas) == *(p.md.Spec.Replicas) {
// Scaling not required.
return nil
}
if *(p.newMS.Spec.Replicas) > *(p.md.Spec.Replicas) {
// Scale down.
log.V(5).Info(fmt.Sprintf("Setting scale down intent for MachineSet %s to %d replicas", p.newMS.Name, *(p.md.Spec.Replicas)), "MachineSet", klog.KObj(p.newMS))
p.scaleIntents[p.newMS.Name] = *(p.md.Spec.Replicas)
return nil
}
newReplicasCount, err := mdutil.NewMSNewReplicas(p.md, allMSs, *p.newMS.Spec.Replicas)
if err != nil {
return err
}
if newReplicasCount < *(p.newMS.Spec.Replicas) {
scaleDownCount := *(p.newMS.Spec.Replicas) - newReplicasCount
log.V(5).Info(fmt.Sprintf("Setting scale down intent for MachineSet %s to %d replicas (-%d)", p.newMS.Name, newReplicasCount, scaleDownCount), "MachineSet", klog.KObj(p.newMS))
p.scaleIntents[p.newMS.Name] = newReplicasCount
}
if newReplicasCount > *(p.newMS.Spec.Replicas) {
scaleUpCount := newReplicasCount - *(p.newMS.Spec.Replicas)
log.V(5).Info(fmt.Sprintf("Setting scale up intent for MachineSet %s to %d replicas (+%d)", p.newMS.Name, newReplicasCount, scaleUpCount), "MachineSet", klog.KObj(p.newMS))
p.scaleIntents[p.newMS.Name] = newReplicasCount
}
return nil
}
func (p *rolloutPlanner) reconcileOldMachineSets(ctx context.Context) error {
log := ctrl.LoggerFrom(ctx)
oldMachinesCount := mdutil.GetReplicaCountForMachineSets(p.oldMSs)
if oldMachinesCount == 0 {
// Can't scale down further
return nil
}
newMSReplicas := ptr.Deref(p.newMS.Spec.Replicas, 0)
if v, ok := p.scaleIntents[p.newMS.Name]; ok {
newMSReplicas = v
}
allMachinesCount := oldMachinesCount + newMSReplicas
log.V(4).Info("New MachineSet has available machines",
"machineset", client.ObjectKeyFromObject(p.newMS).String(), "available-replicas", ptr.Deref(p.newMS.Status.AvailableReplicas, 0))
maxUnavailable := mdutil.MaxUnavailable(*p.md)
// Check if we can scale down. We can scale down in the following 2 cases:
// * Some old MachineSets have unhealthy replicas, we could safely scale down those unhealthy replicas since that won't further
// increase unavailability.
// * New MachineSet has scaled up and it's replicas becomes ready, then we can scale down old MachineSets in a further step.
//
// maxScaledDown := allMachinesCount - minAvailable - newMachineSetMachinesUnavailable
// take into account not only maxUnavailable and any surge machines that have been created, but also unavailable machines from
// the newMS, so that the unavailable machines from the newMS would not make us scale down old MachineSets 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, newMS is created with 3 replicas, oldMS is scaled down to 8, and newMS is scaled up to 5.
// * The new MachineSet machines crashloop and never become available.
// * allMachinesCount is 13. minAvailable is 8. newMSMachinesUnavailable is 5.
// * A node fails and causes one of the oldMS machines to become unavailable. However, 13 - 8 - 5 = 0, so the oldMS won't be scaled down.
// * The user notices the crashloop and does kubectl rollout undo to rollback.
// * newMSMachinesUnavailable is 1, since we rolled back to the good MachineSet, 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 newMS 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 MachineSet created must start with 0 replicas because allMachinesCount is already at 13.
// * However, newMSMachinesUnavailable would also be 0, so the 2 old MachineSets could be scaled down by 5 (13 - 8 - 0), which would then
// allow the new MachineSet to be scaled up by 5.
availableReplicas := ptr.Deref(p.newMS.Status.AvailableReplicas, 0)
minAvailable := *(p.md.Spec.Replicas) - maxUnavailable
newMSUnavailableMachineCount := newMSReplicas - availableReplicas
maxScaledDown := allMachinesCount - minAvailable - newMSUnavailableMachineCount
if maxScaledDown <= 0 {
return nil
}
// Clean up unhealthy replicas first, otherwise unhealthy replicas will block deployment
// and cause timeout. See https://github.com/kubernetes/kubernetes/issues/16737
cleanupCount, err := p.cleanupUnhealthyReplicas(ctx, maxScaledDown)
if err != nil {
return err
}
log.V(4).Info("Cleaned up unhealthy replicas from old MachineSets", "count", cleanupCount)
// Scale down old MachineSets, need check maxUnavailable to ensure we can scale down
scaledDownCount, err := p.scaleDownOldMachineSetsForRollingUpdate(ctx)
if err != nil {
return err
}
log.V(4).Info("Scaled down old MachineSets of MachineDeployment", "count", scaledDownCount)
return nil
}
// cleanupUnhealthyReplicas will scale down old MachineSets with unhealthy replicas, so that all unhealthy replicas will be deleted.
func (p *rolloutPlanner) cleanupUnhealthyReplicas(ctx context.Context, maxCleanupCount int32) (int32, error) {
log := ctrl.LoggerFrom(ctx)
sort.Sort(mdutil.MachineSetsByCreationTimestamp(p.oldMSs))
// Scale down all old MachineSets with any unhealthy replicas. MachineSet will honour spec.deletion.order
// for deleting Machines. Machines with a deletion timestamp, with a failure message or without a nodeRef
// are preferred for all strategies.
// This results in a best effort to remove machines backing unhealthy nodes.
totalScaledDown := int32(0)
for _, oldMS := range p.oldMSs {
if oldMS.Spec.Replicas == nil {
return 0, errors.Errorf("spec.replicas for MachineSet %v is nil, this is unexpected", client.ObjectKeyFromObject(oldMS))
}
if totalScaledDown >= maxCleanupCount {
break
}
oldMSReplicas := *(oldMS.Spec.Replicas)
if oldMSReplicas == 0 {
// cannot scale down this MachineSet.
continue
}
oldMSAvailableReplicas := ptr.Deref(oldMS.Status.AvailableReplicas, 0)
log.V(4).Info("Found available Machines in old MachineSet",
"count", oldMSAvailableReplicas, "target-machineset", client.ObjectKeyFromObject(oldMS).String())
if oldMSReplicas == oldMSAvailableReplicas {
// no unhealthy replicas found, no scaling required.
continue
}
// TODO(in-place): fix this logic
// It looks like that the current logic fails when the MD controller is called twice in a row, without MS controller being triggered in the between, e.g.
// - first reconcile scales down ms1, 6-->5 (-1)
// - second reconcile is not taking into account scales down already in progress, unhealthy count is wrongly computed as -1 instead of 0, this leads to increasing replica count instead of keeping it as it is (or scaling down), and then the safeguard below errors out.
remainingCleanupCount := maxCleanupCount - totalScaledDown
unhealthyCount := oldMSReplicas - oldMSAvailableReplicas
scaledDownCount := min(remainingCleanupCount, unhealthyCount)
newReplicasCount := oldMSReplicas - scaledDownCount
if newReplicasCount > oldMSReplicas {
return 0, errors.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %v: %d -> %d",
client.ObjectKeyFromObject(oldMS), oldMSReplicas, newReplicasCount)
}
scaleDownCount := *(oldMS.Spec.Replicas) - newReplicasCount
log.V(5).Info(fmt.Sprintf("Setting scale down intent for MachineSet %s to %d replicas (-%d)", oldMS.Name, newReplicasCount, scaleDownCount), "MachineSet", klog.KObj(oldMS))
p.scaleIntents[oldMS.Name] = newReplicasCount
totalScaledDown += scaledDownCount
}
return totalScaledDown, nil
}
// scaleDownOldMachineSetsForRollingUpdate scales down old MachineSets when deployment strategy is "RollingUpdate".
// Need check maxUnavailable to ensure availability.
func (p *rolloutPlanner) scaleDownOldMachineSetsForRollingUpdate(ctx context.Context) (int32, error) {
log := ctrl.LoggerFrom(ctx)
allMSs := append(p.oldMSs, p.newMS)
maxUnavailable := mdutil.MaxUnavailable(*p.md)
minAvailable := *(p.md.Spec.Replicas) - maxUnavailable
// Find the number of available machines.
availableMachineCount := ptr.Deref(mdutil.GetAvailableReplicaCountForMachineSets(allMSs), 0)
// Check if we can scale down.
if availableMachineCount <= minAvailable {
// Cannot scale down.
return 0, nil
}
log.V(4).Info("Found available machines in deployment, scaling down old MSes", "count", availableMachineCount)
sort.Sort(mdutil.MachineSetsByCreationTimestamp(p.oldMSs))
// TODO(in-place): fix this logic
// It looks like that the current logic fails when the MD controller is called twice in a row e.g. reconcile of md 6 replicas MaxSurge=3, MaxUnavailable=1 and
// ms1, 6/5 replicas << one is scaling down, but scale down not yet processed by the MS controller.
// ms2, 3/3 replicas
// Leads to:
// ms1, 6/1 replicas << it further scaled down by 4, which leads to totAvailable machines is less than MinUnavailable, which should not happen
// ms2, 3/3 replicas
totalScaledDown := int32(0)
totalScaleDownCount := availableMachineCount - minAvailable
for _, oldMS := range p.oldMSs {
if totalScaledDown >= totalScaleDownCount {
// No further scaling required.
break
}
oldMSReplicas := ptr.Deref(oldMS.Spec.Replicas, 0)
if v, ok := p.scaleIntents[oldMS.Name]; ok {
oldMSReplicas = v
}
if oldMSReplicas == 0 {
// cannot scale down this MachineSet.
continue
}
// Scale down.
scaleDownCount := min(oldMSReplicas, totalScaleDownCount-totalScaledDown)
newReplicasCount := oldMSReplicas - scaleDownCount
if newReplicasCount > oldMSReplicas {
return totalScaledDown, errors.Errorf("when scaling down old MachineSet, got invalid request to scale down %v: %d -> %d",
client.ObjectKeyFromObject(oldMS), oldMSReplicas, newReplicasCount)
}
log.V(5).Info(fmt.Sprintf("Setting scale down intent for MachineSet %s to %d replicas (-%d)", oldMS.Name, newReplicasCount, scaleDownCount), "MachineSet", klog.KObj(oldMS))
p.scaleIntents[oldMS.Name] = newReplicasCount
totalScaledDown += scaleDownCount
}
return totalScaledDown, nil
}
// cleanupDisableMachineCreateAnnotation will remove the disable machine create annotation from new MachineSets that were created during reconcileOldMachineSetsOnDelete.
func (r *Reconciler) cleanupDisableMachineCreateAnnotation(ctx context.Context, newMS *clusterv1.MachineSet) error {
log := ctrl.LoggerFrom(ctx, "MachineSet", klog.KObj(newMS))
if newMS.Annotations != nil {
if _, ok := newMS.Annotations[clusterv1.DisableMachineCreateAnnotation]; ok {
log.V(4).Info("removing annotation on latest MachineSet to enable machine creation")
patchHelper, err := patch.NewHelper(newMS, r.Client)
if err != nil {
return err
}
delete(newMS.Annotations, clusterv1.DisableMachineCreateAnnotation)
err = patchHelper.Patch(ctx, newMS)
if err != nil {
return err
}
}
}
return nil
}