-
Notifications
You must be signed in to change notification settings - Fork 35
/
updates.go
755 lines (605 loc) · 30.8 KB
/
updates.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/*
Copyright 2022 Red Hat, Inc.
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 controlplanemachineset
import (
"context"
"errors"
"fmt"
"sort"
"time"
"github.com/go-logr/logr"
machinev1 "github.com/openshift/api/machine/v1"
"github.com/openshift/cluster-control-plane-machine-set-operator/pkg/machineproviders"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
)
const (
// createdReplacement is a log message used to inform the user that a new Machine was created to
// replace an existing Machine.
createdReplacement = "Created replacement machine"
// errorCreatingMachine is a log message used to inform the user that an error occurred while
// attempting to create a replacement Machine.
errorCreatingMachine = "Error creating machine"
// errorDeletingMachine is a log message used to inform the user that an error occurred while
// attempting to delete replacement Machine.
errorDeletingMachine = "Error deleting machine"
// alreadyPresentReplacement is a log message used to inform the user that a new Machine was not created to
// replace an existing Machine, because a replacement has already been created.
alreadyPresentReplacement = "Replacement machine already present"
// invalidStrategyMessage is used to inform the user that they have provided an invalid value
// for the update strategy.
invalidStrategyMessage = "invalid value for spec.strategy.type"
// machineRequiresUpdate is a log message used to inform the user that a Machine requires an update.
// This is used with the RollingUpdate replacement strategy.
machineRequiresUpdate = "Machine requires an update"
// machineRequiresDeleteBeforeUpdate is a log message used to inform the user that a Machine requires an update,
// but that they must first delete the Machine to trigger a replacement.
// This is used with the OnDelete replacement strategy.
machineRequiresDeleteBeforeUpdate = "Machine requires an update, delete the machine to trigger a replacement"
// noUpdatesRequired is a log message used to inform the user that no updates are required within
// the current set of Machines.
noUpdatesRequired = "No updates required"
// noCapacityForExpansion is a log message used to inform the user that no capacity for expanding the machine count
// by creating a new machine is left as maximum surge has been reached.
noCapacityForExpansion = "Insufficient capacity for expansion, maximum surge has been reached." +
" Cannot create a replacement Machine at this time."
// removingOldMachine is a log message used to inform the user that an old Machine has been
// deleted as a part of the rollout operation.
removingOldMachine = "Removing old machine"
// waitingForReady is a log message used to inform the user that no operations are taking
// place because the rollout is waiting for a Machine to be ready.
// This is used exclusively when adding a new Machine to a missing index.
waitingForReady = "Waiting for machine to become ready"
// waitingForRemoved is a log message used to inform the user that no operations are taking
// place because the rollout is waiting for a Machine to be removed.
waitingForRemoved = "Waiting for machine to be removed"
// waitingForReplacement is a log message used to inform the user that no operations are taking
// place because the rollout is waiting for a replacement Machine to become ready.
// This is used when replacing a Machine within an index.
waitingForReplacement = "Waiting for replacement machine to become ready"
// unknownMachineName is a value used for logging new machines when we do not know the name
// of the upcoming machine. This can occur when all machines have been removed from an index
// and a new one will be created.
unknownMachineName = "<Unknown>"
)
var (
// errRecreateStrategyNotSupported is used to inform users that the Recreate update strategy is not yet supported.
// It may be supported in a future version.
errRecreateStrategyNotSupported = fmt.Errorf("update strategy %q is not supported", machinev1.Recreate)
// errReplicasRequired is used to inform users that the replicas field is currently unset, and
// must be set to continue operation.
errReplicasRequired = errors.New("spec.replicas is unset: replicas is required")
// errUnknownStrategy is used to inform users that the update strategy they have provided is not recognised.
errUnknownStrategy = errors.New("unknown update strategy")
)
// reconcileMachineUpdates determines if any Machines are in need of an update and then handles those updates as per the
// update strategy within the ControlPlaneMachineSet.
// When a Machine needs an update, this function should create a replacement where appropriate.
func (r *ControlPlaneMachineSetReconciler) reconcileMachineUpdates(ctx context.Context, logger logr.Logger, cpms *machinev1.ControlPlaneMachineSet, machineProvider machineproviders.MachineProvider, machineInfos map[int32][]machineproviders.MachineInfo) (ctrl.Result, error) {
switch cpms.Spec.Strategy.Type {
case machinev1.RollingUpdate:
return r.reconcileMachineRollingUpdate(ctx, logger, cpms, machineProvider, machineInfos)
case machinev1.OnDelete:
return r.reconcileMachineOnDeleteUpdate(ctx, logger, cpms, machineProvider, machineInfos)
case machinev1.Recreate:
meta.SetStatusCondition(&cpms.Status.Conditions, metav1.Condition{
Type: conditionDegraded,
Status: metav1.ConditionTrue,
Reason: reasonInvalidStrategy,
Message: fmt.Sprintf("%s: %s", invalidStrategyMessage, errRecreateStrategyNotSupported),
})
logger.Error(errRecreateStrategyNotSupported, invalidStrategyMessage)
default:
meta.SetStatusCondition(&cpms.Status.Conditions,
metav1.Condition{
Type: conditionDegraded,
Status: metav1.ConditionTrue,
Reason: reasonInvalidStrategy,
Message: fmt.Sprintf("%s: %s: %s", invalidStrategyMessage, errUnknownStrategy, cpms.Spec.Strategy.Type),
})
logger.Error(fmt.Errorf("%w: %s", errUnknownStrategy, cpms.Spec.Strategy.Type), invalidStrategyMessage)
}
// Do not return an error here as we only return here when the strategy is invalid.
// This will need user intervention to resolve.
return ctrl.Result{}, nil
}
// reconcileMachineRollingUpdate implements the rolling update strategy for the ControlPlaneMachineSet. It uses the
// indexed machine information to determine when a new Machine is required to be created. When a new Machine is required,
// it uses the machine provider to create the new Machine.
//
// For rolling updates, a new Machine is required when a machine index has a Machine, which needs an update, but does
// not yet have replacement created. It must also observe the surge semantics of a rolling update, so, if an existing
// index is already going through the process of a rolling update, it should not start the update of any other index.
// At present, the surge is limited to a single Machine instance.
//
// Once a replacement Machine is ready, the strategy should also delete the old Machine to allow it to be removed from
// the cluster.
//
// In certain scenarios, there may be indexes with missing Machines. In these circumstances, the update should attempt
// to create a new Machine to fulfil the requirement of that index.
//
//nolint:cyclop
func (r *ControlPlaneMachineSetReconciler) reconcileMachineRollingUpdate(ctx context.Context, logger logr.Logger, cpms *machinev1.ControlPlaneMachineSet, machineProvider machineproviders.MachineProvider, indexedMachineInfos map[int32][]machineproviders.MachineInfo) (ctrl.Result, error) {
logger = logger.WithValues("updateStrategy", cpms.Spec.Strategy.Type)
// To ensure an ordered and safe reconciliation,
// one index at a time is considered.
// Indexes are sorted in ascending order, so that all the operations of the same importance,
// are executed prioritizing the lower indexes first.
sortedIndexedMs := sortMachineInfosByIndex(indexedMachineInfos)
// The maximum number of machines that
// can be scheduled above the original number of desired machines.
// At present, the surge is limited to a single Machine instance.
// NOTE: If this gets changed or parametrized,
// the tests will need to be updated accordingly.
maxSurge := 1
// Devise the existing surge and keep track of the current surge count.
// No check for early stoppage is done here,
// as deletions can continue even if the maxSurge has been already reached.
surgeCount := deviseExistingSurge(cpms, sortedIndexedMs)
var updated, shouldRequeue bool
for _, indexToMachines := range sortedIndexedMs {
idx := indexToMachines.index
machines := indexToMachines.machineInfos
if done, result, err := r.deleteReplacedMachines(ctx, logger, machineProvider, machines); err != nil {
return result, err
} else if done {
updated = true
}
if r.waitForReadyMachine(logger, machines) || r.waitForReplacementMachine(logger, machines) {
// Relying on machine events is not sufficient in this case, as the machine could already be in Running phase
// while the backing node might still be in NotReady condition. Therefore in order to catch
// node's NotReady -> Ready changes (a necessary for CPMS replicas to be Ready), we add a manual requeue.
updated, shouldRequeue = true, true
}
if done := r.waitForRemoveMachine(logger, machines); done {
updated = true
}
if done, result, err := r.createRollingUpdateReplacementMachines(ctx, logger, machineProvider, machines, idx, maxSurge, &surgeCount); err != nil {
return result, err
} else if done {
updated = true
}
}
if !updated {
logger.V(4).Info(noUpdatesRequired)
}
if shouldRequeue {
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
return ctrl.Result{}, nil
}
// reconcileMachineOnDeleteUpdate implements the rolling update strategy for the ControlPlaneMachineSet. It uses the
// indexed machine information to determine when a new Machine is required to be created. When a new Machine is required,
// it uses the machine provider to create the new Machine.
//
// For on-delete updates, a new Machine is required when a machine index has a Machine with a non-zero deletion
// timestamp but does not yet have a replacement created.
//
// In certain scenarios, there may be indexes with missing Machines. In these circumstances, the update should attempt
// to create a new Machine to fulfil the requirement of that index.
//
//nolint:cyclop
func (r *ControlPlaneMachineSetReconciler) reconcileMachineOnDeleteUpdate(ctx context.Context, logger logr.Logger, cpms *machinev1.ControlPlaneMachineSet, machineProvider machineproviders.MachineProvider, indexedMachineInfos map[int32][]machineproviders.MachineInfo) (ctrl.Result, error) {
logger = logger.WithValues("updateStrategy", cpms.Spec.Strategy.Type)
// To ensure an ordered and safe reconciliation,
// one index at a time is considered.
// Indexes are sorted in ascending order, so that all the operations of the same importance,
// are executed prioritizing the lower indexes first.
sortedIndexedMs := sortMachineInfosByIndex(indexedMachineInfos)
var updated, shouldRequeue bool
for _, indexToMachines := range sortedIndexedMs {
idx := indexToMachines.index
machines := indexToMachines.machineInfos
needsReplacement := needReplacementMachines(machines)
machinesPending := pendingMachines(machines)
// if no machines need replacement or are pending, we can continue processing the next MachineInfo
if isEmpty(needsReplacement) && hasAny(machines) && isEmpty(machinesPending) {
continue
}
if r.waitForReadyMachine(logger, machines) || r.waitForReplacementMachine(logger, machines) {
// Relying on machine events is not sufficient in this case, as the machine could already be in Running phase
// while the backing node might still be in NotReady condition. Therefore in order to catch
// node's NotReady -> Ready changes (a necessary for CPMS replicas to be Ready), we add a manual requeue.
updated, shouldRequeue = true, true
}
if done := r.waitForRemoveMachine(logger, machines); done {
updated = true
}
if done, result, err := r.createOnDeleteReplacementMachines(ctx, logger, machineProvider, machines, idx); err != nil {
return result, err
} else if done {
updated = true
}
}
if !updated {
logger.V(4).Info(noUpdatesRequired)
}
if shouldRequeue {
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
return ctrl.Result{}, nil
}
// waitForReadyMachine checks machines and finds out whether to wait or not for any of them to become ready.
func (r *ControlPlaneMachineSetReconciler) waitForReadyMachine(logger logr.Logger, machines []machineproviders.MachineInfo) bool {
machinesPending := pendingMachines(machines)
machinesReady := readyMachines(machines)
machinesDeleting := deletingMachines(machines)
// Find out if and what Machines in this index need an update.
if isEmpty(machinesReady) && hasAny(machinesPending) && isEmpty(machinesDeleting) {
// There are No Ready Machines for this index but a Pending Machine Replacement is present.
// Wait for it to become Ready.
// Consider the first found pending machine for this index to be the replacement machine.
replacementMachine := machinesPending[0]
logger := logger.WithValues("index", replacementMachine.Index, "namespace", r.Namespace, "name", replacementMachine.MachineRef.ObjectMeta.Name)
logger.V(2).Info(waitingForReady)
return true
}
return false
}
// waitForReplacementMachine checks machines and finds out whether to wait or not for any replacement to become ready.
func (r *ControlPlaneMachineSetReconciler) waitForReplacementMachine(logger logr.Logger, machines []machineproviders.MachineInfo) bool {
machinesPending := pendingMachines(machines)
machinesNeedingReplacement := needReplacementMachines(machines)
if hasAny(machinesNeedingReplacement) && hasAny(machinesPending) {
// A Pending Machine Replacement already exists.
// Wait for it to become Ready.
// Consider the first found pending machine for this index to be the replacement machine.
replacementMachine := machinesPending[0]
// Consider the first found outdated machine for this index to be the one in need of update.
outdatedMachine := machinesNeedingReplacement[0]
logger := logger.WithValues("index", outdatedMachine.Index, "namespace", r.Namespace, "name", outdatedMachine.MachineRef.ObjectMeta.Name)
logger.V(2).WithValues("replacementName", replacementMachine.MachineRef.ObjectMeta.Name).Info(waitingForReplacement)
return true
}
return false
}
// waitForRemoveMachine checks machines and finds out whether to wait or not for any of them to be removed.
func (r *ControlPlaneMachineSetReconciler) waitForRemoveMachine(logger logr.Logger, machines []machineproviders.MachineInfo) bool {
machinesDeleting := deletingMachines(machines)
machinesUpdatedNonDeleted := updatedNonDeletedMachines(machines)
if hasAny(machinesDeleting) && hasAny(machinesUpdatedNonDeleted) {
// A replacement Machine exists, but the original has not been completely deleted yet.
// Wait for the deleted Machine to be removed.
// Consider the first found deleted machine for this index to be the deleting machine.
deletedMachine := machinesDeleting[0]
logger := logger.WithValues("index", deletedMachine.Index, "namespace", r.Namespace, "name", deletedMachine.MachineRef.ObjectMeta.Name)
logger.V(2).Info(waitingForRemoved)
return true
}
return false
}
func (r *ControlPlaneMachineSetReconciler) deleteReplacedMachines(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, machines []machineproviders.MachineInfo) (bool, ctrl.Result, error) {
if len(machines) < 2 {
// No need to delete any machines if there are less than 2 machines in an index.
return false, ctrl.Result{}, nil
}
machinesNeedingReplacement := needReplacementMachines(machines)
machinesUpdated := updatedMachines(machines)
machinesOutdatedNonReady := nonReadyMachines(machinesNeedingReplacement)
var toDeleteMachine machineproviders.MachineInfo
if hasAny(machinesNeedingReplacement) && hasAny(machinesUpdated) {
// The Outdated Machine still exists for this index,
// but an Updated replacement exists for it.
// Thus it is safe to trigger its Deletion.
toDeleteMachine = machinesNeedingReplacement[0]
}
if hasAny(machinesOutdatedNonReady) {
// An Outdated Machine exists for this index,
// and the machine is also Not Ready.
// This usually happens when a second generation of machines is created as replacements,
// but the configuration is broken or the Machine simply never becomes Ready.
// This means the Machine should be deleted to make room for a "third generation" replacement machine.
toDeleteMachine = machinesOutdatedNonReady[0]
}
if len(machinesUpdated) > 1 {
// More than one Updated (Ready and Up-to-date) Machine exists for this index.
// This means there is an excess in Updated Machines for this index and
// the oldest Machine in this state should be deleted.
toDeleteMachine = sortMachineInfoByCreationTimestamp(machinesUpdated)[0]
}
// Check if any Machine was deemed for deletion.
if toDeleteMachine.MachineRef != nil {
logger := logger.WithValues("index", toDeleteMachine.Index, "namespace", r.Namespace, "name", toDeleteMachine.MachineRef.ObjectMeta.Name)
if !isDeletedMachine(toDeleteMachine) {
result, err := deleteMachine(ctx, logger, machineProvider, toDeleteMachine, r.Namespace)
if err != nil {
return false, result, err
}
return true, result, nil
}
// The Outdated Machine has already been marked for deletion.
return true, ctrl.Result{}, nil
}
return false, ctrl.Result{}, nil
}
// create replacement machines for the OnDelete method.
// this function will attempt to create new machines when none are available
// in the machine info, or when there is a machine that needs an update for
// which no replacement has been created.
func (r *ControlPlaneMachineSetReconciler) createOnDeleteReplacementMachines(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, machines []machineproviders.MachineInfo, idx int32) (bool, ctrl.Result, error) {
if isEmpty(machines) {
// No Machines exist for this index.
// Trigger a Machine creation.
logger := logger.WithValues("index", idx, "namespace", r.Namespace, "name", unknownMachineName)
_, result, err := r.createMachine(ctx, logger, machineProvider, idx)
if err != nil {
return false, result, err
}
return true, result, nil
}
machinesNeedingReplacement := needReplacementMachines(machines)
if len(machines) == 1 && len(machinesNeedingReplacement) == 1 {
// if there is only 1 machine and it needs an update
logger := logger.WithValues("index", machines[0].Index, "namespace", r.Namespace, "name", machines[0].MachineRef.ObjectMeta.Name)
if isDeletedMachine(machines[0]) {
// if deleted create the replacement
_, result, err := r.createMachine(ctx, logger, machineProvider, idx)
if err != nil {
return false, result, err
}
return true, result, nil
} else {
// if not deleted, tell the user to delete it
logger.V(2).WithValues("diff", machines[0].Diff).Info(machineRequiresDeleteBeforeUpdate)
return true, ctrl.Result{}, nil
}
}
return false, ctrl.Result{}, nil
}
// create replacement machines for the RollingUpdate method.
// this function will attempt to create new machines when none are available
// in the machine info, or when there is a machine that needs an update for
// which no replacement has been created. in all cases it will observe the
// surge parameters when creating new machines.
func (r *ControlPlaneMachineSetReconciler) createRollingUpdateReplacementMachines(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, machines []machineproviders.MachineInfo, idx int32, maxSurge int, surgeCount *int) (bool, ctrl.Result, error) {
machinesNeedingReplacement := needReplacementMachines(machines)
machinesPending := pendingMachines(machines)
machinesUpdatedNonDeleted := updatedNonDeletedMachines(machines)
if isEmpty(machines) {
// No Machines exist for this index.
// Trigger a Machine creation.
logger := logger.WithValues("index", idx, "namespace", r.Namespace, "name", unknownMachineName)
result, err := r.createMachineWithSurge(ctx, logger, machineProvider, idx, maxSurge, surgeCount)
if err != nil {
return false, result, err
}
return true, result, nil
}
if hasAny(machinesNeedingReplacement) && isEmpty(machinesUpdatedNonDeleted) && isEmpty(machinesPending) {
// A Machine for this index needs updating (or has been deleted).
// No Updated (non-terminated) or Pending (Updated, Non-Ready) Replacement Machine exist for it.
// Trigger a Machine creation.
// Consider the first found outdated machine for this index to be the one in need of update.
outdatedMachine := machinesNeedingReplacement[0]
logger := logger.WithValues("index", outdatedMachine.Index, "namespace", r.Namespace, "name", outdatedMachine.MachineRef.ObjectMeta.Name)
// The diff will be nil if the machine has been deleted.
// Only log whether a machine requires an update if diff is not nil.
if outdatedMachine.Diff != nil {
logger.V(2).WithValues("diff", outdatedMachine.Diff).Info(machineRequiresUpdate)
}
result, err := r.createMachineWithSurge(ctx, logger, machineProvider, outdatedMachine.Index, maxSurge, surgeCount)
if err != nil {
return false, result, err
}
return true, result, nil
}
return false, ctrl.Result{}, nil
}
// deleteMachine deletes the Machine provided.
func deleteMachine(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, outdatedMachine machineproviders.MachineInfo, namespace string) (ctrl.Result, error) { //nolint:unparam
if err := machineProvider.DeleteMachine(ctx, logger, outdatedMachine.MachineRef); err != nil {
werr := fmt.Errorf("error deleting Machine %s/%s: %w", namespace, outdatedMachine.MachineRef.ObjectMeta.Name, err)
logger.Error(werr, errorDeletingMachine)
return ctrl.Result{}, werr
}
logger.V(2).Info(removingOldMachine)
return ctrl.Result{}, nil
}
// createMachine checks if a machine already exists and otherwise creates the Machine provided.
func (r *ControlPlaneMachineSetReconciler) createMachine(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, idx int32) (bool, ctrl.Result, error) { //nolint:unparam
// Check if a replacement machine already exists and
// was not previously detected due to potential stale cache.
exists, err := r.checkForExistingReplacement(ctx, logger, machineProvider, idx)
if err != nil {
return false, ctrl.Result{}, fmt.Errorf("error checking for existing replacement: %w", err)
}
if exists {
// A machine within the index for which we are about to
// create a replacement already has a replacement machine.
// This means the machine provider cache was stale when we previously checked.
// No need to create a replacement.
logger.V(2).Info(alreadyPresentReplacement)
// Do not error but signal the machine was not created (created=false).
return false, ctrl.Result{}, nil
}
if err := machineProvider.CreateMachine(ctx, logger, idx); err != nil {
werr := fmt.Errorf("error creating new Machine for index %d: %w", idx, err)
logger.Error(werr, errorCreatingMachine)
return false, ctrl.Result{}, werr
}
logger.V(2).Info(createdReplacement)
return true, ctrl.Result{}, nil
}
// createMachineWithSurge creates the Machine provided while observing the surge count.
// This function will not create machines if the current surgeCount is greater
// than the maxSurge. If it does create a machine, it will increase the surgeCount.
func (r *ControlPlaneMachineSetReconciler) createMachineWithSurge(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, idx int32, maxSurge int, surgeCount *int) (ctrl.Result, error) {
// Check if a surge in Machines is allowed.
if *surgeCount >= maxSurge {
// No more room to surge
logger.V(2).Info(noCapacityForExpansion)
return ctrl.Result{}, nil
}
// There is still room to surge,
// trigger a Replacement Machine creation.
created, result, err := r.createMachine(ctx, logger, machineProvider, idx)
if err != nil {
return result, err
}
if created {
*surgeCount++
}
return result, nil
}
// checkForExistingReplacement checks with an uncached API client if a specific index,
// already has an existing, up to date, replacement machine.
func (r *ControlPlaneMachineSetReconciler) checkForExistingReplacement(ctx context.Context, logger logr.Logger, machineProvider machineproviders.MachineProvider, idx int32) (bool, error) {
// Define an uncached machine provider.
uncachedMachineProvider, err := machineProvider.WithClient(ctx, logger, r.UncachedClient)
if err != nil {
return false, fmt.Errorf("could not get uncached machine provider: %w", err)
}
mInfos, err := uncachedMachineProvider.GetMachineInfos(ctx, logger)
if err != nil {
return false, fmt.Errorf("error getting Machines: %w", err)
}
for _, m := range mInfos {
if m.Index == idx && !m.NeedsUpdate && m.MachineRef.ObjectMeta.DeletionTimestamp == nil {
// An up to date Machine has been found for the specified index,
// meaning an updated replacement already exists for this index.
return true, nil
}
}
return false, nil
}
// isDeletedMachine checks if a machine is deleted.
func isDeletedMachine(m machineproviders.MachineInfo) bool {
return m.MachineRef.ObjectMeta.DeletionTimestamp != nil
}
// needReplacementMachines returns the list of MachineInfo which have Machines that need an update or have
// been deleted.
func needReplacementMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
needsReplacement := []machineproviders.MachineInfo{}
for _, m := range machinesInfo {
if m.NeedsUpdate || isDeletedMachine(m) {
needsReplacement = append(needsReplacement, m)
}
}
return needsReplacement
}
// deletingMachines returns the list of MachineInfo which have a Machine with a deletion timestamp.
func deletingMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for _, m := range machinesInfo {
if isDeletedMachine(m) {
result = append(result, m)
}
}
return result
}
// pendingMachines returns the list of MachineInfo which have a Pending Machine and are not pending deletion.
// A Machine pending deletion should not be considered pending as it will never progress into a Ready Machine.
func pendingMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for i := range machinesInfo {
if !machinesInfo[i].Ready && !machinesInfo[i].NeedsUpdate && !isDeletedMachine(machinesInfo[i]) {
result = append(result, machinesInfo[i])
}
}
return result
}
// updatedMachines returns the list of MachineInfo which have an Updated (Spec up-to-date and Ready) Machine.
func updatedMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for i := range machinesInfo {
if machinesInfo[i].Ready && !machinesInfo[i].NeedsUpdate {
result = append(result, machinesInfo[i])
}
}
return result
}
// updatedNonDeletedMachines returns the list of MachineInfo which have an Updated (Spec up-to-date and Ready) Machine and
// are not pending deletion.
func updatedNonDeletedMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for i := range machinesInfo {
if machinesInfo[i].Ready && !machinesInfo[i].NeedsUpdate && !isDeletedMachine(machinesInfo[i]) {
result = append(result, machinesInfo[i])
}
}
return result
}
// readyMachines returns the list of MachineInfo which have a Ready Machine.
func readyMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for i := range machinesInfo {
if machinesInfo[i].Ready {
result = append(result, machinesInfo[i])
}
}
return result
}
// nonReadyMachines returns the list of MachineInfo which have a Non Ready Machine.
func nonReadyMachines(machinesInfo []machineproviders.MachineInfo) []machineproviders.MachineInfo {
result := []machineproviders.MachineInfo{}
for i := range machinesInfo {
if !machinesInfo[i].Ready {
result = append(result, machinesInfo[i])
}
}
return result
}
// indexToMachineInfos pairs an index with a list of machineInfos.
type indexToMachineInfos struct {
// index is the index of the machines represented in the MachineInfos.
index int32
// machineInfos is the list of MachineInfos for the index.
machineInfos []machineproviders.MachineInfo
}
// sortMachineInfosByIndex returns a list numerically sorted by index, of each index' MachineInfos.
func sortMachineInfosByIndex(indexedMachineInfos map[int32][]machineproviders.MachineInfo) []indexToMachineInfos {
slice := []indexToMachineInfos{}
for idx, machines := range indexedMachineInfos {
slice = append(slice, indexToMachineInfos{
index: idx,
machineInfos: machines,
})
}
sort.Slice(slice, func(i, j int) bool {
return slice[i].index < slice[j].index
})
return slice
}
// sortMachineInfoByCreationTimestamp returns a slice of MachineInfo sorted by Machine's CreationTimestamp.
func sortMachineInfoByCreationTimestamp(machineInfos []machineproviders.MachineInfo) []machineproviders.MachineInfo {
sort.Slice(machineInfos, func(i, j int) bool {
return machineInfos[i].MachineRef.ObjectMeta.CreationTimestamp.Before(&machineInfos[j].MachineRef.ObjectMeta.CreationTimestamp)
})
return machineInfos
}
// machineInfosMaptoSlice returns a slice of MachineInfos from a map of MachineInfos slices.
func machineInfosMaptoSlice(indexedMachineInfos map[int32][]machineproviders.MachineInfo) []machineproviders.MachineInfo {
slice := []machineproviders.MachineInfo{}
for _, machines := range indexedMachineInfos {
slice = append(slice, machines...)
}
return slice
}
// deviseExistingSurge computes the current amount of replicas surge for the ControlPlaneMachineSet.
func deviseExistingSurge(cpms *machinev1.ControlPlaneMachineSet, mis []indexToMachineInfos) int {
desiredReplicas := int(*cpms.Spec.Replicas)
currentReplicas := 0
for _, mi := range mis {
currentReplicas += len(mi.machineInfos)
}
return currentReplicas - desiredReplicas
}
// hasAny checks if a MachineInfo slice contains at least 1 element.
func hasAny(machinesInfo []machineproviders.MachineInfo) bool {
return len(machinesInfo) > 0
}
// isEmpty checks if a MachineInfo slice is empty.
func isEmpty(machinesInfo []machineproviders.MachineInfo) bool {
return len(machinesInfo) == 0
}