-
Notifications
You must be signed in to change notification settings - Fork 431
/
machine.go
450 lines (400 loc) · 14.3 KB
/
machine.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
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scope
import (
"context"
"encoding/base64"
"encoding/json"
"github.com/Azure/go-autorest/autorest/to"
"github.com/go-logr/logr"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/klogr"
infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1alpha3"
azure "sigs.k8s.io/cluster-api-provider-azure/cloud"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
capierrors "sigs.k8s.io/cluster-api/errors"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// MachineScopeParams defines the input parameters used to create a new MachineScope.
type MachineScopeParams struct {
Client client.Client
Logger logr.Logger
ClusterScope azure.ClusterScoper
Machine *clusterv1.Machine
AzureMachine *infrav1.AzureMachine
}
// NewMachineScope creates a new MachineScope from the supplied parameters.
// This is meant to be called for each reconcile iteration.
func NewMachineScope(params MachineScopeParams) (*MachineScope, error) {
if params.Client == nil {
return nil, errors.New("client is required when creating a MachineScope")
}
if params.Machine == nil {
return nil, errors.New("machine is required when creating a MachineScope")
}
if params.AzureMachine == nil {
return nil, errors.New("azure machine is required when creating a MachineScope")
}
if params.Logger == nil {
params.Logger = klogr.New()
}
helper, err := patch.NewHelper(params.AzureMachine, params.Client)
if err != nil {
return nil, errors.Wrap(err, "failed to init patch helper")
}
return &MachineScope{
client: params.Client,
Machine: params.Machine,
AzureMachine: params.AzureMachine,
Logger: params.Logger,
patchHelper: helper,
ClusterScoper: params.ClusterScope,
}, nil
}
// MachineScope defines a scope defined around a machine and its cluster.
type MachineScope struct {
logr.Logger
client client.Client
patchHelper *patch.Helper
azure.ClusterScoper
Machine *clusterv1.Machine
AzureMachine *infrav1.AzureMachine
}
// VMSpecs returns the VM specs.
func (m *MachineScope) VMSpecs() []azure.VMSpec {
return []azure.VMSpec{
{
Name: m.Name(),
Role: m.Role(),
NICNames: m.NICNames(),
SSHKeyData: m.AzureMachine.Spec.SSHPublicKey,
Size: m.AzureMachine.Spec.VMSize,
OSDisk: m.AzureMachine.Spec.OSDisk,
DataDisks: m.AzureMachine.Spec.DataDisks,
Zone: m.AvailabilityZone(),
Identity: m.AzureMachine.Spec.Identity,
UserAssignedIdentities: m.AzureMachine.Spec.UserAssignedIdentities,
SpotVMOptions: m.AzureMachine.Spec.SpotVMOptions,
},
}
}
// TagsSpecs returns the tags for the AzureMachine.
func (m *MachineScope) TagsSpecs() []azure.TagsSpec {
return []azure.TagsSpec{
{
Scope: azure.VMID(m.SubscriptionID(), m.ResourceGroup(), m.Name()),
Tags: m.AdditionalTags(),
Annotation: infrav1.VMTagsLastAppliedAnnotation,
},
}
}
// PublicIPSpecs returns the public IP specs.
func (m *MachineScope) PublicIPSpecs() []azure.PublicIPSpec {
var spec []azure.PublicIPSpec
if m.AzureMachine.Spec.AllocatePublicIP == true {
spec = append(spec, azure.PublicIPSpec{
Name: azure.GenerateNodePublicIPName(m.Name()),
})
}
return spec
}
// InboundNatSpecs returns the inbound NAT specs.
func (m *MachineScope) InboundNatSpecs() []azure.InboundNatSpec {
if m.Role() == infrav1.ControlPlane {
return []azure.InboundNatSpec{
{
Name: m.Name(),
LoadBalancerName: azure.GeneratePublicLBName(m.ClusterName()),
},
}
}
return []azure.InboundNatSpec{}
}
// NICSpecs returns the network interface specs.
func (m *MachineScope) NICSpecs() []azure.NICSpec {
spec := azure.NICSpec{
Name: azure.GenerateNICName(m.Name()),
MachineName: m.Name(),
VNetName: m.Vnet().Name,
VNetResourceGroup: m.Vnet().ResourceGroup,
SubnetName: m.Subnet().Name,
VMSize: m.AzureMachine.Spec.VMSize,
AcceleratedNetworking: m.AzureMachine.Spec.AcceleratedNetworking,
IPv6Enabled: m.IsIPv6Enabled(),
EnableIPForwarding: m.AzureMachine.Spec.EnableIPForwarding,
}
if m.Role() == infrav1.ControlPlane {
publicLBName := azure.GeneratePublicLBName(m.ClusterName())
spec.PublicLBName = publicLBName
spec.PublicLBAddressPoolName = azure.GenerateBackendAddressPoolName(publicLBName)
spec.PublicLBNATRuleName = m.Name()
if !m.IsIPv6Enabled() {
internalLBName := azure.GenerateInternalLBName(m.ClusterName())
spec.InternalLBName = internalLBName
spec.InternalLBAddressPoolName = azure.GenerateBackendAddressPoolName(internalLBName)
}
} else if m.Role() == infrav1.Node {
publicLBName := m.ClusterName()
spec.PublicLBName = publicLBName
spec.PublicLBAddressPoolName = azure.GenerateOutboundBackendddressPoolName(publicLBName)
}
specs := []azure.NICSpec{spec}
if m.AzureMachine.Spec.AllocatePublicIP == true {
specs = append(specs, azure.NICSpec{
Name: azure.GeneratePublicNICName(m.Name()),
MachineName: m.Name(),
VNetName: m.Vnet().Name,
VNetResourceGroup: m.Vnet().ResourceGroup,
SubnetName: m.Subnet().Name,
PublicIPName: azure.GenerateNodePublicIPName(m.Name()),
VMSize: m.AzureMachine.Spec.VMSize,
AcceleratedNetworking: m.AzureMachine.Spec.AcceleratedNetworking,
})
}
return specs
}
// NICNames returns the NIC names
func (m *MachineScope) NICNames() []string {
nicNames := make([]string, len(m.NICSpecs()))
for i, nic := range m.NICSpecs() {
nicNames[i] = nic.Name
}
return nicNames
}
// DiskSpecs returns the disk specs.
func (m *MachineScope) DiskSpecs() []azure.DiskSpec {
spec := azure.DiskSpec{
Name: azure.GenerateOSDiskName(m.Name()),
}
disks := []azure.DiskSpec{spec}
for _, dd := range m.AzureMachine.Spec.DataDisks {
disks = append(disks, azure.DiskSpec{Name: azure.GenerateDataDiskName(m.Name(), dd.NameSuffix)})
}
return disks
}
// BastionSpecs returns the bastion specs.
func (m *MachineScope) BastionSpecs() []azure.BastionSpec {
spec := azure.BastionSpec{
Name: azure.GenerateOSDiskName(m.Name()),
SubnetName: m.Subnet().Name,
PublicIPName: azure.GenerateNodePublicIPName(azure.GenerateNICName(m.Name())),
VNetName: m.Vnet().Name,
}
return []azure.BastionSpec{spec}
}
// RoleAssignmentSpecs returns the role assignment specs.
func (m *MachineScope) RoleAssignmentSpecs() []azure.RoleAssignmentSpec {
if m.AzureMachine.Spec.Identity == infrav1.VMIdentitySystemAssigned {
return []azure.RoleAssignmentSpec{
{
MachineName: m.Name(),
Name: m.AzureMachine.Spec.RoleAssignmentName,
ResourceType: azure.VirtualMachine,
},
}
}
return []azure.RoleAssignmentSpec{}
}
// Subnet returns the machine's subnet based on its role
func (m *MachineScope) Subnet() *infrav1.SubnetSpec {
if m.IsControlPlane() {
return m.ControlPlaneSubnet()
}
return m.NodeSubnet()
}
// AvailabilityZone returns the AzureMachine Availability Zone.
// Priority for selecting the AZ is
// 1) Machine.Spec.FailureDomain
// 2) AzureMachine.Spec.FailureDomain (This is to support deprecated AZ)
// 3) AzureMachine.Spec.AvailabilityZone.ID (This is DEPRECATED)
// 4) No AZ
func (m *MachineScope) AvailabilityZone() string {
if m.Machine.Spec.FailureDomain != nil {
return *m.Machine.Spec.FailureDomain
}
// DEPRECATED: to support old clients
if m.AzureMachine.Spec.FailureDomain != nil {
return *m.AzureMachine.Spec.FailureDomain
}
if m.AzureMachine.Spec.AvailabilityZone.ID != nil {
return *m.AzureMachine.Spec.AvailabilityZone.ID
}
return ""
}
// Name returns the AzureMachine name.
func (m *MachineScope) Name() string {
return m.AzureMachine.Name
}
// Namespace returns the namespace name.
func (m *MachineScope) Namespace() string {
return m.AzureMachine.Namespace
}
// IsControlPlane returns true if the machine is a control plane.
func (m *MachineScope) IsControlPlane() bool {
return util.IsControlPlaneMachine(m.Machine)
}
// Role returns the machine role from the labels.
func (m *MachineScope) Role() string {
if util.IsControlPlaneMachine(m.Machine) {
return infrav1.ControlPlane
}
return infrav1.Node
}
// GetVMID returns the AzureMachine instance id by parsing Spec.ProviderID.
func (m *MachineScope) GetVMID() string {
parsed, err := noderefutil.NewProviderID(m.ProviderID())
if err != nil {
return ""
}
return parsed.ID()
}
// ProviderID returns the AzureMachine providerID from the spec.
func (m *MachineScope) ProviderID() string {
parsed, err := noderefutil.NewProviderID(to.String(m.AzureMachine.Spec.ProviderID))
if err != nil {
return ""
}
return parsed.ID()
}
// SetProviderID sets the AzureMachine providerID in spec.
func (m *MachineScope) SetProviderID(v string) {
m.AzureMachine.Spec.ProviderID = to.StringPtr(v)
}
// VMState returns the AzureMachine VM state.
func (m *MachineScope) VMState() infrav1.VMState {
if m.AzureMachine.Status.VMState != nil {
return *m.AzureMachine.Status.VMState
}
return ""
}
// SetVMState sets the AzureMachine VM state.
func (m *MachineScope) SetVMState(v infrav1.VMState) {
m.AzureMachine.Status.VMState = &v
}
// SetReady sets the AzureMachine Ready Status to true.
func (m *MachineScope) SetReady() {
m.AzureMachine.Status.Ready = true
}
// SetNotReady sets the AzureMachine Ready Status to false.
func (m *MachineScope) SetNotReady() {
m.AzureMachine.Status.Ready = false
}
// SetFailureMessage sets the AzureMachine status failure message.
func (m *MachineScope) SetFailureMessage(v error) {
m.AzureMachine.Status.FailureMessage = to.StringPtr(v.Error())
}
// SetFailureReason sets the AzureMachine status failure reason.
func (m *MachineScope) SetFailureReason(v capierrors.MachineStatusError) {
m.AzureMachine.Status.FailureReason = &v
}
// SetAnnotation sets a key value annotation on the AzureMachine.
func (m *MachineScope) SetAnnotation(key, value string) {
if m.AzureMachine.Annotations == nil {
m.AzureMachine.Annotations = map[string]string{}
}
m.AzureMachine.Annotations[key] = value
}
// AnnotationJSON returns a map[string]interface from a JSON annotation.
func (m *MachineScope) AnnotationJSON(annotation string) (map[string]interface{}, error) {
out := map[string]interface{}{}
jsonAnnotation := m.AzureMachine.GetAnnotations()[annotation]
if len(jsonAnnotation) == 0 {
return out, nil
}
err := json.Unmarshal([]byte(jsonAnnotation), &out)
if err != nil {
return out, err
}
return out, nil
}
// UpdateAnnotationJSON updates the `annotation` with
// `content`. `content` in this case should be a `map[string]interface{}`
// suitable for turning into JSON. This `content` map will be marshalled into a
// JSON string before being set as the given `annotation`.
func (m *MachineScope) UpdateAnnotationJSON(annotation string, content map[string]interface{}) error {
b, err := json.Marshal(content)
if err != nil {
return err
}
m.SetAnnotation(annotation, string(b))
return nil
}
// SetAddresses sets the Azure address status.
func (m *MachineScope) SetAddresses(addrs []corev1.NodeAddress) {
m.AzureMachine.Status.Addresses = addrs
}
// PatchObject persists the machine spec and status.
func (m *MachineScope) PatchObject(ctx context.Context) error {
conditions.SetSummary(m.AzureMachine,
conditions.WithConditions(
infrav1.VMRunningCondition,
),
conditions.WithStepCounterIfOnly(
infrav1.VMRunningCondition,
),
)
return m.patchHelper.Patch(
ctx,
m.AzureMachine,
patch.WithOwnedConditions{Conditions: []clusterv1.ConditionType{
clusterv1.ReadyCondition,
infrav1.VMRunningCondition,
}})
}
// Close the MachineScope by updating the machine spec, machine status.
func (m *MachineScope) Close(ctx context.Context) error {
return m.PatchObject(ctx)
}
// AdditionalTags merges AdditionalTags from the scope's AzureCluster and AzureMachine. If the same key is present in both,
// the value from AzureMachine takes precedence.
func (m *MachineScope) AdditionalTags() infrav1.Tags {
tags := make(infrav1.Tags)
// Start with the cluster-wide tags...
tags.Merge(m.ClusterScoper.AdditionalTags())
// ... and merge in the Machine's
tags.Merge(m.AzureMachine.Spec.AdditionalTags)
// Set the cloud provider tag
tags[infrav1.ClusterAzureCloudProviderTagKey(m.ClusterName())] = string(infrav1.ResourceLifecycleOwned)
return tags
}
// GetBootstrapData returns the bootstrap data from the secret in the Machine's bootstrap.dataSecretName.
func (m *MachineScope) GetBootstrapData(ctx context.Context) (string, error) {
if m.Machine.Spec.Bootstrap.DataSecretName == nil {
return "", errors.New("error retrieving bootstrap data: linked Machine's bootstrap.dataSecretName is nil")
}
secret := &corev1.Secret{}
key := types.NamespacedName{Namespace: m.Namespace(), Name: *m.Machine.Spec.Bootstrap.DataSecretName}
if err := m.client.Get(ctx, key, secret); err != nil {
return "", errors.Wrapf(err, "failed to retrieve bootstrap data secret for AzureMachine %s/%s", m.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
}
// GetVMImage returns the image from the machine configuration, or a default one.
func (m *MachineScope) GetVMImage() (*infrav1.Image, error) {
// Use custom Marketplace image, Image ID or a Shared Image Gallery image if provided
if m.AzureMachine.Spec.Image != nil {
return m.AzureMachine.Spec.Image, nil
}
m.Info("No image specified for machine, using default", "machine", m.AzureMachine.GetName())
return azure.GetDefaultUbuntuImage(to.String(m.Machine.Spec.Version))
}