-
Notifications
You must be signed in to change notification settings - Fork 120
/
machine_util.go
1524 lines (1315 loc) · 55.4 KB
/
machine_util.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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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/util/pod_util.go
Modifications Copyright (c) 2017 SAP SE or an SAP affiliate company. All rights reserved.
*/
// Package controller is used to provide the core functionalities of machine-controller-manager
package controller
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math"
"runtime"
"strings"
"time"
machineapi "github.com/gardener/machine-controller-manager/pkg/apis/machine"
"github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
"github.com/gardener/machine-controller-manager/pkg/util/nodeops"
"github.com/gardener/machine-controller-manager/pkg/util/provider/drain"
"github.com/gardener/machine-controller-manager/pkg/util/provider/driver"
"github.com/gardener/machine-controller-manager/pkg/util/provider/machinecodes/codes"
"github.com/gardener/machine-controller-manager/pkg/util/provider/machinecodes/status"
"github.com/gardener/machine-controller-manager/pkg/util/provider/machineutils"
utilstrings "github.com/gardener/machine-controller-manager/pkg/util/strings"
utiltime "github.com/gardener/machine-controller-manager/pkg/util/time"
v1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
)
// emptyMap is a dummy emptyMap to compare with
var emptyMap = make(map[string]string)
const (
maxReplacements = 1
pollInterval = 100 * time.Millisecond
lockAcquireTimeout = 1 * time.Second
cacheUpdateTimeout = 1 * time.Second
)
// TODO: use client library instead when it starts to support update retries
//
// see https://github.com/kubernetes/kubernetes/issues/21479
type updateMachineFunc func(machine *v1alpha1.Machine) error
/*
// UpdateMachineWithRetries updates a machine with given applyUpdate function. Note that machine not found error is ignored.
// The returned bool value can be used to tell if the machine is actually updated.
func UpdateMachineWithRetries(machineClient v1alpha1client.MachineInterface, machineLister v1alpha1listers.MachineLister, namespace, name string, applyUpdate updateMachineFunc) (*v1alpha1.Machine, error) {
var machine *v1alpha1.Machine
retryErr := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
var err error
machine, err = machineLister.Machines(namespace).Get(name)
if err != nil {
return err
}
machine = machine.DeepCopy()
// Apply the update, then attempt to push it to the apiserver.
if applyErr := applyUpdate(machine); applyErr != nil {
return applyErr
}
machine, err = machineClient.Update(machine)
return err
})
// Ignore the precondition violated error, this machine is already updated
// with the desired label.
if retryErr == errorsutil.ErrPreconditionViolated {
klog.V(4).Infof("Machine %s precondition doesn't hold, skip updating it.", name)
retryErr = nil
}
return machine, retryErr
}
*/
// ValidateMachineClass validates the machine class.
func (c *controller) ValidateMachineClass(ctx context.Context, classSpec *v1alpha1.ClassSpec) (*v1alpha1.MachineClass, map[string][]byte, machineutils.RetryPeriod, error) {
var (
machineClass *v1alpha1.MachineClass
err error
retry = machineutils.LongRetry
)
if classSpec.Kind != machineutils.MachineClassKind {
return c.TryMachineClassMigration(ctx, classSpec)
}
machineClass, err = c.machineClassLister.MachineClasses(c.namespace).Get(classSpec.Name)
if err != nil {
klog.Errorf("MachineClass %s/%s not found. Skipping. %v", c.namespace, classSpec.Name, err)
return nil, nil, retry, err
}
internalMachineClass := &machineapi.MachineClass{}
err = c.internalExternalScheme.Convert(machineClass, internalMachineClass, nil)
if err != nil {
klog.Warning("Error in scheme conversion")
return nil, nil, retry, err
}
secretData, err := c.getSecretData(machineClass.Name, machineClass.SecretRef, machineClass.CredentialsSecretRef)
if err != nil {
klog.V(2).Infof("Could not compute secret data: %+v", err)
return nil, nil, retry, err
}
if finalizers := sets.NewString(machineClass.Finalizers...); !finalizers.Has(MCMFinalizerName) {
c.machineClassQueue.Add(machineClass.Name)
errMessage := fmt.Sprintf("The machine class %s has no finalizers set. So not reconciling the machine.", machineClass.Name)
err := errors.New(errMessage)
klog.Warning(errMessage)
return nil, nil, machineutils.ShortRetry, err
}
err = c.validateNodeTemplate(machineClass.NodeTemplate)
if err != nil {
klog.Warning(err)
return nil, nil, machineutils.ShortRetry, err
}
return machineClass, secretData, retry, nil
}
func (c *controller) getSecretData(machineClassName string, secretRefs ...*v1.SecretReference) (map[string][]byte, error) {
var secretData map[string][]byte
for _, secretRef := range secretRefs {
if secretRef == nil {
continue
}
secretRef, err := c.getSecret(secretRef, machineClassName)
if err != nil {
klog.V(2).Infof("Secret reference %s/%s not found", secretRef.Namespace, secretRef.Name)
return nil, err
}
if secretRef != nil {
secretData = mergeDataMaps(secretData, secretRef.Data)
}
}
return secretData, nil
}
// validateNodeTemplate validates the optional nodeTemplate field is configured in the MachineClass
func (c *controller) validateNodeTemplate(nodeTemplate *v1alpha1.NodeTemplate) error {
var allErr []error
capacityAttributes := []v1.ResourceName{"cpu", "gpu", "memory"}
if nodeTemplate == nil {
return nil
}
for _, attribute := range capacityAttributes {
if _, ok := nodeTemplate.Capacity[attribute]; !ok {
err := errors.New("MachineClass NodeTemplate Capacity should mandatorily have CPU, GPU and Memory configured")
allErr = append(allErr, err)
}
}
if nodeTemplate.InstanceType == "" || nodeTemplate.Region == "" || nodeTemplate.Zone == "" {
err := errors.New("MachineClass NodeTemplate Instance Type, region and zone cannot be empty")
allErr = append(allErr, err)
}
if allErr != nil {
return fmt.Errorf("%s", allErr)
}
return nil
}
// getSecret retrieves the kubernetes secret if found
func (c *controller) getSecret(ref *v1.SecretReference, MachineClassName string) (*v1.Secret, error) {
if ref == nil {
// If no secretRef, return nil
return nil, nil
}
secretRef, err := c.secretLister.Secrets(ref.Namespace).Get(ref.Name)
if err != nil && apierrors.IsNotFound(err) {
klog.V(3).Infof("No secret %q: found for MachineClass %q", ref, MachineClassName)
return nil, nil
} else if err != nil {
klog.Errorf("Unable get secret %q for MachineClass %q: %v", MachineClassName, ref, err)
return nil, err
}
return secretRef, err
}
// nodeConditionsHaveChanged compares two node statuses to see if any of the statuses have changed
func nodeConditionsHaveChanged(machineConditions []v1.NodeCondition, nodeConditions []v1.NodeCondition) bool {
if len(machineConditions) != len(nodeConditions) {
return true
}
for i := range nodeConditions {
if nodeConditions[i].Status != machineConditions[i].Status {
return true
}
}
return false
}
func mergeDataMaps(in map[string][]byte, maps ...map[string][]byte) map[string][]byte {
out := make(map[string][]byte)
for _, m := range append([]map[string][]byte{in}, maps...) {
for k, v := range m {
out[k] = v
}
}
return out
}
// syncMachineNodeTemplate syncs nodeTemplates between machine and corresponding node-object.
// It ensures, that any nodeTemplate element available on Machine should be available on node-object.
// Although there could be more elements already available on node-object which will not be touched.
func (c *controller) syncMachineNodeTemplates(ctx context.Context, machine *v1alpha1.Machine) (machineutils.RetryPeriod, error) {
var (
initializedNodeAnnotation bool
currentlyAppliedALTJSONByte []byte
lastAppliedALT v1alpha1.NodeTemplateSpec
)
node, err := c.nodeLister.Get(machine.Status.Node)
if err != nil && apierrors.IsNotFound(err) {
// Dont return error so that other steps can be executed.
return machineutils.LongRetry, nil
}
if err != nil {
klog.Errorf("Error occurred while trying to fetch node object - err: %s", err)
return machineutils.LongRetry, err
}
nodeCopy := node.DeepCopy()
// Initialize node annotations if empty
if nodeCopy.Annotations == nil {
nodeCopy.Annotations = make(map[string]string)
initializedNodeAnnotation = true
}
// Extracts the last applied annotations to lastAppliedLabels
lastAppliedALTJSONString, exists := node.Annotations[machineutils.LastAppliedALTAnnotation]
if exists {
err = json.Unmarshal([]byte(lastAppliedALTJSONString), &lastAppliedALT)
if err != nil {
klog.Errorf("Error occurred while syncing node annotations, labels & taints: %s", err)
return machineutils.ShortRetry, err
}
}
annotationsChanged := SyncMachineAnnotations(machine, nodeCopy, lastAppliedALT.Annotations)
labelsChanged := SyncMachineLabels(machine, nodeCopy, lastAppliedALT.Labels)
taintsChanged := SyncMachineTaints(machine, nodeCopy, lastAppliedALT.Spec.Taints)
// Update node-object with latest nodeTemplate elements if elements have changed.
if initializedNodeAnnotation || labelsChanged || annotationsChanged || taintsChanged {
klog.V(2).Infof(
"Updating machine annotations:%v, labels:%v, taints:%v for machine: %q with providerID: %q and backing node: %q",
annotationsChanged,
labelsChanged,
taintsChanged,
machine.Name,
getProviderID(machine),
getNodeName(machine),
)
// Update the machineutils.LastAppliedALTAnnotation
lastAppliedALT = machine.Spec.NodeTemplateSpec
currentlyAppliedALTJSONByte, err = json.Marshal(lastAppliedALT)
if err != nil {
klog.Errorf("Error occurred while syncing node annotations, labels & taints: %s", err)
return machineutils.ShortRetry, err
}
nodeCopy.Annotations[machineutils.LastAppliedALTAnnotation] = string(currentlyAppliedALTJSONByte)
_, err := c.targetCoreClient.CoreV1().Nodes().Update(ctx, nodeCopy, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Errorf("Updated failed for node object of machine %q. Retrying, error: %q", machine.Name, err)
} else {
// Return error even when machine object is updated
err = fmt.Errorf("Machine ALTs have been reconciled")
}
return machineutils.ShortRetry, err
}
return machineutils.LongRetry, nil
}
// SyncMachineAnnotations syncs the annotations of the machine with node-objects.
// It returns true if update is needed else false.
func SyncMachineAnnotations(
machine *v1alpha1.Machine,
node *v1.Node,
lastAppliedAnnotations map[string]string,
) bool {
toBeUpdated := false
mAnnotations, nAnnotations := machine.Spec.NodeTemplateSpec.Annotations, node.Annotations
// Initialize node annotations if nil
if nAnnotations == nil {
nAnnotations = make(map[string]string)
node.Annotations = nAnnotations
}
// Intialize machine annotations to empty map if nil
if mAnnotations == nil {
mAnnotations = emptyMap
}
// Delete any annotation that existed in the past but has been deleted now
for lastAppliedAnnotationKey := range lastAppliedAnnotations {
if _, exists := mAnnotations[lastAppliedAnnotationKey]; !exists {
delete(nAnnotations, lastAppliedAnnotationKey)
toBeUpdated = true
}
}
// Add/Update any key that doesn't exist or whose value as changed
for mKey, mValue := range mAnnotations {
if nValue, exists := nAnnotations[mKey]; !exists || mValue != nValue {
nAnnotations[mKey] = mValue
toBeUpdated = true
}
}
return toBeUpdated
}
// SyncMachineLabels syncs the labels of the machine with node-objects.
// It returns true if update is needed else false.
func SyncMachineLabels(
machine *v1alpha1.Machine,
node *v1.Node,
lastAppliedLabels map[string]string,
) bool {
toBeUpdated := false
mLabels, nLabels := machine.Spec.NodeTemplateSpec.Labels, node.Labels
// Initialize node labels if nil
if nLabels == nil {
nLabels = make(map[string]string)
node.Labels = nLabels
}
// Intialize machine labels to empty map if nil
if mLabels == nil {
mLabels = emptyMap
}
// Delete any labels that existed in the past but has been deleted now
for lastAppliedLabelKey := range lastAppliedLabels {
if _, exists := mLabels[lastAppliedLabelKey]; !exists {
delete(nLabels, lastAppliedLabelKey)
toBeUpdated = true
}
}
// Add/Update any key that doesn't exist or whose value as changed
for mKey, mValue := range mLabels {
if nValue, exists := nLabels[mKey]; !exists || mValue != nValue {
nLabels[mKey] = mValue
toBeUpdated = true
}
}
return toBeUpdated
}
type taintKeyEffect struct {
// Required. The taint key to be applied to a node.
Key string
// Valid effects are NoSchedule, PreferNoSchedule and NoExecute.
Effect v1.TaintEffect
}
// SyncMachineTaints syncs the taints of the machine with node-objects.
// It returns true if update is needed else false.
func SyncMachineTaints(
machine *v1alpha1.Machine,
node *v1.Node,
lastAppliedTaints []v1.Taint,
) bool {
toBeUpdated := false
mTaints, nTaints := machine.Spec.NodeTemplateSpec.Spec.Taints, node.Spec.Taints
mTaintsMap := make(map[taintKeyEffect]*v1.Taint, 0)
nTaintsMap := make(map[taintKeyEffect]*v1.Taint, 0)
// Convert the slice of taints to map of taint [key, effect] = Taint
// Helps with indexed searching
for i := range mTaints {
mTaint := &mTaints[i]
taintKE := taintKeyEffect{
Key: mTaint.Key,
Effect: mTaint.Effect,
}
mTaintsMap[taintKE] = mTaint
}
for i := range nTaints {
nTaint := &nTaints[i]
taintKE := taintKeyEffect{
Key: nTaint.Key,
Effect: nTaint.Effect,
}
nTaintsMap[taintKE] = nTaint
}
// Delete taints that existed on the machine object in the last update but deleted now
for _, lastAppliedTaint := range lastAppliedTaints {
lastAppliedKE := taintKeyEffect{
Key: lastAppliedTaint.Key,
Effect: lastAppliedTaint.Effect,
}
if _, exists := mTaintsMap[lastAppliedKE]; !exists {
delete(nTaintsMap, lastAppliedKE)
toBeUpdated = true
}
}
// Add any taints that exists in the machine object but not on the node object
for mKE, mV := range mTaintsMap {
if nV, exists := nTaintsMap[mKE]; !exists || *nV != *mV {
nTaintsMap[mKE] = mV
toBeUpdated = true
}
}
if toBeUpdated {
// Convert the map of taints to slice of taints
nTaints = make([]v1.Taint, len(nTaintsMap))
i := 0
for _, nV := range nTaintsMap {
nTaints[i] = *nV
i++
}
node.Spec.Taints = nTaints
}
return toBeUpdated
}
// machineCreateErrorHandler TODO
func (c *controller) machineCreateErrorHandler(ctx context.Context, machine *v1alpha1.Machine, createMachineResponse *driver.CreateMachineResponse, err error) (machineutils.RetryPeriod, error) {
var (
retryRequired = machineutils.MediumRetry
lastKnownState string
)
if machineErr, ok := status.FromError(err); ok {
switch machineErr.Code() {
case codes.Unknown, codes.DeadlineExceeded, codes.Aborted, codes.Unavailable:
retryRequired = machineutils.ShortRetry
}
}
if createMachineResponse != nil && createMachineResponse.LastKnownState != "" {
lastKnownState = createMachineResponse.LastKnownState
}
c.machineStatusUpdate(
ctx,
machine,
v1alpha1.LastOperation{
Description: "Cloud provider message - " + err.Error(),
State: v1alpha1.MachineStateFailed,
Type: v1alpha1.MachineOperationCreate,
LastUpdateTime: metav1.Now(),
},
v1alpha1.CurrentStatus{
Phase: c.getCreateFailurePhase(machine),
LastUpdateTime: metav1.Now(),
},
lastKnownState,
)
return retryRequired, nil
}
func (c *controller) machineStatusUpdate(
ctx context.Context,
machine *v1alpha1.Machine,
lastOperation v1alpha1.LastOperation,
currentStatus v1alpha1.CurrentStatus,
lastKnownState string,
) error {
clone := machine.DeepCopy()
clone.Status.LastOperation = lastOperation
clone.Status.CurrentStatus = currentStatus
clone.Status.LastKnownState = lastKnownState
if isMachineStatusSimilar(clone.Status, machine.Status) {
klog.V(3).Infof("Not updating the status of the machine object %q, as the content is similar", clone.Name)
return nil
}
_, err := c.controlMachineClient.Machines(clone.Namespace).UpdateStatus(ctx, clone, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Warningf("Machine/status UPDATE failed for machine %q. Retrying, error: %s", machine.Name, err)
} else {
klog.V(2).Infof("Machine/status UPDATE for %q", machine.Name)
}
return err
}
// isMachineStatusSimilar checks if the status of 2 machines is similar or not.
func isMachineStatusSimilar(s1, s2 v1alpha1.MachineStatus) bool {
s1Copy, s2Copy := s1.DeepCopy(), s2.DeepCopy()
tolerateTimeDiff := 30 * time.Minute
// Since lastOperation hasn't been updated in the last 30minutes, force update this.
if (s1.LastOperation.LastUpdateTime.Time.Before(time.Now().Add(tolerateTimeDiff * -1))) || (s2.LastOperation.LastUpdateTime.Time.Before(time.Now().Add(tolerateTimeDiff * -1))) {
return false
}
if utilstrings.StringSimilarityRatio(s1Copy.LastOperation.Description, s2Copy.LastOperation.Description) > 0.75 {
// If strings are similar, ignore comparison
// This occurs when cloud provider errors repeats with different request IDs
s1Copy.LastOperation.Description, s2Copy.LastOperation.Description = "", ""
}
// Avoiding timestamp comparison
s1Copy.LastOperation.LastUpdateTime, s2Copy.LastOperation.LastUpdateTime = metav1.Time{}, metav1.Time{}
s1Copy.CurrentStatus.LastUpdateTime, s2Copy.CurrentStatus.LastUpdateTime = metav1.Time{}, metav1.Time{}
return apiequality.Semantic.DeepEqual(s1Copy.LastOperation, s2Copy.LastOperation) && apiequality.Semantic.DeepEqual(s1Copy.CurrentStatus, s2Copy.CurrentStatus)
}
// getCreateFailurePhase gets the effective creation timeout
func (c *controller) getCreateFailurePhase(machine *v1alpha1.Machine) v1alpha1.MachinePhase {
timeOutDuration := c.getEffectiveCreationTimeout(machine).Duration
// Timeout value obtained by subtracting last operation with expected time out period
timeOut := metav1.Now().Add(-timeOutDuration).Sub(machine.CreationTimestamp.Time)
if timeOut > 0 {
// Machine creation timeout occured while joining of machine
// Machine set controller would replace this machine with a new one as phase is failed.
klog.V(2).Infof("Machine %q , providerID %q and backing node %q couldn't join in creation timeout of %s. Changing phase to failed.", machine.Name, getProviderID(machine), getNodeName(machine), timeOutDuration)
return v1alpha1.MachineFailed
}
return v1alpha1.MachineCrashLoopBackOff
}
// reconcileMachineHealth updates the machine object with
// any change in node conditions or health
func (c *controller) reconcileMachineHealth(ctx context.Context, machine *v1alpha1.Machine) (machineutils.RetryPeriod, error) {
var (
cloneDirty = false
clone = machine.DeepCopy()
description string
lastOperationType v1alpha1.MachineOperationType
)
node, err := c.nodeLister.Get(machine.Status.Node)
if err != nil {
if apierrors.IsNotFound(err) {
// Node object is not found
if len(machine.Status.Conditions) > 0 &&
machine.Status.CurrentStatus.Phase == v1alpha1.MachineRunning {
// If machine has conditions on it,
// and corresponding node object went missing
// and if machine object still reports healthy
description = fmt.Sprintf(
"Node object went missing. Machine %s is unhealthy - changing MachineState to Unknown",
machine.Name,
)
klog.Warning(description)
clone.Status.CurrentStatus = v1alpha1.CurrentStatus{
Phase: v1alpha1.MachineUnknown,
// TimeoutActive: true,
LastUpdateTime: metav1.Now(),
}
clone.Status.LastOperation = v1alpha1.LastOperation{
Description: description,
State: v1alpha1.MachineStateProcessing,
Type: v1alpha1.MachineOperationHealthCheck,
LastUpdateTime: metav1.Now(),
}
cloneDirty = true
}
} else {
// Any other types of errors while fetching node object
klog.Errorf("Could not fetch node object for machine %q", machine.Name)
return machineutils.ShortRetry, err
}
} else {
if nodeConditionsHaveChanged(machine.Status.Conditions, node.Status.Conditions) {
clone.Status.Conditions = node.Status.Conditions
klog.V(3).Infof("Conditions of Machine %q with providerID %q and backing node %q are changing", machine.Name, getProviderID(machine), getNodeName(machine))
cloneDirty = true
}
if !c.isHealthy(clone) && clone.Status.CurrentStatus.Phase == v1alpha1.MachineRunning {
// If machine is not healthy, and current state is running,
// change the machinePhase to unknown and activate health check timeout
description = fmt.Sprintf("Machine %s is unhealthy - changing MachineState to Unknown. Node conditions: %+v", clone.Name, clone.Status.Conditions)
klog.Warning(description)
clone.Status.CurrentStatus = v1alpha1.CurrentStatus{
Phase: v1alpha1.MachineUnknown,
// TimeoutActive: true,
LastUpdateTime: metav1.Now(),
}
clone.Status.LastOperation = v1alpha1.LastOperation{
Description: description,
State: v1alpha1.MachineStateProcessing,
Type: v1alpha1.MachineOperationHealthCheck,
LastUpdateTime: metav1.Now(),
}
cloneDirty = true
} else if c.isHealthy(clone) && clone.Status.CurrentStatus.Phase != v1alpha1.MachineRunning {
// If machine is healhy and current machinePhase is not running.
// indicates that the machine is not healthy and status needs to be updated.
if clone.Status.LastOperation.Type == v1alpha1.MachineOperationCreate &&
clone.Status.LastOperation.State != v1alpha1.MachineStateSuccessful {
// When machine creation went through
description = fmt.Sprintf("Machine %s successfully joined the cluster", clone.Name)
lastOperationType = v1alpha1.MachineOperationCreate
// Delete the bootstrap token
err = c.deleteBootstrapToken(ctx, clone.Name)
if err != nil {
klog.Warning(err)
}
} else {
// Machine rejoined the cluster after a healthcheck
description = fmt.Sprintf("Machine %s successfully re-joined the cluster", clone.Name)
lastOperationType = v1alpha1.MachineOperationHealthCheck
}
klog.V(2).Info(description)
// Machine is ready and has joined/re-joined the cluster
clone.Status.LastOperation = v1alpha1.LastOperation{
Description: description,
State: v1alpha1.MachineStateSuccessful,
Type: lastOperationType,
LastUpdateTime: metav1.Now(),
}
clone.Status.CurrentStatus = v1alpha1.CurrentStatus{
Phase: v1alpha1.MachineRunning,
// TimeoutActive: false,
LastUpdateTime: metav1.Now(),
}
cloneDirty = true
}
}
if !cloneDirty &&
(machine.Status.CurrentStatus.Phase == v1alpha1.MachinePending ||
machine.Status.CurrentStatus.Phase == v1alpha1.MachineUnknown) {
var (
description string
timeOutDuration time.Duration
)
isMachinePending := machine.Status.CurrentStatus.Phase == v1alpha1.MachinePending
sleepTime := 1 * time.Minute
if isMachinePending {
timeOutDuration = c.getEffectiveCreationTimeout(machine).Duration
} else {
timeOutDuration = c.getEffectiveHealthTimeout(machine).Duration
}
// Timeout value obtained by subtracting last operation with expected time out period
timeOut := metav1.Now().Add(-timeOutDuration).Sub(machine.Status.CurrentStatus.LastUpdateTime.Time)
if timeOut > 0 {
// Machine health timeout occured while joining or rejoining of machine
if isMachinePending {
// Timeout occurred while machine creation
description = fmt.Sprintf(
"Machine %s failed to join the cluster in %s minutes.",
machine.Name,
timeOutDuration,
)
// Log the error message for machine failure
klog.Error(description)
clone.Status.LastOperation = v1alpha1.LastOperation{
Description: description,
State: v1alpha1.MachineStateFailed,
Type: machine.Status.LastOperation.Type,
LastUpdateTime: metav1.Now(),
}
clone.Status.CurrentStatus = v1alpha1.CurrentStatus{
Phase: v1alpha1.MachineFailed,
// TimeoutActive: false,
LastUpdateTime: metav1.Now(),
}
cloneDirty = true
} else {
// Timeout occurred due to machine being unhealthy for too long
description = fmt.Sprintf(
"Machine %s is not healthy since %s minutes. Changing status to failed. Node Conditions: %+v",
machine.Name,
timeOutDuration,
machine.Status.Conditions,
)
machineDeployName := getMachineDeploymentName(machine)
// creating lock for machineDeployment, if not allocated
c.permitGiver.RegisterPermits(machineDeployName, 1)
return c.tryMarkingMachineFailed(ctx, machine, clone, machineDeployName, description, lockAcquireTimeout)
}
} else {
// If timeout has not occurred, re-enqueue the machine
// after a specified sleep time
c.enqueueMachineAfter(machine, sleepTime)
}
}
if cloneDirty {
_, err = c.controlMachineClient.Machines(clone.Namespace).UpdateStatus(ctx, clone, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Errorf("Update failed for machine %q. Retrying, error: %q", machine.Name, err)
} else {
klog.V(2).Infof("Machine State has been updated for %q with providerID %q and backing node %q", machine.Name, getProviderID(machine), getNodeName(machine))
// Return error for continuing in next iteration
err = fmt.Errorf("machine creation is successful. Machine State has been UPDATED")
}
return machineutils.ShortRetry, err
}
return machineutils.LongRetry, nil
}
/*
SECTION
Manipulate Finalizers
*/
func (c *controller) addMachineFinalizers(ctx context.Context, machine *v1alpha1.Machine) (machineutils.RetryPeriod, error) {
if finalizers := sets.NewString(machine.Finalizers...); !finalizers.Has(MCMFinalizerName) {
finalizers.Insert(MCMFinalizerName)
clone := machine.DeepCopy()
clone.Finalizers = finalizers.List()
_, err := c.controlMachineClient.Machines(clone.Namespace).Update(ctx, clone, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Errorf("Failed to add finalizers for machine %q: %s", machine.Name, err)
} else {
// Return error even when machine object is updated
klog.V(2).Infof("Added finalizer to machine %q with providerID %q and backing node %q", machine.Name, getProviderID(machine), getNodeName(machine))
err = fmt.Errorf("Machine creation in process. Machine finalizers are UPDATED")
}
return machineutils.ShortRetry, err
}
return machineutils.ShortRetry, nil
}
func (c *controller) deleteMachineFinalizers(ctx context.Context, machine *v1alpha1.Machine) (machineutils.RetryPeriod, error) {
if finalizers := sets.NewString(machine.Finalizers...); finalizers.Has(MCMFinalizerName) {
finalizers.Delete(MCMFinalizerName)
clone := machine.DeepCopy()
clone.Finalizers = finalizers.List()
_, err := c.controlMachineClient.Machines(clone.Namespace).Update(ctx, clone, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Errorf("Failed to delete finalizers for machine %q: %s", machine.Name, err)
return machineutils.ShortRetry, err
}
klog.V(2).Infof("Removed finalizer to machine %q with providerID %q and backing node %q", machine.Name, getProviderID(machine), getNodeName(machine))
return machineutils.LongRetry, nil
}
return machineutils.LongRetry, nil
}
/*
SECTION
Helper Functions
*/
func (c *controller) isHealthy(machine *v1alpha1.Machine) bool {
numOfConditions := len(machine.Status.Conditions)
if numOfConditions == 0 {
// Kubernetes node object for this machine hasn't been received
return false
}
for _, condition := range machine.Status.Conditions {
if condition.Type == v1.NodeReady && condition.Status != v1.ConditionTrue {
// If Kubelet is not ready
return false
}
conditions := strings.Split(*c.getEffectiveNodeConditions(machine), ",")
for _, c := range conditions {
if string(condition.Type) == c && condition.Status != v1.ConditionFalse {
return false
}
}
}
return true
}
/*
SECTION
Delete machine
*/
// setMachineTerminationStatus set's the machine status to terminating
func (c *controller) setMachineTerminationStatus(ctx context.Context, deleteMachineRequest *driver.DeleteMachineRequest) (machineutils.RetryPeriod, error) {
clone := deleteMachineRequest.Machine.DeepCopy()
clone.Status.LastOperation = v1alpha1.LastOperation{
Description: machineutils.GetVMStatus,
State: v1alpha1.MachineStateProcessing,
Type: v1alpha1.MachineOperationDelete,
LastUpdateTime: metav1.Now(),
}
clone.Status.CurrentStatus = v1alpha1.CurrentStatus{
Phase: v1alpha1.MachineTerminating,
// TimeoutActive: false,
LastUpdateTime: metav1.Now(),
}
_, err := c.controlMachineClient.Machines(clone.Namespace).UpdateStatus(ctx, clone, metav1.UpdateOptions{})
if err != nil {
// Keep retrying until update goes through
klog.Errorf("Machine/status UPDATE failed for machine %q. Retrying, error: %s", deleteMachineRequest.Machine.Name, err)
} else {
klog.V(2).Infof("Machine %q status updated to terminating ", deleteMachineRequest.Machine.Name)
// Return error even when machine object is updated to ensure reconcilation is restarted
err = fmt.Errorf("Machine deletion in process. Phase set to termination")
}
return machineutils.ShortRetry, err
}
// getVMStatus tries to retrive VM status backed by machine
func (c *controller) getVMStatus(ctx context.Context, getMachineStatusRequest *driver.GetMachineStatusRequest) (machineutils.RetryPeriod, error) {
var (
retry machineutils.RetryPeriod
description string
state v1alpha1.MachineState
)
_, err := c.driver.GetMachineStatus(ctx, getMachineStatusRequest)
if err == nil {
// VM Found
description = machineutils.InitiateDrain
state = v1alpha1.MachineStateProcessing
retry = machineutils.ShortRetry
// Return error even when machine object is updated to ensure reconcilation is restarted
err = fmt.Errorf("Machine deletion in process. VM with matching ID found")
} else {
if machineErr, ok := status.FromError(err); !ok {
// Error occurred with decoding machine error status, aborting without retry.
description = "Error occurred with decoding machine error status while getting VM status, aborting without retry. " + err.Error() + " " + machineutils.GetVMStatus
state = v1alpha1.MachineStateFailed
retry = machineutils.LongRetry
err = fmt.Errorf("Machine deletion has failed. " + description)
} else {
// Decoding machine error code
switch machineErr.Code() {
case codes.Unimplemented:
// GetMachineStatus() call is not implemented
// In this case, try to drain and delete
description = machineutils.InitiateDrain
state = v1alpha1.MachineStateProcessing
retry = machineutils.ShortRetry
case codes.NotFound:
// VM was not found at provder
description = "VM was not found at provider. " + machineutils.InitiateNodeDeletion
state = v1alpha1.MachineStateProcessing
retry = machineutils.ShortRetry
case codes.Unknown, codes.DeadlineExceeded, codes.Aborted, codes.Unavailable:
description = "Error occurred with decoding machine error status while getting VM status, aborting with retry. " + machineutils.GetVMStatus
state = v1alpha1.MachineStateFailed
retry = machineutils.ShortRetry
default:
// Error occurred with decoding machine error status, abort with retry.
description = "Error occurred with decoding machine error status while getting VM status, aborting without retry. machine code: " + err.Error() + " " + machineutils.GetVMStatus
state = v1alpha1.MachineStateFailed
retry = machineutils.MediumRetry
}
}
}
c.machineStatusUpdate(
ctx,
getMachineStatusRequest.Machine,
v1alpha1.LastOperation{
Description: description,
State: state,
Type: v1alpha1.MachineOperationDelete,
LastUpdateTime: metav1.Now(),
},
// Let the clone.Status.CurrentStatus (LastUpdateTime) be as it was before.
// This helps while computing when the drain timeout to determine if force deletion is to be triggered.
// Ref - https://github.com/gardener/machine-controller-manager/blob/rel-v0.34.0/pkg/util/provider/machinecontroller/machine_util.go#L872
getMachineStatusRequest.Machine.Status.CurrentStatus,
getMachineStatusRequest.Machine.Status.LastKnownState,
)
return retry, err
}
// isValidNodeName checks if the nodeName is valid
func isValidNodeName(nodeName string) bool {
return nodeName != ""
}
// isConditionEmpty returns true if passed NodeCondition is empty
func isConditionEmpty(condition v1.NodeCondition) bool {
return condition == v1.NodeCondition{}
}
// initializes err and description with the passed string message
func printLogInitError(s string, err *error, description *string, machine *v1alpha1.Machine) {
klog.Warningf(s+" machine: %q ", machine.Name)
*err = fmt.Errorf(s+" %s", machineutils.InitiateVMDeletion)
*description = fmt.Sprintf(s+" %s", machineutils.InitiateVMDeletion)
}
// drainNode attempts to drain the node backed by the machine object
func (c *controller) drainNode(ctx context.Context, deleteMachineRequest *driver.DeleteMachineRequest) (machineutils.RetryPeriod, error) {
var (
// Declarations
err error
forceDeletePods bool
forceDeleteMachine bool
timeOutOccurred bool
skipDrain bool
description string
state v1alpha1.MachineState
readOnlyFileSystemCondition, nodeReadyCondition v1.NodeCondition
// Initialization
machine = deleteMachineRequest.Machine
maxEvictRetries = int32(math.Min(float64(*c.getEffectiveMaxEvictRetries(machine)), c.getEffectiveDrainTimeout(machine).Seconds()/drain.PodEvictionRetryInterval.Seconds()))
pvDetachTimeOut = c.safetyOptions.PvDetachTimeout.Duration
pvReattachTimeOut = c.safetyOptions.PvReattachTimeout.Duration
timeOutDuration = c.getEffectiveDrainTimeout(deleteMachineRequest.Machine).Duration
forceDeleteLabelPresent = machine.Labels["force-deletion"] == "True"
nodeName = machine.Labels["node"]
nodeNotReadyDuration = 5 * time.Minute
ReadonlyFilesystem v1.NodeConditionType = "ReadonlyFilesystem"
)
if !isValidNodeName(nodeName) {
message := "Skipping drain as nodeName is not a valid one for machine."
printLogInitError(message, &err, &description, machine)
skipDrain = true
} else {