-
Notifications
You must be signed in to change notification settings - Fork 33
/
virtualmachine_pool.go
487 lines (407 loc) · 16.2 KB
/
virtualmachine_pool.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
/*
Copyright 2019 The KubeMacPool 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 pool_manager
import (
"fmt"
"net"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubevirt "kubevirt.io/client-go/api/v1"
"github.com/k8snetworkplumbingwg/kubemacpool/pkg/names"
)
func (p *PoolManager) AllocateVirtualMachineMac(virtualMachine *kubevirt.VirtualMachine) error {
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
log.V(1).Info("AllocateVirtualMachineMac: data",
"macmap", p.macPoolMap,
"podmap", p.podToMacPoolMap,
"currentMac", p.currentMac.String())
if len(virtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces) == 0 {
log.V(1).Info("no interfaces found for virtual machine, skipping mac allocation", "virtualMachine", virtualMachine)
return nil
}
if len(virtualMachine.Spec.Template.Spec.Networks) == 0 {
log.V(1).Info("no networks found for virtual machine, skipping mac allocation",
"virtualMachineName", virtualMachine.Name,
"virtualMachineNamespace", virtualMachine.Namespace)
return nil
}
networks := map[string]kubevirt.Network{}
for _, network := range virtualMachine.Spec.Template.Spec.Networks {
networks[network.Name] = network
}
log.V(1).Info("virtual machine data",
"virtualMachineName", virtualMachine.Name,
"virtualMachineNamespace", virtualMachine.Namespace,
"virtualMachineInterfaces", virtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces)
copyVM := virtualMachine.DeepCopy()
allocations := map[string]string{}
for idx, iface := range copyVM.Spec.Template.Spec.Domain.Devices.Interfaces {
if iface.Masquerade == nil && iface.Slirp == nil && networks[iface.Name].Multus == nil {
log.Info("mac address can be set only for interface of type masquerade and slirp on the pod network")
continue
}
if iface.MacAddress != "" {
if err := p.allocateRequestedVirtualMachineInterfaceMac(copyVM, iface); err != nil {
p.revertAllocationOnVm(vmNamespaced(copyVM), allocations)
return err
}
allocations[iface.Name] = iface.MacAddress
} else {
macAddr, err := p.allocateFromPoolForVirtualMachine(copyVM, iface)
if err != nil {
p.revertAllocationOnVm(vmNamespaced(copyVM), allocations)
return err
}
copyVM.Spec.Template.Spec.Domain.Devices.Interfaces[idx].MacAddress = macAddr
allocations[iface.Name] = macAddr
}
}
err := p.AddMacToWaitingConfig(allocations)
if err != nil {
return err
}
virtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces = copyVM.Spec.Template.Spec.Domain.Devices.Interfaces
return nil
}
func (p *PoolManager) ReleaseVirtualMachineMac(vm *kubevirt.VirtualMachine) error {
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
log.V(1).Info("ReleaseVirtualMachineMac: data",
"macmap", p.macPoolMap,
"podmap", p.podToMacPoolMap,
"currentMac", p.currentMac.String())
if len(vm.Spec.Template.Spec.Domain.Devices.Interfaces) == 0 {
log.V(1).Info("no interfaces found for virtual machine, skipping mac release",
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace)
return nil
}
log.V(1).Info("virtual machine data",
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace,
"interfaces", vm.Spec.Template.Spec.Domain.Devices.Interfaces)
for _, iface := range vm.Spec.Template.Spec.Domain.Devices.Interfaces {
if iface.MacAddress != "" {
delete(p.macPoolMap, iface.MacAddress)
log.Info("released mac from virtual machine",
"mac", iface.MacAddress,
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace)
}
}
return nil
}
func (p *PoolManager) UpdateMacAddressesForVirtualMachine(previousVirtualMachine, virtualMachine *kubevirt.VirtualMachine) error {
p.poolMutex.Lock()
log.V(1).Info("UpdateMacAddressesForVirtualMachine: data",
"macmap", p.macPoolMap,
"podmap", p.podToMacPoolMap,
"currentMac", p.currentMac.String())
if previousVirtualMachine == nil {
p.poolMutex.Unlock()
return p.AllocateVirtualMachineMac(virtualMachine)
}
defer p.poolMutex.Unlock()
// This map is for revert if the allocation failed
copyInterfacesMap := make(map[string]string)
// This map is for deltas
deltaInterfacesMap := make(map[string]string)
for _, iface := range previousVirtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces {
copyInterfacesMap[iface.Name] = iface.MacAddress
deltaInterfacesMap[iface.Name] = iface.MacAddress
}
copyVM := virtualMachine.DeepCopy()
newAllocations := map[string]string{}
releaseOldAllocations := map[string]string{}
for idx, iface := range virtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces {
allocatedMacAddress, ifaceExist := copyInterfacesMap[iface.Name]
// The interface was configured before check if we need to update the mac or assign the existing one
if ifaceExist {
if iface.MacAddress == "" {
copyVM.Spec.Template.Spec.Domain.Devices.Interfaces[idx].MacAddress = allocatedMacAddress
} else if iface.MacAddress != allocatedMacAddress {
// Specific mac address was requested
err := p.allocateRequestedVirtualMachineInterfaceMac(copyVM, iface)
if err != nil {
p.revertAllocationOnVm(vmNamespaced(copyVM), newAllocations)
return err
}
releaseOldAllocations[iface.Name] = allocatedMacAddress
newAllocations[iface.Name] = iface.MacAddress
}
delete(deltaInterfacesMap, iface.Name)
} else {
if iface.MacAddress != "" {
if err := p.allocateRequestedVirtualMachineInterfaceMac(copyVM, iface); err != nil {
p.revertAllocationOnVm(vmNamespaced(copyVM), newAllocations)
return err
}
newAllocations[iface.Name] = iface.MacAddress
} else {
macAddr, err := p.allocateFromPoolForVirtualMachine(copyVM, iface)
if err != nil {
p.revertAllocationOnVm(vmNamespaced(copyVM), newAllocations)
return err
}
copyVM.Spec.Template.Spec.Domain.Devices.Interfaces[idx].MacAddress = macAddr
newAllocations[iface.Name] = iface.MacAddress
}
}
}
// Release delta interfaces
log.V(1).Info("UpdateMacAddressesForVirtualMachine: delta interfaces to release",
"interfaces Map", deltaInterfacesMap)
p.releaseMacAddressesFromInterfaceMap(deltaInterfacesMap)
// Release old allocations
log.V(1).Info("UpdateMacAddressesForVirtualMachine: old interfaces to release",
"interfaces Map", releaseOldAllocations)
p.releaseMacAddressesFromInterfaceMap(releaseOldAllocations)
virtualMachine.Spec.Template.Spec.Domain.Devices.Interfaces = copyVM.Spec.Template.Spec.Domain.Devices.Interfaces
return nil
}
func (p *PoolManager) allocateFromPoolForVirtualMachine(virtualMachine *kubevirt.VirtualMachine, iface kubevirt.Interface) (string, error) {
macAddr, err := p.getFreeMac()
if err != nil {
return "", err
}
p.macPoolMap[macAddr.String()] = AllocationStatusWaitingForPod
log.Info("mac from pool was allocated for virtual machine",
"allocatedMac", macAddr.String(),
"virtualMachineName", virtualMachine.Name,
"virtualMachineNamespace", virtualMachine.Namespace)
return macAddr.String(), nil
}
func (p *PoolManager) allocateRequestedVirtualMachineInterfaceMac(virtualMachine *kubevirt.VirtualMachine, iface kubevirt.Interface) error {
requestedMac := iface.MacAddress
if _, err := net.ParseMAC(requestedMac); err != nil {
return err
}
if _, exist := p.macPoolMap[requestedMac]; exist {
err := fmt.Errorf("failed to allocate requested mac address")
log.Error(err, "mac address already allocated")
return err
}
p.macPoolMap[requestedMac] = AllocationStatusWaitingForPod
log.Info("requested mac was allocated for virtual machine",
"requestedMap", requestedMac,
"virtualMachineName", virtualMachine.Name,
"virtualMachineNamespace", virtualMachine.Namespace)
return nil
}
func (p *PoolManager) initVirtualMachineMap() error {
if !p.isKubevirt {
return nil
}
result := p.kubeClient.ExtensionsV1beta1().RESTClient().Get().RequestURI("apis/kubevirt.io/v1alpha3/virtualmachines").Do()
if result.Error() != nil {
return result.Error()
}
vms := &kubevirt.VirtualMachineList{}
err := result.Into(vms)
if err != nil {
return err
}
for _, vm := range vms.Items {
log.V(1).Info("InitMaps for virtual machine",
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace)
if len(vm.Spec.Template.Spec.Domain.Devices.Interfaces) == 0 {
log.V(1).Info("no interfaces found for virtual machine, skipping mac allocation", "virtualMachine", vm)
continue
}
if len(vm.Spec.Template.Spec.Networks) == 0 {
log.V(1).Info("no networks found for virtual machine, skipping mac allocation",
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace)
continue
}
networks := map[string]kubevirt.Network{}
for _, network := range vm.Spec.Template.Spec.Networks {
networks[network.Name] = network
}
log.V(1).Info("virtual machine data",
"virtualMachineName", vm.Name,
"virtualMachineNamespace", vm.Namespace,
"virtualMachineInterfaces", vm.Spec.Template.Spec.Domain.Devices.Interfaces)
for _, iface := range vm.Spec.Template.Spec.Domain.Devices.Interfaces {
if iface.Masquerade == nil && iface.Slirp == nil && networks[iface.Name].Multus == nil {
log.Info("mac address can be set only for interface of type masquerade and slirp on the pod network")
continue
}
if iface.MacAddress != "" {
if err := p.allocateRequestedVirtualMachineInterfaceMac(&vm, iface); err != nil {
// Dont return an error here if we can't allocate a mac for a configured vm
log.Error(fmt.Errorf("failed to parse mac address for virtual machine"),
"Invalid mac address for virtual machine",
"virtualMachineNamespace", vm.Namespace,
"virtualMachineName", vm.Name,
"virtualMachineInterfaceMac", iface.MacAddress)
continue
}
p.macPoolMap[iface.MacAddress] = AllocationStatusAllocated
}
}
}
waitingMac, err := p.getOrCreateVmMacWaitMap()
if err != nil {
return err
}
for macAddress := range waitingMac {
macAddress = strings.Replace(macAddress, "-", ":", 5)
if _, exist := p.macPoolMap[macAddress]; !exist {
p.macPoolMap[macAddress] = AllocationStatusWaitingForPod
}
}
return nil
}
func (p *PoolManager) IsKubevirtEnabled() bool {
return p.isKubevirt
}
func (p *PoolManager) isRelatedToKubevirt(pod *corev1.Pod) bool {
if pod.ObjectMeta.OwnerReferences == nil {
return false
}
for _, ref := range pod.OwnerReferences {
if ref.Kind == kubevirt.VirtualMachineInstanceGroupVersionKind.Kind {
requestUrl := fmt.Sprintf("apis/kubevirt.io/v1alpha3/namespaces/%s/virtualmachines/%s", pod.Namespace, ref.Name)
log.V(1).Info("test", "requestURI", requestUrl)
result := p.kubeClient.ExtensionsV1beta1().RESTClient().Get().RequestURI(requestUrl).Do()
data, err := result.Raw()
log.V(1).Info("get kubevirt virtual machine object response", "err", err, "response", string(data))
if err != nil && errors.IsNotFound(err) {
log.V(1).Info("this pod is an ephemeral vmi object allocating mac as a regular pod")
return false
}
return true
}
}
return false
}
func (p *PoolManager) releaseMacAddressesFromInterfaceMap(allocations map[string]string) {
for _, value := range allocations {
delete(p.macPoolMap, value)
}
}
// Revert allocation if one of the requested mac addresses fails to be allocated
func (p *PoolManager) revertAllocationOnVm(vmName string, allocations map[string]string) {
log.V(1).Info("Revert vm allocation", "vmName", vmName, "allocations", allocations)
p.releaseMacAddressesFromInterfaceMap(allocations)
}
// This function return or creates a config map that contains mac address and the allocation time.
func (p *PoolManager) getOrCreateVmMacWaitMap() (map[string]string, error) {
configMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
_, err = p.kubeClient.CoreV1().
ConfigMaps(p.managerNamespace).
Create(&corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: names.WAITING_VMS_CONFIGMAP,
Namespace: p.managerNamespace}})
return map[string]string{}, nil
}
return nil, err
}
return configMap.Data, nil
}
// Add all the allocated mac addresses to the waiting config map with the current time.
func (p *PoolManager) AddMacToWaitingConfig(allocations map[string]string) error {
configMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})
if err != nil {
return err
}
if configMap.Data == nil {
configMap.Data = map[string]string{}
}
for _, macAddress := range allocations {
log.V(1).Info("add mac address to waiting config", "macAddress", macAddress)
macAddress = strings.Replace(macAddress, ":", "-", 5)
configMap.Data[macAddress] = time.Now().Format(time.RFC3339)
}
_, err = p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Update(configMap)
return err
}
// Remove all the mac addresses from the waiting configmap this mean the vm was saved in the etcd and pass validations
func (p *PoolManager) MarkVMAsReady(vm *kubevirt.VirtualMachine) error {
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
configMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})
if err != nil {
return err
}
if configMap.Data == nil {
log.Info("the configMap is empty")
return nil
}
for _, vmInterface := range vm.Spec.Template.Spec.Domain.Devices.Interfaces {
if vmInterface.MacAddress != "" {
p.macPoolMap[vmInterface.MacAddress] = AllocationStatusAllocated
macAddress := strings.Replace(vmInterface.MacAddress, ":", "-", 5)
delete(configMap.Data, macAddress)
}
}
_, err = p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Update(configMap)
log.V(1).Info("marked virtual machine as ready", "virtualMachineNamespace", vm.Namespace,
"virtualMachineName", vm.Name)
return err
}
// This function check if there are virtual machines that hits the create
// mutating webhook but we didn't get the creation event in the controller loop
// this mean the create was failed by some other mutating or validating webhook
// so we release the virtual machine
func (p *PoolManager) vmWaitingCleanupLook(waitTime int) {
c := time.Tick(3 * time.Second)
log.Info("starting cleanup loop for waiting mac addresses")
for _ = range c {
p.poolMutex.Lock()
configMap, err := p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Get(names.WAITING_VMS_CONFIGMAP, metav1.GetOptions{})
if err != nil {
log.Error(err, "failed to get config map", "configMapName", names.WAITING_VMS_CONFIGMAP)
p.poolMutex.Unlock()
continue
}
if configMap.Data == nil {
log.Info("the configMap is empty", "configMapName", names.WAITING_VMS_CONFIGMAP)
p.poolMutex.Unlock()
continue
}
for macAddress, allocationTime := range configMap.Data {
t, err := time.Parse(time.RFC3339, allocationTime)
if err != nil {
// TODO: remove the mac from the wait map??
log.Error(err, "failed to parse allocation time")
continue
}
if time.Now().After(t.Add(time.Duration(waitTime) * time.Second)) {
delete(configMap.Data, macAddress)
macAddress = strings.Replace(macAddress, "-", ":", 5)
delete(p.macPoolMap, macAddress)
log.V(1).Info("released mac address in waiting loop", "macAddress", macAddress)
}
}
_, err = p.kubeClient.CoreV1().ConfigMaps(p.managerNamespace).Update(configMap)
if err != nil {
log.Error(err, "failed to update config map", "configMapName", names.WAITING_VMS_CONFIGMAP)
}
p.poolMutex.Unlock()
}
}
// Checks if the namespace of a vm instance is opted in for kubemacpool
func (p *PoolManager) IsVmInstanceOptedIn(namespaceName string) (bool, error) {
return p.isInstanceOptedIn(namespaceName, "kubemacpool-mutator", "mutatevirtualmachines.kubemacpool.io")
}
func vmNamespaced(machine *kubevirt.VirtualMachine) string {
return fmt.Sprintf("%s/%s", machine.Namespace, machine.Name)
}