-
Notifications
You must be signed in to change notification settings - Fork 0
/
reconciler.go
319 lines (268 loc) · 9.62 KB
/
reconciler.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
package machine
import (
"fmt"
"strings"
configv1 "github.com/openshift/api/config/v1"
machinecontroller "github.com/openshift/machine-api-operator/pkg/controller/machine"
"github.com/openshift/machine-api-operator/pkg/metrics"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
nutanixv1 "github.com/nutanix-cloud-native/machine-api-provider-nutanix/pkg/apis/nutanixprovider/v1beta1"
nutanixClientV3 "github.com/nutanix-cloud-native/prism-go-client/pkg/nutanix/v3"
)
const (
requeueAfterSeconds = 20
requeueAfterFatalSeconds = 180
masterLabel = "node-role.kubernetes.io/master"
providerIDFmt = "nutanix://%s"
infraName = "cluster"
)
// Reconciler runs the logic to reconciles a machine resource towards its desired state
type Reconciler struct {
*machineScope
}
func newReconciler(scope *machineScope) *Reconciler {
return &Reconciler{
machineScope: scope,
}
}
// create creates machine if it does not exists.
func (r *Reconciler) create() error {
klog.Infof("%s: creating machine", r.machine.Name)
if err := validateMachine(*r.machine); err != nil {
e1 := fmt.Errorf("%v: failed validating machine provider spec: %w", r.machine.GetName(), err)
klog.Error(e1.Error())
return e1
}
userData, err := r.machineScope.getUserData()
if err != nil {
return fmt.Errorf("failed to get user data: %w", err)
}
infra := &configv1.Infrastructure{}
infraName := client.ObjectKey{Name: infraName}
if err := r.client.Get(r.Context, infraName, infra); err != nil {
klog.Errorf("error reconciling create machine %s: failed to get Infrastructure %s. %v",
r.machine.Name, infraName, err)
return err
}
vm, err := createVM(r.machineScope, userData)
if err != nil {
klog.Errorf("%s: error creating machine: %v", r.machine.Name, err)
r.machineScope.setProviderStatus(nil, conditionFailed(nutanixv1.MachineCreation, err.Error()))
return fmt.Errorf("failed to create VM: %w", err)
}
klog.Infof("Created VM %s, with uuid: %s", r.machine.Name, *vm.Metadata.UUID)
if err = r.updateMachineWithVMState(vm); err != nil {
return fmt.Errorf("failed to update machine with vm state: %w", err)
}
r.machineScope.setProviderStatus(vm, conditionSuccess(nutanixv1.MachineCreation))
return nil
}
// update finds a vm and reconciles the machine resource status against it.
func (r *Reconciler) update() error {
klog.Infof("%s: updating machine", r.machine.Name)
err := validateMachine(*r.machine)
if err != nil {
return fmt.Errorf("%v: failed validating machine provider spec: %v", r.machine.GetName(), err)
}
var vm *nutanixClientV3.VMIntentResponse
if r.providerStatus.VmUUID == nil {
// Try to find the vm by name
vm, err = findVMByName(r.nutanixClient, r.machine.Name)
if err != nil {
metrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{
Name: r.machine.Name,
Namespace: r.machine.Namespace,
Reason: err.Error(),
})
klog.Errorf("%s: error finding the vm with name %s: %v", r.machine.Name, r.machine.Name, err)
r.machineScope.setProviderStatus(nil, conditionFailed(nutanixv1.MachineUpdate, err.Error()))
return err
}
r.providerStatus.VmUUID = vm.Metadata.UUID
} else {
// find the existing VM with the vmUuid
vmUuid := *r.providerStatus.VmUUID
vm, err = findVMByUUID(r.nutanixClient, vmUuid)
if err != nil {
metrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{
Name: r.machine.Name,
Namespace: r.machine.Namespace,
Reason: err.Error(),
})
klog.Errorf("%s: error finding the vm with uuid %s: %v", r.machine.Name, vmUuid, err)
r.machineScope.setProviderStatus(nil, conditionFailed(nutanixv1.MachineUpdate, err.Error()))
return err
}
}
if err = r.updateMachineWithVMState(vm); err != nil {
metrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{
Name: r.machine.Name,
Namespace: r.machine.Namespace,
Reason: err.Error(),
})
klog.Errorf("%s: error update machine with VM state: %v", r.machine.Name, err)
r.machineScope.setProviderStatus(vm, conditionFailed(nutanixv1.MachineUpdate, err.Error()))
return err
}
r.machineScope.setProviderStatus(vm, conditionSuccess(nutanixv1.MachineUpdate))
klog.Infof("Updated machine %s vm state", r.machine.Name)
return nil
}
// delete deletes VM
func (r *Reconciler) delete() error {
klog.Infof("%s: deleting machine", r.machine.Name)
var err error
if r.providerStatus.VmUUID == nil {
err = fmt.Errorf("%s: cannot delete the vm, the vmUUID is null.", r.machine.Name)
klog.Errorf(err.Error())
return err
}
vmUuid := *r.providerStatus.VmUUID
_, err = findVMByUUID(r.nutanixClient, vmUuid)
if err != nil {
if strings.Contains(err.Error(), "Not Found") {
klog.Warningf("%v: vm with uuid %s does not exist", r.machine.Name, vmUuid)
return nil
}
klog.Errorf("%v: error finding vm with uuid %s", r.machine.Name, vmUuid)
return err
}
// Ensure volumes are detached before deleting the Node.
if r.isNodeLinked() {
attached, err := r.nodeHasVolumesAttached()
if err != nil {
return fmt.Errorf("failed to determine if node %v has attached volumes: %w", r.machine.Status.NodeRef.Name, err)
}
if attached {
return fmt.Errorf("node %v has attached volumes, requeuing", r.machine.Status.NodeRef.Name)
}
}
// Delete vm with the vmUuid
err = deleteVM(r.nutanixClient, vmUuid)
if err != nil {
metrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{
Name: r.machine.Name,
Namespace: r.machine.Namespace,
Reason: err.Error(),
})
klog.Errorf("%s: error deleting vm with uuid %s: %v", r.machine.Name, vmUuid, err)
return err
}
// update machine spec and status
r.machine.Spec.ProviderID = nil
r.machine.Status.Addresses = r.machine.Status.Addresses[:0]
r.providerStatus.Ready = false
r.providerStatus.VmUUID = nil
klog.Infof("Deleted machine %v vm with uuid %s", r.machine.Name, vmUuid)
return nil
}
// exists returns true if machine corresponding VM exists.
func (r *Reconciler) exists() (bool, error) {
err := validateMachine(*r.machine)
if err != nil {
return false, fmt.Errorf("%v: failed validating machine provider spec: %v", r.machine.GetName(), err)
}
if r.providerStatus.VmUUID != nil {
// Try to find the vm by uuid
vmUuid := *r.providerStatus.VmUUID
_, err = findVMByUUID(r.nutanixClient, vmUuid)
} else {
// Try to find the vm by name
_, err = findVMByName(r.nutanixClient, r.machine.Name)
}
if err != nil {
if strings.Contains(err.Error(), "Not Found") {
return false, nil
}
metrics.RegisterFailedInstanceUpdate(&metrics.MachineLabels{
Name: r.machine.Name,
Namespace: r.machine.Namespace,
Reason: err.Error(),
})
klog.Errorf("%s: error finding the vm : %v", r.machine.Name, err)
return false, err
}
klog.Infof("%s: vm exists", r.machine.Name)
return true, nil
}
// isMaster returns true if the machine is part of a cluster's control plane
func (r *Reconciler) isMaster() (bool, error) {
if r.machine.Status.NodeRef == nil {
klog.Errorf("NodeRef not found in machine %s", r.machine.Name)
return false, nil
}
node := &corev1.Node{}
nodeKey := types.NamespacedName{
Name: r.machine.Status.NodeRef.Name,
}
err := r.client.Get(r.Context, nodeKey, node)
if err != nil {
return false, fmt.Errorf("failed to get node from machine %s", r.machine.Name)
}
if _, exists := node.Labels[masterLabel]; exists {
return true, nil
}
return false, nil
}
// setProviderID adds providerID in the machine spec
func (r *Reconciler) setProviderID(vmUUID *string) error {
if vmUUID == nil {
return fmt.Errorf("Failed to update machine providerID: null vmUUID")
}
// update the machine.Spec.ProviderID
existingProviderID := r.machine.Spec.ProviderID
providerID := fmt.Sprintf(providerIDFmt, *vmUUID)
if existingProviderID != nil && *existingProviderID == providerID {
klog.Infof("%s: ProviderID already set in the machine Spec with value: %s", r.machine.Name, *existingProviderID)
} else {
r.machine.Spec.ProviderID = &providerID
klog.Infof("%s: ProviderID set at machine.spec: %s", r.machine.Name, providerID)
}
// update the corresponding node.Spec.ProviderID
var nodeName string
if r.machine.Status.NodeRef != nil {
nodeName = r.machine.Status.NodeRef.Name
}
if len(nodeName) == 0 {
nodeName = r.machine.Name
}
nodeKey := types.NamespacedName{Name: nodeName}
node := &corev1.Node{}
err := r.client.Get(r.Context, nodeKey, node)
if err != nil {
return fmt.Errorf("%s: failed to get node %s: %v", r.machine.Name, nodeName, err)
}
existingNodeProviderID := node.Spec.ProviderID
if existingNodeProviderID == providerID {
klog.Infof("%s: The node %s spec.providerID is already set with value: %s", r.machine.Name, nodeName, existingNodeProviderID)
} else {
node.Spec.ProviderID = providerID
err := r.client.Update(r.Context, node)
if err != nil {
klog.Errorf("%s: failed to update the node %s spec.providerID. %v", r.machine.Name, nodeName, err)
return err
}
klog.Infof("%s: The node %s spec.providerID is set to: %s", r.machine.Name, nodeName, providerID)
}
return nil
}
func (r *Reconciler) updateMachineWithVMState(vm *nutanixClientV3.VMIntentResponse) error {
if vm == nil {
return nil
}
klog.Infof("%v: updating machine providerID", r.machine.Name)
if err := r.setProviderID(vm.Metadata.UUID); err != nil {
return err
}
powerState := *vm.Status.Resources.PowerState
if r.machine.Annotations == nil {
r.machine.Annotations = map[string]string{}
}
r.machine.Annotations[machinecontroller.MachineInstanceStateAnnotationName] = powerState
klog.Infof("%v: updated machine powerstate annotation (%s: %s)", r.machine.Name,
machinecontroller.MachineInstanceStateAnnotationName, powerState)
return nil
}