-
Notifications
You must be signed in to change notification settings - Fork 431
/
machinepool.go
811 lines (701 loc) · 32.2 KB
/
machinepool.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
/*
Copyright 2020 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 scope
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"strings"
azureautorest "github.com/Azure/go-autorest/autorest/azure"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/pointer"
infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-azure/azure"
machinepool "sigs.k8s.io/cluster-api-provider-azure/azure/scope/strategies/machinepool_deployments"
"sigs.k8s.io/cluster-api-provider-azure/azure/services/roleassignments"
"sigs.k8s.io/cluster-api-provider-azure/azure/services/scalesets"
"sigs.k8s.io/cluster-api-provider-azure/azure/services/virtualmachineimages"
infrav1exp "sigs.k8s.io/cluster-api-provider-azure/exp/api/v1beta1"
"sigs.k8s.io/cluster-api-provider-azure/util/futures"
"sigs.k8s.io/cluster-api-provider-azure/util/tele"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
capierrors "sigs.k8s.io/cluster-api/errors"
expv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
// ScalesetsServiceName is the name of the scalesets service.
// TODO: move this to scalesets.go once we remove the usage in this package,
// added here to avoid a circular dependency.
const ScalesetsServiceName = "scalesets"
type (
// MachinePoolScopeParams defines the input parameters used to create a new MachinePoolScope.
MachinePoolScopeParams struct {
Client client.Client
MachinePool *expv1.MachinePool
AzureMachinePool *infrav1exp.AzureMachinePool
ClusterScope azure.ClusterScoper
}
// MachinePoolScope defines a scope defined around a machine pool and its cluster.
MachinePoolScope struct {
azure.ClusterScoper
AzureMachinePool *infrav1exp.AzureMachinePool
MachinePool *expv1.MachinePool
client client.Client
patchHelper *patch.Helper
capiMachinePoolPatchHelper *patch.Helper
vmssState *azure.VMSS
}
// NodeStatus represents the status of a Kubernetes node.
NodeStatus struct {
Ready bool
Version string
}
)
// NewMachinePoolScope creates a new MachinePoolScope from the supplied parameters.
// This is meant to be called for each reconcile iteration.
func NewMachinePoolScope(params MachinePoolScopeParams) (*MachinePoolScope, error) {
if params.Client == nil {
return nil, errors.New("client is required when creating a MachinePoolScope")
}
if params.MachinePool == nil {
return nil, errors.New("machine pool is required when creating a MachinePoolScope")
}
if params.AzureMachinePool == nil {
return nil, errors.New("azure machine pool is required when creating a MachinePoolScope")
}
helper, err := patch.NewHelper(params.AzureMachinePool, params.Client)
if err != nil {
return nil, errors.Wrap(err, "failed to init patch helper")
}
capiMachinePoolPatchHelper, err := patch.NewHelper(params.MachinePool, params.Client)
if err != nil {
return nil, errors.Wrap(err, "failed to init capi patch helper")
}
return &MachinePoolScope{
client: params.Client,
MachinePool: params.MachinePool,
AzureMachinePool: params.AzureMachinePool,
patchHelper: helper,
capiMachinePoolPatchHelper: capiMachinePoolPatchHelper,
ClusterScoper: params.ClusterScope,
}, nil
}
// ScaleSetSpec returns the scale set spec.
func (m *MachinePoolScope) ScaleSetSpec() azure.ScaleSetSpec {
return azure.ScaleSetSpec{
Name: m.Name(),
Size: m.AzureMachinePool.Spec.Template.VMSize,
Capacity: int64(pointer.Int32Deref(m.MachinePool.Spec.Replicas, 0)),
SSHKeyData: m.AzureMachinePool.Spec.Template.SSHPublicKey,
OSDisk: m.AzureMachinePool.Spec.Template.OSDisk,
DataDisks: m.AzureMachinePool.Spec.Template.DataDisks,
SubnetName: m.AzureMachinePool.Spec.Template.NetworkInterfaces[0].SubnetName,
VNetName: m.Vnet().Name,
VNetResourceGroup: m.Vnet().ResourceGroup,
PublicLBName: m.OutboundLBName(infrav1.Node),
PublicLBAddressPoolName: azure.GenerateOutboundBackendAddressPoolName(m.OutboundLBName(infrav1.Node)),
AcceleratedNetworking: m.AzureMachinePool.Spec.Template.NetworkInterfaces[0].AcceleratedNetworking,
Identity: m.AzureMachinePool.Spec.Identity,
UserAssignedIdentities: m.AzureMachinePool.Spec.UserAssignedIdentities,
DiagnosticsProfile: m.AzureMachinePool.Spec.Template.Diagnostics,
SecurityProfile: m.AzureMachinePool.Spec.Template.SecurityProfile,
SpotVMOptions: m.AzureMachinePool.Spec.Template.SpotVMOptions,
FailureDomains: m.MachinePool.Spec.FailureDomains,
TerminateNotificationTimeout: m.AzureMachinePool.Spec.Template.TerminateNotificationTimeout,
NetworkInterfaces: m.AzureMachinePool.Spec.Template.NetworkInterfaces,
OrchestrationMode: m.AzureMachinePool.Spec.OrchestrationMode,
}
}
// Name returns the Azure Machine Pool Name.
func (m *MachinePoolScope) Name() string {
// Windows Machine pools names cannot be longer than 9 chars
if m.AzureMachinePool.Spec.Template.OSDisk.OSType == azure.WindowsOS && len(m.AzureMachinePool.Name) > 9 {
return "win-" + m.AzureMachinePool.Name[len(m.AzureMachinePool.Name)-5:]
}
return m.AzureMachinePool.Name
}
// ProviderID returns the AzureMachinePool ID by parsing Spec.FakeProviderID.
func (m *MachinePoolScope) ProviderID() string {
parsed, err := noderefutil.NewProviderID(m.AzureMachinePool.Spec.ProviderID)
if err != nil {
return ""
}
return parsed.ID()
}
// SetProviderID sets the AzureMachinePool providerID in spec.
func (m *MachinePoolScope) SetProviderID(v string) {
m.AzureMachinePool.Spec.ProviderID = v
}
// SystemAssignedIdentityName returns the scope for the system assigned identity.
func (m *MachinePoolScope) SystemAssignedIdentityName() string {
if m.AzureMachinePool.Spec.SystemAssignedIdentityRole != nil {
return m.AzureMachinePool.Spec.SystemAssignedIdentityRole.Name
}
return ""
}
// SystemAssignedIdentityScope returns the scope for the system assigned identity.
func (m *MachinePoolScope) SystemAssignedIdentityScope() string {
if m.AzureMachinePool.Spec.SystemAssignedIdentityRole != nil {
return m.AzureMachinePool.Spec.SystemAssignedIdentityRole.Scope
}
return ""
}
// SystemAssignedIdentityDefinitionID returns the role definition ID for the system assigned identity.
func (m *MachinePoolScope) SystemAssignedIdentityDefinitionID() string {
if m.AzureMachinePool.Spec.SystemAssignedIdentityRole != nil {
return m.AzureMachinePool.Spec.SystemAssignedIdentityRole.DefinitionID
}
return ""
}
// ProvisioningState returns the AzureMachinePool provisioning state.
func (m *MachinePoolScope) ProvisioningState() infrav1.ProvisioningState {
if m.AzureMachinePool.Status.ProvisioningState != nil {
return *m.AzureMachinePool.Status.ProvisioningState
}
return ""
}
// SetVMSSState updates the machine pool scope with the current state of the VMSS.
func (m *MachinePoolScope) SetVMSSState(vmssState *azure.VMSS) {
m.vmssState = vmssState
}
// NeedsRequeue return true if any machines are not on the latest model or the VMSS is not in a terminal provisioning
// state.
func (m *MachinePoolScope) NeedsRequeue() bool {
state := m.AzureMachinePool.Status.ProvisioningState
if m.vmssState == nil {
return state != nil && infrav1.IsTerminalProvisioningState(*state)
}
if !m.vmssState.HasLatestModelAppliedToAll() {
return true
}
desiredMatchesActual := len(m.vmssState.Instances) == int(m.DesiredReplicas())
return !(state != nil && infrav1.IsTerminalProvisioningState(*state) && desiredMatchesActual)
}
// DesiredReplicas returns the replica count on machine pool or 0 if machine pool replicas is nil.
func (m MachinePoolScope) DesiredReplicas() int32 {
return pointer.Int32Deref(m.MachinePool.Spec.Replicas, 0)
}
// MaxSurge returns the number of machines to surge, or 0 if the deployment strategy does not support surge.
func (m MachinePoolScope) MaxSurge() (int, error) {
if surger, ok := m.getDeploymentStrategy().(machinepool.Surger); ok {
surgeCount, err := surger.Surge(int(m.DesiredReplicas()))
if err != nil {
return 0, errors.Wrap(err, "failed to calculate surge for the machine pool")
}
return surgeCount, nil
}
return 0, nil
}
// updateReplicasAndProviderIDs ties the Azure VMSS instance data and the Node status data together to build and update
// the AzureMachinePool replica count and providerIDList.
func (m *MachinePoolScope) updateReplicasAndProviderIDs(ctx context.Context) error {
ctx, _, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.UpdateInstanceStatuses")
defer done()
machines, err := m.getMachinePoolMachines(ctx)
if err != nil {
return errors.Wrap(err, "failed to get machine pool machines")
}
var readyReplicas int32
providerIDs := make([]string, len(machines))
for i, machine := range machines {
if machine.Status.Ready {
readyReplicas++
}
providerIDs[i] = machine.Spec.ProviderID
}
m.AzureMachinePool.Status.Replicas = readyReplicas
m.AzureMachinePool.Spec.ProviderIDList = providerIDs
return nil
}
func (m *MachinePoolScope) getMachinePoolMachines(ctx context.Context) ([]infrav1exp.AzureMachinePoolMachine, error) {
ctx, _, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.getMachinePoolMachines")
defer done()
labels := map[string]string{
clusterv1.ClusterLabelName: m.ClusterName(),
infrav1exp.MachinePoolNameLabel: m.AzureMachinePool.Name,
}
ampml := &infrav1exp.AzureMachinePoolMachineList{}
if err := m.client.List(ctx, ampml, client.InNamespace(m.AzureMachinePool.Namespace), client.MatchingLabels(labels)); err != nil {
return nil, errors.Wrap(err, "failed to list AzureMachinePoolMachines")
}
return ampml.Items, nil
}
func (m *MachinePoolScope) applyAzureMachinePoolMachines(ctx context.Context) error {
ctx, log, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.applyAzureMachinePoolMachines")
defer done()
if m.vmssState == nil {
log.Info("vmssState is nil")
return nil
}
labels := map[string]string{
clusterv1.ClusterLabelName: m.ClusterName(),
infrav1exp.MachinePoolNameLabel: m.AzureMachinePool.Name,
}
ampml := &infrav1exp.AzureMachinePoolMachineList{}
if err := m.client.List(ctx, ampml, client.InNamespace(m.AzureMachinePool.Namespace), client.MatchingLabels(labels)); err != nil {
return errors.Wrap(err, "failed to list AzureMachinePoolMachines")
}
existingMachinesByProviderID := make(map[string]infrav1exp.AzureMachinePoolMachine, len(ampml.Items))
for _, machine := range ampml.Items {
existingMachinesByProviderID[machine.Spec.ProviderID] = machine
}
// determine which machines need to be created to reflect the current state in Azure
azureMachinesByProviderID := m.vmssState.InstancesByProviderID(m.AzureMachinePool.Spec.OrchestrationMode)
for key, val := range azureMachinesByProviderID {
if _, ok := existingMachinesByProviderID[key]; !ok {
log.V(4).Info("creating AzureMachinePoolMachine", "providerID", key)
if err := m.createMachine(ctx, val); err != nil {
return errors.Wrap(err, "failed creating AzureMachinePoolMachine")
}
continue
}
}
deleted := false
// delete machines that no longer exist in Azure
for key, machine := range existingMachinesByProviderID {
machine := machine
if _, ok := azureMachinesByProviderID[key]; !ok {
deleted = true
log.V(4).Info("deleting AzureMachinePoolMachine because it no longer exists in the VMSS", "providerID", key)
delete(existingMachinesByProviderID, key)
if err := m.client.Delete(ctx, &machine); err != nil {
return errors.Wrap(err, "failed deleting AzureMachinePoolMachine no longer existing in Azure")
}
}
}
if deleted {
log.V(4).Info("exiting early due to finding AzureMachinePoolMachine(s) that were deleted because they no longer exist in the VMSS")
// exit early to be less greedy about delete
return nil
}
if futures.Has(m.AzureMachinePool, m.Name(), ScalesetsServiceName, infrav1.PatchFuture) ||
futures.Has(m.AzureMachinePool, m.Name(), ScalesetsServiceName, infrav1.PutFuture) ||
futures.Has(m.AzureMachinePool, m.Name(), ScalesetsServiceName, infrav1.DeleteFuture) {
log.V(4).Info("exiting early due an in-progress long running operation on the ScaleSet")
// exit early to be less greedy about delete
return nil
}
// when replicas are externally managed, we do not want to scale down manually since that is handled by the external scaler.
if m.HasReplicasExternallyManaged(ctx) {
log.V(4).Info("exiting early due to replicas externally managed")
return nil
}
deleteSelector := m.getDeploymentStrategy()
if deleteSelector == nil {
log.V(4).Info("can not select AzureMachinePoolMachines to delete because no deployment strategy is specified")
return nil
}
// select machines to delete to lower the replica count
toDelete, err := deleteSelector.SelectMachinesToDelete(ctx, m.DesiredReplicas(), existingMachinesByProviderID)
if err != nil {
return errors.Wrap(err, "failed selecting AzureMachinePoolMachine(s) to delete")
}
for _, machine := range toDelete {
machine := machine
log.Info("deleting selected AzureMachinePoolMachine", "providerID", machine.Spec.ProviderID)
if err := m.client.Delete(ctx, &machine); err != nil {
return errors.Wrap(err, "failed deleting AzureMachinePoolMachine to reduce replica count")
}
}
log.V(4).Info("done reconciling AzureMachinePoolMachine(s)")
return nil
}
func (m *MachinePoolScope) createMachine(ctx context.Context, machine azure.VMSSVM) error {
ctx, _, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.createMachine")
defer done()
parsed, err := azureautorest.ParseResourceID(machine.ID)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to parse resource id %q", machine.ID))
}
instanceID := strings.ReplaceAll(parsed.ResourceName, "_", "-")
ampm := infrav1exp.AzureMachinePoolMachine{
ObjectMeta: metav1.ObjectMeta{
Name: m.AzureMachinePool.Name + "-" + instanceID,
Namespace: m.AzureMachinePool.Namespace,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: infrav1exp.GroupVersion.String(),
Kind: "AzureMachinePool",
Name: m.AzureMachinePool.Name,
BlockOwnerDeletion: pointer.Bool(true),
UID: m.AzureMachinePool.UID,
},
},
Labels: map[string]string{
m.ClusterName(): string(infrav1.ResourceLifecycleOwned),
clusterv1.ClusterLabelName: m.ClusterName(),
infrav1exp.MachinePoolNameLabel: m.AzureMachinePool.Name,
},
},
Spec: infrav1exp.AzureMachinePoolMachineSpec{
ProviderID: machine.ProviderID(),
InstanceID: machine.InstanceID,
},
}
controllerutil.AddFinalizer(&m, infrav1exp.AzureMachinePoolMachineFinalizer)
conditions.MarkFalse(&m, infrav1.VMRunningCondition, string(infrav1.Creating), clusterv1.ConditionSeverityInfo, "")
if err := m.client.Create(ctx, &m); err != nil {
return errors.Wrapf(err, "failed creating AzureMachinePoolMachine %s in AzureMachinePool %s", machine.ID, m.AzureMachinePool.Name)
}
return nil
}
// SetLongRunningOperationState will set the future on the AzureMachinePool status to allow the resource to continue
// in the next reconciliation.
func (m *MachinePoolScope) SetLongRunningOperationState(future *infrav1.Future) {
futures.Set(m.AzureMachinePool, future)
}
// GetLongRunningOperationState will get the future on the AzureMachinePool status.
func (m *MachinePoolScope) GetLongRunningOperationState(name, service, futureType string) *infrav1.Future {
return futures.Get(m.AzureMachinePool, name, service, futureType)
}
// DeleteLongRunningOperationState will delete the future from the AzureMachinePool status.
func (m *MachinePoolScope) DeleteLongRunningOperationState(name, service, futureType string) {
futures.Delete(m.AzureMachinePool, name, service, futureType)
}
// setProvisioningStateAndConditions sets the AzureMachinePool provisioning state and conditions.
func (m *MachinePoolScope) setProvisioningStateAndConditions(v infrav1.ProvisioningState) {
m.AzureMachinePool.Status.ProvisioningState = &v
switch {
case v == infrav1.Succeeded && *m.MachinePool.Spec.Replicas == m.AzureMachinePool.Status.Replicas:
// vmss is provisioned with enough ready replicas
conditions.MarkTrue(m.AzureMachinePool, infrav1.ScaleSetRunningCondition)
conditions.MarkTrue(m.AzureMachinePool, infrav1.ScaleSetModelUpdatedCondition)
conditions.MarkTrue(m.AzureMachinePool, infrav1.ScaleSetDesiredReplicasCondition)
m.SetReady()
case v == infrav1.Succeeded && *m.MachinePool.Spec.Replicas != m.AzureMachinePool.Status.Replicas:
// not enough ready or too many ready replicas we must still be scaling up or down
updatingState := infrav1.Updating
m.AzureMachinePool.Status.ProvisioningState = &updatingState
if *m.MachinePool.Spec.Replicas > m.AzureMachinePool.Status.Replicas {
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetDesiredReplicasCondition, infrav1.ScaleSetScaleUpReason, clusterv1.ConditionSeverityInfo, "")
} else {
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetDesiredReplicasCondition, infrav1.ScaleSetScaleDownReason, clusterv1.ConditionSeverityInfo, "")
}
m.SetNotReady()
case v == infrav1.Updating:
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetModelUpdatedCondition, infrav1.ScaleSetModelOutOfDateReason, clusterv1.ConditionSeverityInfo, "")
m.SetNotReady()
case v == infrav1.Creating:
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetRunningCondition, infrav1.ScaleSetCreatingReason, clusterv1.ConditionSeverityInfo, "")
m.SetNotReady()
case v == infrav1.Deleting:
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetRunningCondition, infrav1.ScaleSetDeletingReason, clusterv1.ConditionSeverityInfo, "")
m.SetNotReady()
default:
conditions.MarkFalse(m.AzureMachinePool, infrav1.ScaleSetRunningCondition, string(v), clusterv1.ConditionSeverityInfo, "")
m.SetNotReady()
}
}
// SetReady sets the AzureMachinePool Ready Status to true.
func (m *MachinePoolScope) SetReady() {
m.AzureMachinePool.Status.Ready = true
}
// SetNotReady sets the AzureMachinePool Ready Status to false.
func (m *MachinePoolScope) SetNotReady() {
m.AzureMachinePool.Status.Ready = false
}
// SetFailureMessage sets the AzureMachinePool status failure message.
func (m *MachinePoolScope) SetFailureMessage(v error) {
m.AzureMachinePool.Status.FailureMessage = pointer.String(v.Error())
}
// SetFailureReason sets the AzureMachinePool status failure reason.
func (m *MachinePoolScope) SetFailureReason(v capierrors.MachineStatusError) {
m.AzureMachinePool.Status.FailureReason = &v
}
// AdditionalTags merges AdditionalTags from the scope's AzureCluster and AzureMachinePool. If the same key is present in both,
// the value from AzureMachinePool takes precedence.
func (m *MachinePoolScope) AdditionalTags() infrav1.Tags {
tags := make(infrav1.Tags)
// Start with the cluster-wide tags...
tags.Merge(m.ClusterScoper.AdditionalTags())
// ... and merge in the Machine Pool's
tags.Merge(m.AzureMachinePool.Spec.AdditionalTags)
// Set the cloud provider tag
tags[infrav1.ClusterAzureCloudProviderTagKey(m.ClusterName())] = string(infrav1.ResourceLifecycleOwned)
return tags
}
// SetAnnotation sets a key value annotation on the AzureMachinePool.
func (m *MachinePoolScope) SetAnnotation(key, value string) {
if m.AzureMachinePool.Annotations == nil {
m.AzureMachinePool.Annotations = map[string]string{}
}
m.AzureMachinePool.Annotations[key] = value
}
// PatchObject persists the AzureMachinePool spec and status.
func (m *MachinePoolScope) PatchObject(ctx context.Context) error {
ctx, _, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.PatchObject")
defer done()
conditions.SetSummary(m.AzureMachinePool)
return m.patchHelper.Patch(
ctx,
m.AzureMachinePool,
patch.WithOwnedConditions{Conditions: []clusterv1.ConditionType{
clusterv1.ReadyCondition,
infrav1.BootstrapSucceededCondition,
infrav1.ScaleSetDesiredReplicasCondition,
infrav1.ScaleSetModelUpdatedCondition,
infrav1.ScaleSetRunningCondition,
}})
}
// Close the MachinePoolScope by updating the AzureMachinePool spec and AzureMachinePool status.
func (m *MachinePoolScope) Close(ctx context.Context) error {
ctx, log, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.Close")
defer done()
if m.vmssState != nil {
if err := m.applyAzureMachinePoolMachines(ctx); err != nil {
log.Error(err, "failed to apply changes to the AzureMachinePoolMachines")
return errors.Wrap(err, "failed to apply changes to AzureMachinePoolMachines")
}
m.setProvisioningStateAndConditions(m.vmssState.State)
if err := m.updateReplicasAndProviderIDs(ctx); err != nil {
return errors.Wrap(err, "failed to update replicas and providerIDs")
}
if m.HasReplicasExternallyManaged(ctx) {
if err := m.updateCustomDataHash(ctx); err != nil {
// ignore errors to calculating the custom data hash since it's not absolutely crucial.
log.V(4).Error(err, "unable to update custom data hash, ignoring.")
}
}
}
if err := m.PatchObject(ctx); err != nil {
return errors.Wrap(err, "unable to patch AzureMachinePool")
}
if err := m.PatchCAPIMachinePoolObject(ctx); err != nil {
return errors.Wrap(err, "unable to patch CAPI MachinePool")
}
return nil
}
// GetBootstrapData returns the bootstrap data from the secret in the MachinePool's bootstrap.dataSecretName.
func (m *MachinePoolScope) GetBootstrapData(ctx context.Context) (string, error) {
ctx, _, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.GetBootstrapData")
defer done()
dataSecretName := m.MachinePool.Spec.Template.Spec.Bootstrap.DataSecretName
if dataSecretName == nil {
return "", errors.New("error retrieving bootstrap data: linked MachinePool Spec's bootstrap.dataSecretName is nil")
}
secret := &corev1.Secret{}
key := types.NamespacedName{Namespace: m.AzureMachinePool.Namespace, Name: *dataSecretName}
if err := m.client.Get(ctx, key, secret); err != nil {
return "", errors.Wrapf(err, "failed to retrieve bootstrap data secret for AzureMachinePool %s/%s", m.AzureMachinePool.Namespace, m.Name())
}
value, ok := secret.Data["value"]
if !ok {
return "", errors.New("error retrieving bootstrap data: secret value key is missing")
}
return base64.StdEncoding.EncodeToString(value), nil
}
// calculateBootstrapDataHash calculates the sha256 hash of the bootstrap data.
func (m *MachinePoolScope) calculateBootstrapDataHash(ctx context.Context) (string, error) {
bootstrapData, err := m.GetBootstrapData(ctx)
if err != nil {
return "", err
}
h := sha256.New()
n, err := io.WriteString(h, bootstrapData)
if err != nil || n == 0 {
return "", fmt.Errorf("unable to write custom data (bytes written: %q): %w", n, err)
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// HasBootstrapDataChanges calculates the sha256 hash of the bootstrap data and compares it with the saved hash in AzureMachinePool.Status.
func (m *MachinePoolScope) HasBootstrapDataChanges(ctx context.Context) (bool, error) {
newHash, err := m.calculateBootstrapDataHash(ctx)
if err != nil {
return false, err
}
return m.AzureMachinePool.GetAnnotations()[azure.CustomDataHashAnnotation] != newHash, nil
}
// updateCustomDataHash calculates the sha256 hash of the bootstrap data and saves it in AzureMachinePool.Status.
func (m *MachinePoolScope) updateCustomDataHash(ctx context.Context) error {
newHash, err := m.calculateBootstrapDataHash(ctx)
if err != nil {
return err
}
m.SetAnnotation(azure.CustomDataHashAnnotation, newHash)
return nil
}
// GetVMImage picks an image from the AzureMachinePool configuration, or uses a default one.
func (m *MachinePoolScope) GetVMImage(ctx context.Context) (*infrav1.Image, error) {
ctx, log, done := tele.StartSpanWithLogger(ctx, "scope.MachinePoolScope.GetVMImage")
defer done()
// Use custom Marketplace image, Image ID or a Shared Image Gallery image if provided
if m.AzureMachinePool.Spec.Template.Image != nil {
return m.AzureMachinePool.Spec.Template.Image, nil
}
svc := virtualmachineimages.New(m)
var (
err error
defaultImage *infrav1.Image
)
if m.AzureMachinePool.Spec.Template.OSDisk.OSType == azure.WindowsOS {
runtime := m.AzureMachinePool.Annotations["runtime"]
windowsServerVersion := m.AzureMachinePool.Annotations["windowsServerVersion"]
log.V(4).Info("No image specified for machine, using default Windows Image", "machine", m.MachinePool.GetName(), "runtime", runtime, "windowsServerVersion", windowsServerVersion)
defaultImage, err = svc.GetDefaultWindowsImage(ctx, m.Location(), pointer.StringDeref(m.MachinePool.Spec.Template.Spec.Version, ""), runtime, windowsServerVersion)
} else {
defaultImage, err = svc.GetDefaultUbuntuImage(ctx, m.Location(), pointer.StringDeref(m.MachinePool.Spec.Template.Spec.Version, ""))
}
if err != nil {
return defaultImage, errors.Wrap(err, "failed to get default OS image")
}
return defaultImage, nil
}
// SaveVMImageToStatus persists the AzureMachinePool image to the status.
func (m *MachinePoolScope) SaveVMImageToStatus(image *infrav1.Image) {
m.AzureMachinePool.Status.Image = image
}
// RoleAssignmentSpecs returns the role assignment specs.
func (m *MachinePoolScope) RoleAssignmentSpecs(principalID *string) []azure.ResourceSpecGetter {
roles := make([]azure.ResourceSpecGetter, 1)
if m.HasSystemAssignedIdentity() {
roles[0] = &roleassignments.RoleAssignmentSpec{
Name: m.SystemAssignedIdentityName(),
MachineName: m.Name(),
ResourceGroup: m.ResourceGroup(),
ResourceType: azure.VirtualMachineScaleSet,
Scope: m.SystemAssignedIdentityScope(),
RoleDefinitionID: m.SystemAssignedIdentityDefinitionID(),
PrincipalID: principalID,
}
return roles
}
return []azure.ResourceSpecGetter{}
}
// RoleAssignmentResourceType returns the role assignment resource type.
func (m *MachinePoolScope) RoleAssignmentResourceType() string {
return azure.VirtualMachineScaleSet
}
// HasSystemAssignedIdentity returns true if the azure machine pool has system
// assigned identity.
func (m *MachinePoolScope) HasSystemAssignedIdentity() bool {
return m.AzureMachinePool.Spec.Identity == infrav1.VMIdentitySystemAssigned
}
// VMSSExtensionSpecs returns the VMSS extension specs.
func (m *MachinePoolScope) VMSSExtensionSpecs() []azure.ResourceSpecGetter {
var extensionSpecs = []azure.ResourceSpecGetter{}
for _, extension := range m.AzureMachinePool.Spec.Template.VMExtensions {
extensionSpecs = append(extensionSpecs, &scalesets.VMSSExtensionSpec{
ExtensionSpec: azure.ExtensionSpec{
Name: extension.Name,
VMName: m.Name(),
Publisher: extension.Publisher,
Version: extension.Version,
Settings: extension.Settings,
ProtectedSettings: extension.ProtectedSettings,
},
ResourceGroup: m.ResourceGroup(),
})
}
bootstrapExtensionSpec := azure.GetBootstrappingVMExtension(m.AzureMachinePool.Spec.Template.OSDisk.OSType, m.CloudEnvironment(), m.Name())
if bootstrapExtensionSpec != nil {
extensionSpecs = append(extensionSpecs, &scalesets.VMSSExtensionSpec{
ExtensionSpec: *bootstrapExtensionSpec,
ResourceGroup: m.ResourceGroup(),
})
}
return extensionSpecs
}
func (m *MachinePoolScope) getDeploymentStrategy() machinepool.TypedDeleteSelector {
if m.AzureMachinePool == nil {
return nil
}
return machinepool.NewMachinePoolDeploymentStrategy(m.AzureMachinePool.Spec.Strategy)
}
// SetSubnetName defaults the AzureMachinePool subnet name to the name of the subnet with role 'node' when there is only one of them.
// Note: this logic exists only for purposes of ensuring backwards compatibility for old clusters created without the `subnetName` field being
// set, and should be removed in the future when this field is no longer optional.
func (m *MachinePoolScope) SetSubnetName() error {
if m.AzureMachinePool.Spec.Template.NetworkInterfaces[0].SubnetName == "" {
subnetName := ""
for _, subnet := range m.NodeSubnets() {
subnetName = subnet.Name
}
if len(m.NodeSubnets()) == 0 || len(m.NodeSubnets()) > 1 || subnetName == "" {
return errors.New("a subnet name must be specified when no subnets are specified or more than 1 subnet of role 'node' exist")
}
m.AzureMachinePool.Spec.Template.NetworkInterfaces[0].SubnetName = subnetName
}
return nil
}
// UpdateDeleteStatus updates a condition on the AzureMachinePool status after a DELETE operation.
func (m *MachinePoolScope) UpdateDeleteStatus(condition clusterv1.ConditionType, service string, err error) {
switch {
case err == nil:
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.DeletedReason, clusterv1.ConditionSeverityInfo, "%s successfully deleted", service)
case azure.IsOperationNotDoneError(err):
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.DeletingReason, clusterv1.ConditionSeverityInfo, "%s deleting", service)
default:
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.DeletionFailedReason, clusterv1.ConditionSeverityError, "%s failed to delete. err: %s", service, err.Error())
}
}
// UpdatePutStatus updates a condition on the AzureMachinePool status after a PUT operation.
func (m *MachinePoolScope) UpdatePutStatus(condition clusterv1.ConditionType, service string, err error) {
switch {
case err == nil:
conditions.MarkTrue(m.AzureMachinePool, condition)
case azure.IsOperationNotDoneError(err):
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.CreatingReason, clusterv1.ConditionSeverityInfo, "%s creating or updating", service)
default:
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.FailedReason, clusterv1.ConditionSeverityError, "%s failed to create or update. err: %s", service, err.Error())
}
}
// UpdatePatchStatus updates a condition on the AzureMachinePool status after a PATCH operation.
func (m *MachinePoolScope) UpdatePatchStatus(condition clusterv1.ConditionType, service string, err error) {
switch {
case err == nil:
conditions.MarkTrue(m.AzureMachinePool, condition)
case azure.IsOperationNotDoneError(err):
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.UpdatingReason, clusterv1.ConditionSeverityInfo, "%s updating", service)
default:
conditions.MarkFalse(m.AzureMachinePool, condition, infrav1.FailedReason, clusterv1.ConditionSeverityError, "%s failed to update. err: %s", service, err.Error())
}
}
// PatchCAPIMachinePoolObject persists the capi machinepool configuration and status.
func (m *MachinePoolScope) PatchCAPIMachinePoolObject(ctx context.Context) error {
return m.capiMachinePoolPatchHelper.Patch(
ctx,
m.MachinePool,
)
}
// UpdateCAPIMachinePoolReplicas updates the associated MachinePool replica count.
func (m *MachinePoolScope) UpdateCAPIMachinePoolReplicas(ctx context.Context, replicas *int32) {
m.MachinePool.Spec.Replicas = replicas
}
// HasReplicasExternallyManaged returns true if the externally managed annotation is set on the CAPI MachinePool resource.
func (m *MachinePoolScope) HasReplicasExternallyManaged(ctx context.Context) bool {
return annotations.ReplicasManagedByExternalAutoscaler(m.MachinePool)
}
// ReconcileReplicas ensures MachinePool replicas match VMSS capacity if replicas are externally managed by an autoscaler.
func (m *MachinePoolScope) ReconcileReplicas(ctx context.Context, vmss *azure.VMSS) error {
if !m.HasReplicasExternallyManaged(ctx) {
return nil
}
var replicas int32 = 0
if m.MachinePool.Spec.Replicas != nil {
replicas = *m.MachinePool.Spec.Replicas
}
if capacity := int32(vmss.Capacity); capacity != replicas {
m.UpdateCAPIMachinePoolReplicas(ctx, &capacity)
}
return nil
}