Repository navigation
Expand file tree
/
Copy pathvm.go
More file actions
3640 lines (3122 loc) · 129 KB
/
Copy pathvm.go
File metadata and controls
3640 lines (3122 loc) · 129 KB
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
/*
* This file is part of the KubeVirt project
*
* 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.
*
* Copyright The KubeVirt Authors.
*
*/
package vm
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"math"
"math/rand"
"strconv"
"strings"
"time"
"kubevirt.io/kubevirt/pkg/instancetype/revision"
"kubevirt.io/kubevirt/pkg/libvmi"
"kubevirt.io/kubevirt/pkg/liveupdate/memory"
"kubevirt.io/kubevirt/pkg/pointer"
netadmitter "kubevirt.io/kubevirt/pkg/network/admitter"
netvmispec "kubevirt.io/kubevirt/pkg/network/vmispec"
netvmliveupdate "kubevirt.io/kubevirt/pkg/network/vmliveupdate"
"kubevirt.io/kubevirt/pkg/virt-controller/watch/common"
watchutil "kubevirt.io/kubevirt/pkg/virt-controller/watch/util"
appsv1 "k8s.io/api/apps/v1"
authv1 "k8s.io/api/authorization/v1"
k8score "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
k8sfield "k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/utils/trace"
virtv1 "kubevirt.io/api/core/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/client-go/log"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
"kubevirt.io/kubevirt/pkg/apimachinery/patch"
"kubevirt.io/kubevirt/pkg/controller"
"kubevirt.io/kubevirt/pkg/storage/cbt"
storagehotplug "kubevirt.io/kubevirt/pkg/storage/hotplug"
"kubevirt.io/kubevirt/pkg/storage/memorydump"
storagetypes "kubevirt.io/kubevirt/pkg/storage/types"
storageutils "kubevirt.io/kubevirt/pkg/storage/utils"
"kubevirt.io/kubevirt/pkg/storage/velero"
"kubevirt.io/kubevirt/pkg/util"
"kubevirt.io/kubevirt/pkg/util/hardware"
"kubevirt.io/kubevirt/pkg/util/migrations"
traceUtils "kubevirt.io/kubevirt/pkg/util/trace"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-controller/watch/descheduler"
volumemig "kubevirt.io/kubevirt/pkg/virt-controller/watch/volume-migration"
)
const (
fetchingRunStrategyErrFmt = "Error fetching RunStrategy: %v"
fetchingVMKeyErrFmt = "Error fetching vmKey: %v"
startingVMIFailureFmt = "Failure while starting VMI: %v"
nonReceiverVMI = "Found non receiver VMI while VM is receiver"
)
type CloneAuthFunc func(dv *cdiv1.DataVolume, requestNamespace, requestName string, proxy cdiv1.AuthorizationHelperProxy, saNamespace, saName string) (bool, string, error)
// Repeating info / error messages
const (
stoppingVmMsg = "Stopping VM"
startingVmMsg = "Starting VM"
startingVmReceiverMsg = "Starting VM as receiver"
failedExtractVmkeyFromVmErrMsg = "Failed to extract vmKey from VirtualMachine."
failedCreateCRforVmErrMsg = "Failed to create controller revision for VirtualMachine."
failedProcessDeleteNotificationErrMsg = "Failed to process delete notification"
failureDeletingVmiErrFormat = "Failure attempting to delete VMI: %v"
failedManualRecoveryRequiredCondSetErrMsg = "cannot start the VM since it has the manual recovery required condtion set"
// UnauthorizedDataVolumeCreateReason is added in an event when the DataVolume
// ServiceAccount doesn't have permission to create a DataVolume
UnauthorizedDataVolumeCreateReason = "UnauthorizedDataVolumeCreate"
// FailedDataVolumeCreateReason is added in an event when posting a dynamically
// generated dataVolume to the cluster fails.
FailedDataVolumeCreateReason = "FailedDataVolumeCreate"
// SuccessfulDataVolumeCreateReason is added in an event when a dynamically generated
// dataVolume is successfully created
SuccessfulDataVolumeCreateReason = "SuccessfulDataVolumeCreate"
// SourcePVCNotAvailabe is added in an event when the source PVC of a valid
// clone Datavolume doesn't exist
SourcePVCNotAvailabe = "SourcePVCNotAvailabe"
)
const (
hotplugVolumeErrorReason = "HotPlugVolumeError"
hotplugCPUErrorReason = "HotPlugCPUError"
failedUpdateErrorReason = "FailedUpdateError"
failedCreateReason = "FailedCreate"
vmiFailedDeleteReason = "FailedDelete"
affinityChangeErrorReason = "AffinityChangeError"
hotplugMemoryErrorReason = "HotPlugMemoryError"
volumesUpdateErrorReason = "VolumesUpdateError"
tolerationsChangeErrorReason = "TolerationsChangeError"
annotationsLabelsChangeErrorReason = "AnnotationsLabelsChangeError"
)
const defaultMaxCrashLoopBackoffDelaySeconds = 300
func NewController(vmiInformer cache.SharedIndexInformer,
vmInformer cache.SharedIndexInformer,
dataVolumeInformer cache.SharedIndexInformer,
dataSourceInformer cache.SharedIndexInformer,
kubeVirtInformer cache.SharedIndexInformer,
namespaceInformer cache.SharedIndexInformer,
pvcInformer cache.SharedIndexInformer,
crInformer cache.SharedIndexInformer,
recorder record.EventRecorder,
clientset kubecli.KubevirtClient,
clusterConfig *virtconfig.ClusterConfig,
netSynchronizer synchronizer,
firmwareSynchronizer synchronizer,
instancetypeController instancetypeHandler,
additionalLauncherAnnotationsSync []string,
additionalLauncherLabelsSync []string,
) (*Controller, error) {
c := &Controller{
Queue: workqueue.NewTypedRateLimitingQueueWithConfig[string](
workqueue.DefaultTypedControllerRateLimiter[string](),
workqueue.TypedRateLimitingQueueConfig[string]{Name: "virt-controller-vm"},
),
vmiIndexer: vmiInformer.GetIndexer(),
vmIndexer: vmInformer.GetIndexer(),
dataVolumeStore: dataVolumeInformer.GetStore(),
dataSourceStore: dataSourceInformer.GetStore(),
namespaceStore: namespaceInformer.GetStore(),
pvcStore: pvcInformer.GetStore(),
crIndexer: crInformer.GetIndexer(),
instancetypeController: instancetypeController,
recorder: recorder,
clientset: clientset,
expectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()),
dataVolumeExpectations: controller.NewUIDTrackingControllerExpectations(controller.NewControllerExpectations()),
cloneAuthFunc: func(dv *cdiv1.DataVolume, requestNamespace, requestName string, proxy cdiv1.AuthorizationHelperProxy, saNamespace, saName string) (bool, string, error) {
response, err := dv.AuthorizeSA(requestNamespace, requestName, proxy, saNamespace, saName)
return response.Allowed, response.Reason, err
},
clusterConfig: clusterConfig,
netSynchronizer: netSynchronizer,
firmwareSynchronizer: firmwareSynchronizer,
additionalLauncherAnnotationsSync: additionalLauncherAnnotationsSync,
additionalLauncherLabelsSync: additionalLauncherLabelsSync,
}
c.hasSynced = func() bool {
return vmiInformer.HasSynced() && vmInformer.HasSynced() &&
dataVolumeInformer.HasSynced() && dataSourceInformer.HasSynced() &&
pvcInformer.HasSynced() && crInformer.HasSynced()
}
_, err := vmInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addVirtualMachine,
DeleteFunc: c.deleteVirtualMachine,
UpdateFunc: c.updateVirtualMachine,
})
if err != nil {
return nil, err
}
_, err = vmiInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addVirtualMachineInstance,
DeleteFunc: c.deleteVirtualMachineInstance,
UpdateFunc: c.updateVirtualMachineInstance,
})
if err != nil {
return nil, err
}
_, err = dataVolumeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addDataVolume,
DeleteFunc: c.deleteDataVolume,
UpdateFunc: c.updateDataVolume,
})
if err != nil {
return nil, err
}
_, err = pvcInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addPVC,
})
if err != nil {
return nil, err
}
_, err = kubeVirtInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
UpdateFunc: c.handleKubeVirtUpdate,
})
if err != nil {
return nil, err
}
_, err = namespaceInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
UpdateFunc: c.handleNamespaceUpdate,
})
if err != nil {
return nil, err
}
return c, nil
}
type authProxy struct {
client kubecli.KubevirtClient
dataSourceStore cache.Store
namespaceStore cache.Store
}
func (p *authProxy) CreateSar(sar *authv1.SubjectAccessReview) (*authv1.SubjectAccessReview, error) {
return p.client.AuthorizationV1().SubjectAccessReviews().Create(context.Background(), sar, metav1.CreateOptions{})
}
func (p *authProxy) GetNamespace(name string) (*k8score.Namespace, error) {
obj, exists, err := p.namespaceStore.GetByKey(name)
if err != nil {
return nil, err
} else if !exists {
return nil, fmt.Errorf("namespace %s does not exist", name)
}
ns := obj.(*k8score.Namespace).DeepCopy()
return ns, nil
}
func (p *authProxy) GetDataSource(namespace, name string) (*cdiv1.DataSource, error) {
key := fmt.Sprintf("%s/%s", namespace, name)
obj, exists, err := p.dataSourceStore.GetByKey(key)
if err != nil {
return nil, err
} else if !exists {
return nil, fmt.Errorf("dataSource %s does not exist", key)
}
ds := obj.(*cdiv1.DataSource).DeepCopy()
return ds, nil
}
type synchronizer interface {
Sync(*virtv1.VirtualMachine, *virtv1.VirtualMachineInstance) (*virtv1.VirtualMachine, error)
}
type instancetypeHandler interface {
synchronizer
ApplyToVM(*virtv1.VirtualMachine) error
ApplyToVMI(*virtv1.VirtualMachine, *virtv1.VirtualMachineInstance) error
ApplyAutoAttachPreferences(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error
}
type Controller struct {
clientset kubecli.KubevirtClient
Queue workqueue.TypedRateLimitingInterface[string]
vmiIndexer cache.Indexer
vmIndexer cache.Indexer
dataVolumeStore cache.Store
dataSourceStore cache.Store
namespaceStore cache.Store
pvcStore cache.Store
crIndexer cache.Indexer
instancetypeController instancetypeHandler
recorder record.EventRecorder
expectations *controller.UIDTrackingControllerExpectations
dataVolumeExpectations *controller.UIDTrackingControllerExpectations
cloneAuthFunc CloneAuthFunc
clusterConfig *virtconfig.ClusterConfig
hasSynced func() bool
netSynchronizer synchronizer
firmwareSynchronizer synchronizer
additionalLauncherAnnotationsSync []string
additionalLauncherLabelsSync []string
}
func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) {
defer controller.HandlePanic()
defer c.Queue.ShutDown()
log.Log.Info("Starting VirtualMachine controller.")
// Wait for cache sync before we start the controller
cache.WaitForCacheSync(stopCh, c.hasSynced)
// Start the actual work
for i := 0; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
<-stopCh
log.Log.Info("Stopping VirtualMachine controller.")
}
func (c *Controller) runWorker() {
for c.Execute() {
}
}
func (c *Controller) satisfiedExpectations(key string) bool {
return c.expectations.SatisfiedExpectations(key) && c.dataVolumeExpectations.SatisfiedExpectations(key)
}
var virtControllerVMWorkQueueTracer = &traceUtils.Tracer{Threshold: time.Second}
func (c *Controller) Execute() bool {
key, quit := c.Queue.Get()
if quit {
return false
}
virtControllerVMWorkQueueTracer.StartTrace(key, "virt-controller VM workqueue", trace.Field{Key: "Workqueue Key", Value: key})
defer virtControllerVMWorkQueueTracer.StopTrace(key)
defer c.Queue.Done(key)
if err := c.execute(key); err != nil {
log.Log.Reason(err).Infof("re-enqueuing VirtualMachine %v", key)
c.Queue.AddRateLimited(key)
} else {
log.Log.V(4).Infof("processed VirtualMachine %v", key)
c.Queue.Forget(key)
}
return true
}
func (c *Controller) execute(key string) error {
obj, exists, err := c.vmIndexer.GetByKey(key)
if err != nil {
return nil
}
if !exists {
// nothing we need to do. It should always be possible to re-create this type of controller
c.expectations.DeleteExpectations(key)
return nil
}
originalVM := obj.(*virtv1.VirtualMachine)
vm := originalVM.DeepCopy()
logger := log.Log.Object(vm)
logger.V(4).Info("Started processing vm")
// this must be first step in execution. Writing the object
// when api version changes ensures our api stored version is updated.
if !controller.ObservedLatestApiVersionAnnotation(vm) {
controller.SetLatestApiVersionAnnotation(vm)
_, err = c.clientset.VirtualMachine(vm.Namespace).Update(context.Background(), vm, metav1.UpdateOptions{})
if err != nil {
logger.Reason(err).Error("Updating api version annotations failed")
}
return err
}
vmKey, err := controller.KeyFunc(vm)
if err != nil {
return err
}
// If any adoptions are attempted, we should first recheck for deletion with
// an uncached quorum read sometime after listing VirtualMachines (see kubernetes/kubernetes#42639).
canAdoptFunc := controller.RecheckDeletionTimestamp(func() (metav1.Object, error) {
fresh, err := c.clientset.VirtualMachine(vm.ObjectMeta.Namespace).Get(context.Background(), vm.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return nil, err
}
if fresh.ObjectMeta.UID != vm.ObjectMeta.UID {
return nil, fmt.Errorf("original VirtualMachine %v/%v is gone: got uid %v, wanted %v", vm.Namespace, vm.Name, fresh.UID, vm.UID)
}
return fresh, nil
})
cm := controller.NewVirtualMachineControllerRefManager(
controller.RealVirtualMachineControl{
Clientset: c.clientset,
}, vm, nil, virtv1.VirtualMachineGroupVersionKind, canAdoptFunc)
var vmi *virtv1.VirtualMachineInstance
vmiObj, exist, err := c.vmiIndexer.GetByKey(vmKey)
if err != nil {
logger.Reason(err).Error("Failed to fetch vmi for namespace from cache.")
return err
}
if !exist {
logger.V(4).Infof("VirtualMachineInstance not found in cache %s", key)
vmi = nil
} else {
vmi = vmiObj.(*virtv1.VirtualMachineInstance)
vmi, err = cm.ClaimVirtualMachineInstanceByName(vmi)
if err != nil {
return err
}
}
dataVolumes, err := storagetypes.ListDataVolumesFromTemplates(vm.Namespace, vm.Spec.DataVolumeTemplates, c.dataVolumeStore)
if err != nil {
logger.Reason(err).Error("Failed to fetch dataVolumes for namespace from cache.")
return err
}
if len(dataVolumes) != 0 {
dataVolumes, err = cm.ClaimMatchedDataVolumes(dataVolumes)
if err != nil {
return err
}
}
var syncErr common.SyncError
vm, vmi, syncErr, err = c.sync(vm, vmi, key)
if err != nil {
return err
}
if syncErr != nil {
logger.Reason(syncErr).Error("Reconciling the VirtualMachine failed.")
}
err = c.updateStatus(vm, originalVM, vmi, syncErr, logger)
if err != nil {
logger.Reason(err).Error("Updating the VirtualMachine status failed.")
return err
}
return syncErr
}
func (c *Controller) handleCloneDataVolume(vm *virtv1.VirtualMachine, dv *cdiv1.DataVolume) error {
if dv.Spec.SourceRef != nil {
return fmt.Errorf("DataVolume sourceRef not supported")
}
if dv.Spec.Source == nil {
return nil
}
// For consistency with other k8s objects, we allow creating clone DataVolumes even when the source PVC doesn't exist.
// This means that a VirtualMachine can be successfully created with volumes that may remain unpopulated until the source PVC is created.
// For this reason, we check if the source PVC exists and, if not, we trigger an event to let users know of this behavior.
if dv.Spec.Source.PVC != nil {
// TODO: a lot of CDI knowledge, maybe an API to check if source exists?
pvc, err := storagetypes.GetPersistentVolumeClaimFromCache(dv.Spec.Source.PVC.Namespace, dv.Spec.Source.PVC.Name, c.pvcStore)
if err != nil {
return err
}
if pvc == nil {
c.recorder.Eventf(vm, k8score.EventTypeWarning, SourcePVCNotAvailabe, "Source PVC %s not available: Target PVC %s will remain unpopulated until source is created", dv.Spec.Source.PVC.Name, dv.Name)
}
}
if err := c.authorizeDataVolume(vm, dv); err != nil {
c.recorder.Eventf(vm, k8score.EventTypeWarning, UnauthorizedDataVolumeCreateReason, "Not authorized to create DataVolume %s: %v", dv.Name, err)
return fmt.Errorf("not authorized to create DataVolume: %v", err)
}
return nil
}
func (c *Controller) authorizeDataVolume(vm *virtv1.VirtualMachine, dataVolume *cdiv1.DataVolume) error {
serviceAccountName := "default"
if vm.Spec.Template.Spec.ServiceAccountName != "" {
serviceAccountName = vm.Spec.Template.Spec.ServiceAccountName
} else if sa := storageutils.ServiceAccountNameFromVolumes(vm.Spec.Template.Spec.Volumes); sa != "" {
serviceAccountName = sa
}
proxy := &authProxy{client: c.clientset, dataSourceStore: c.dataSourceStore, namespaceStore: c.namespaceStore}
allowed, reason, err := c.cloneAuthFunc(dataVolume, vm.Namespace, dataVolume.Name, proxy, vm.Namespace, serviceAccountName)
if err != nil && err != cdiv1.ErrNoTokenOkay {
return err
}
if !allowed {
return fmt.Errorf("%s", reason)
}
return nil
}
func (c *Controller) handleDataVolumes(vm *virtv1.VirtualMachine) (bool, error) {
ready := true
vmKey, err := controller.KeyFunc(vm)
if err != nil {
return ready, err
}
for _, template := range vm.Spec.DataVolumeTemplates {
curDataVolume, err := storagetypes.GetDataVolumeFromCache(vm.Namespace, template.Name, c.dataVolumeStore)
if err != nil {
return false, err
}
if curDataVolume == nil {
// Don't create DV if PVC already exists
pvc, err := storagetypes.GetPersistentVolumeClaimFromCache(vm.Namespace, template.Name, c.pvcStore)
if err != nil {
return false, err
}
// ready = false because encountered DataVolume that is not created yet
ready = false
newDataVolume, err := watchutil.CreateDataVolumeManifest(c.clientset, template, vm)
if err != nil {
return ready, fmt.Errorf("unable to create DataVolume manifest: %v", err)
}
// We validate requirements that are exclusive to clone DataVolumes
if err = c.handleCloneDataVolume(vm, newDataVolume); err != nil {
return ready, err
}
c.dataVolumeExpectations.ExpectCreations(vmKey, 1)
curDataVolume, err = c.clientset.CdiClient().CdiV1beta1().DataVolumes(vm.Namespace).Create(context.Background(), newDataVolume, metav1.CreateOptions{})
if err != nil {
c.dataVolumeExpectations.CreationObserved(vmKey)
if pvc != nil && strings.Contains(err.Error(), "already exists") {
// If the PVC already exists, we can ignore the error and continue
// probably old version of CDI
log.Log.Object(vm).Reason(err).Warning("Appear to be running a version of CDI that does not support claim adoption annotation")
continue
}
c.recorder.Eventf(vm, k8score.EventTypeWarning, FailedDataVolumeCreateReason, "Error creating DataVolume %s: %v", newDataVolume.Name, err)
return ready, fmt.Errorf("failed to create DataVolume: %v", err)
}
c.recorder.Eventf(vm, k8score.EventTypeNormal, SuccessfulDataVolumeCreateReason, "Created DataVolume %s", curDataVolume.Name)
} else {
switch curDataVolume.Status.Phase {
case cdiv1.Succeeded, cdiv1.WaitForFirstConsumer, cdiv1.PendingPopulation:
continue
case cdiv1.Failed:
c.recorder.Eventf(vm, k8score.EventTypeWarning, controller.FailedDataVolumeImportReason, "DataVolume %s failed to import disk image", curDataVolume.Name)
case cdiv1.Pending:
if err := storagetypes.HasDataVolumeExceededQuotaError(curDataVolume); err != nil {
c.recorder.Eventf(vm, k8score.EventTypeWarning, controller.FailedDataVolumeImportReason, "DataVolume %s exceeds quota limits", curDataVolume.Name)
return false, err
}
}
// ready = false because encountered DataVolume that is not populated yet
ready = false
}
}
return ready, nil
}
func (c *Controller) VMICPUsPatch(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
patchSet := patch.New(
patch.WithTest("/spec/domain/cpu/sockets", vmi.Spec.Domain.CPU.Sockets),
patch.WithReplace("/spec/domain/cpu/sockets", vm.Spec.Template.Spec.Domain.CPU.Sockets),
)
vcpusDelta := hardware.GetNumberOfVCPUs(vm.Spec.Template.Spec.Domain.CPU) - hardware.GetNumberOfVCPUs(vmi.Spec.Domain.CPU)
resourcesDelta := resource.NewMilliQuantity(vcpusDelta*int64(1000/c.clusterConfig.GetCPUAllocationRatio()), resource.DecimalSI)
logMsg := fmt.Sprintf("hotplugging cpu to %v sockets", vm.Spec.Template.Spec.Domain.CPU.Sockets)
if !vm.Spec.Template.Spec.Domain.Resources.Requests.Cpu().IsZero() {
newCpuReq := vmi.Spec.Domain.Resources.Requests.Cpu().DeepCopy()
newCpuReq.Add(*resourcesDelta)
patchSet.AddOption(
patch.WithTest("/spec/domain/resources/requests/cpu", vmi.Spec.Domain.Resources.Requests.Cpu().String()),
patch.WithReplace("/spec/domain/resources/requests/cpu", newCpuReq.String()),
)
logMsg = fmt.Sprintf("%s, setting requests to %s", logMsg, newCpuReq.String())
}
if !vm.Spec.Template.Spec.Domain.Resources.Limits.Cpu().IsZero() {
newCpuLimit := vmi.Spec.Domain.Resources.Limits.Cpu().DeepCopy()
newCpuLimit.Add(*resourcesDelta)
patchSet.AddOption(
patch.WithTest("/spec/domain/resources/limits/cpu", vmi.Spec.Domain.Resources.Limits.Cpu().String()),
patch.WithReplace("/spec/domain/resources/limits/cpu", newCpuLimit.String()),
)
logMsg = fmt.Sprintf("%s, setting limits to %s", logMsg, newCpuLimit.String())
}
patchBytes, err := patchSet.GeneratePayload()
if err != nil {
return err
}
_, err = c.clientset.VirtualMachineInstance(vmi.Namespace).Patch(context.Background(), vmi.Name, types.JSONPatchType, patchBytes, v1.PatchOptions{})
if err == nil {
log.Log.Object(vmi).Infof("%s", logMsg)
}
return err
}
func (c *Controller) handleCPUChangeRequest(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if vmi == nil || vmi.DeletionTimestamp != nil {
return nil
}
vmCopyWithInstancetype := vm.DeepCopy()
if err := c.instancetypeController.ApplyToVM(vmCopyWithInstancetype); err != nil {
return err
}
if vmCopyWithInstancetype.Spec.Template.Spec.Domain.CPU == nil || vmi.Spec.Domain.CPU == nil {
return nil
}
if vmCopyWithInstancetype.Spec.Template.Spec.Domain.CPU.Sockets == vmi.Spec.Domain.CPU.Sockets {
return nil
}
vmiConditions := controller.NewVirtualMachineInstanceConditionManager()
if vmiConditions.HasConditionWithStatus(vmi, virtv1.VirtualMachineInstanceVCPUChange, k8score.ConditionTrue) {
return fmt.Errorf("another CPU hotplug is in progress")
}
if migrations.IsMigrating(vmi) {
return fmt.Errorf("CPU hotplug is not allowed while VMI is migrating")
}
// If the following is true, MaxSockets was calculated, not manually specified (or the validation webhook would have rejected the change).
// Since we're here, we can also assume MaxSockets was not changed in the VM spec since last boot.
// Therefore, bumping Sockets to a value higher than MaxSockets is fine, it just requires a reboot.
if vmCopyWithInstancetype.Spec.Template.Spec.Domain.CPU.Sockets > vmi.Spec.Domain.CPU.MaxSockets {
setRestartRequired(vm, "CPU sockets updated in template spec to a value higher than what's available")
return nil
}
if vmCopyWithInstancetype.Spec.Template.Spec.Domain.CPU.Sockets < vmi.Spec.Domain.CPU.Sockets {
setRestartRequired(vm, "Reduction of CPU socket count requires a restart")
return nil
}
if virtconfig.IsARM64(vm.Spec.Template.Spec.Architecture) {
setRestartRequired(vm, "ARM doesn't support CPU hotplug")
return nil
}
if err := c.VMICPUsPatch(vmCopyWithInstancetype, vmi); err != nil {
log.Log.Object(vmi).Errorf("unable to patch vmi to add cpu topology status: %v", err)
return err
}
return nil
}
func (c *Controller) VMNodeSelectorPatch(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
patchset := patch.New()
if vm.Spec.Template.Spec.NodeSelector != nil {
vmNodeSelector := maps.Clone(vm.Spec.Template.Spec.NodeSelector)
if vmNodeSelector == nil {
vmNodeSelector = make(map[string]string)
}
if vmi.Spec.NodeSelector == nil {
patchset.AddOption(patch.WithAdd("/spec/nodeSelector", vmNodeSelector))
} else {
patchset.AddOption(
patch.WithTest("/spec/nodeSelector", vmi.Spec.NodeSelector),
patch.WithReplace("/spec/nodeSelector", vmNodeSelector))
}
} else {
patchset.AddOption(patch.WithRemove("/spec/nodeSelector"))
}
generatedPatch, err := patchset.GeneratePayload()
if err != nil {
return err
}
_, err = c.clientset.VirtualMachineInstance(vmi.Namespace).Patch(context.Background(), vmi.Name, types.JSONPatchType, generatedPatch, metav1.PatchOptions{})
return err
}
func (c *Controller) VMIAffinityPatch(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
patchset := patch.New()
if vm.Spec.Template.Spec.Affinity != nil {
if vmi.Spec.Affinity == nil {
patchset.AddOption(patch.WithAdd("/spec/affinity", vm.Spec.Template.Spec.Affinity))
} else {
patchset.AddOption(
patch.WithTest("/spec/affinity", vmi.Spec.Affinity),
patch.WithReplace("/spec/affinity", vm.Spec.Template.Spec.Affinity))
}
} else {
patchset.AddOption(patch.WithRemove("/spec/affinity"))
}
generatedPatch, err := patchset.GeneratePayload()
if err != nil {
return err
}
_, err = c.clientset.VirtualMachineInstance(vmi.Namespace).Patch(context.Background(), vmi.Name, types.JSONPatchType, generatedPatch, metav1.PatchOptions{})
return err
}
func (c *Controller) vmiTolerationsPatch(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
patchset := patch.New()
if vm.Spec.Template.Spec.Tolerations != nil {
if vmi.Spec.Tolerations == nil {
patchset.AddOption(patch.WithAdd("/spec/tolerations", vm.Spec.Template.Spec.Tolerations))
} else {
patchset.AddOption(
patch.WithTest("/spec/tolerations", vmi.Spec.Tolerations),
patch.WithReplace("/spec/tolerations", vm.Spec.Template.Spec.Tolerations))
}
} else {
patchset.AddOption(patch.WithRemove("/spec/tolerations"))
}
generatedPatch, err := patchset.GeneratePayload()
if err != nil {
return err
}
_, err = c.clientset.VirtualMachineInstance(vmi.Namespace).Patch(context.Background(), vmi.Name, types.JSONPatchType, generatedPatch, metav1.PatchOptions{})
return err
}
func (c *Controller) handleTolerationsChangeRequest(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if vmi == nil || vmi.DeletionTimestamp != nil {
return nil
}
vmCopyWithInstancetype := vm.DeepCopy()
if err := c.instancetypeController.ApplyToVM(vmCopyWithInstancetype); err != nil {
return err
}
if equality.Semantic.DeepEqual(vmCopyWithInstancetype.Spec.Template.Spec.Tolerations, vmi.Spec.Tolerations) {
return nil
}
if migrations.IsMigrating(vmi) {
return fmt.Errorf("tolerations should not be changed during VMI migration")
}
if err := c.vmiTolerationsPatch(vmCopyWithInstancetype, vmi); err != nil {
log.Log.Object(vmi).Errorf("unable to patch vmi to update tolerations: %v", err)
return err
}
return nil
}
func (c *Controller) handleAffinityChangeRequest(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if vmi == nil || vmi.DeletionTimestamp != nil {
return nil
}
vmCopyWithInstancetype := vm.DeepCopy()
if err := c.instancetypeController.ApplyToVM(vmCopyWithInstancetype); err != nil {
return err
}
hasNodeSelectorChanged := !equality.Semantic.DeepEqual(vmCopyWithInstancetype.Spec.Template.Spec.NodeSelector, vmi.Spec.NodeSelector)
hasNodeAffinityChanged := !equality.Semantic.DeepEqual(vmCopyWithInstancetype.Spec.Template.Spec.Affinity, vmi.Spec.Affinity)
if migrations.IsMigrating(vmi) && (hasNodeSelectorChanged || hasNodeAffinityChanged) {
return fmt.Errorf("Node affinity should not be changed during VMI migration")
}
if hasNodeAffinityChanged {
if err := c.VMIAffinityPatch(vmCopyWithInstancetype, vmi); err != nil {
log.Log.Object(vmi).Errorf("unable to patch vmi to update node affinity: %v", err)
return err
}
}
if hasNodeSelectorChanged {
if err := c.VMNodeSelectorPatch(vmCopyWithInstancetype, vmi); err != nil {
log.Log.Object(vmi).Errorf("unable to patch vmi to update node selector: %v", err)
return err
}
}
return nil
}
func (c *Controller) handleVolumeRequests(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if len(vm.Status.VolumeRequests) == 0 {
return nil
}
vmiVolumeMap := make(map[string]virtv1.Volume)
if vmi != nil {
for _, volume := range vmi.Spec.Volumes {
vmiVolumeMap[volume.Name] = volume
}
}
for i, request := range vm.Status.VolumeRequests {
vm.Spec.Template.Spec = *controller.ApplyVolumeRequestOnVMISpec(&vm.Spec.Template.Spec, &vm.Status.VolumeRequests[i])
if vmi == nil || vmi.DeletionTimestamp != nil {
continue
}
if request.AddVolumeOptions != nil {
if _, exists := vmiVolumeMap[request.AddVolumeOptions.Name]; exists {
continue
}
if err := c.clientset.VirtualMachineInstance(vmi.Namespace).AddVolume(context.Background(), vmi.Name, request.AddVolumeOptions); err != nil {
return err
}
} else if request.RemoveVolumeOptions != nil {
if _, exists := vmiVolumeMap[request.RemoveVolumeOptions.Name]; !exists {
continue
}
if err := c.clientset.VirtualMachineInstance(vmi.Namespace).RemoveVolume(context.Background(), vmi.Name, request.RemoveVolumeOptions); err != nil {
return err
}
}
}
return nil
}
func (c *Controller) handleValidationErrors(err error, vmi *virtv1.VirtualMachineInstance, vm *virtv1.VirtualMachine) error {
if errors.Is(err, storagetypes.ErrPVCNotFound) || errors.Is(err, storagetypes.ErrDVNotFound) {
msg := fmt.Sprintf("One of the destination volumes doesn't exist: %v", err)
log.Log.Object(vm).Error(msg)
if err := volumemig.SetVolumesChangeCondition(c.clientset, vmi, k8score.ConditionFalse, msg); err != nil {
return err
}
return nil
}
setRestartRequired(vm, err.Error())
log.Log.Object(vm).Errorf("cannot migrate the VM. Volumes are invalid: %v", err)
return nil
}
func isWaitAsReceiverRunStrategy(vm *virtv1.VirtualMachine) bool {
return vm.Spec.RunStrategy != nil && *vm.Spec.RunStrategy == virtv1.RunStrategyWaitAsReceiver
}
func (c *Controller) handleWaitAsReceiverVolumeInfo(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if vmi == nil {
return nil
}
if vmi.IsMigrationCompleted() {
return nil
}
migVols, err := volumemig.GenerateReceiverMigratedVolumes(c.pvcStore, vmi, vm)
if err != nil {
log.Log.Object(vm).Errorf("failed to generate the migrating volumes for vm: %v", err)
return err
}
if err := volumemig.PatchVMIStatusWithMigratedVolumes(c.clientset, migVols, vmi); err != nil {
log.Log.Object(vm).Errorf("failed to update migrating volumes for vmi:%v", err)
return err
}
return nil
}
func (c *Controller) handleVolumeUpdateRequest(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance) error {
if vmi == nil {
return nil
}
// Abort the volume migration if any of the previous migrated volumes
// has changed
if volMigAbort, err := volumemig.VolumeMigrationCancel(c.clientset, vmi, vm); volMigAbort {
if err == nil {
log.Log.Object(vm).Infof("Cancel volume migration")
}
return err
}
switch {
case vm.Spec.UpdateVolumesStrategy == nil ||
*vm.Spec.UpdateVolumesStrategy == virtv1.UpdateVolumesStrategyReplacement:
log.Log.Object(vm).V(4).Infof("not handling replacement update volumes strategy")
case vm.Spec.UpdateVolumesStrategy != nil && *vm.Spec.UpdateVolumesStrategy == virtv1.UpdateVolumesStrategyMigration:
if !volumemig.PersistentVolumesUpdated(&vm.Spec.Template.Spec, &vmi.Spec) {
log.Log.Object(vm).V(4).Infof("No persistent volumes updated")
return nil
}
// Validate if the update volumes can be migrated
if err := volumemig.ValidateVolumes(vmi, vm, c.dataVolumeStore, c.pvcStore); err != nil {
return c.handleValidationErrors(err, vmi, vm)
} else if err := volumemig.UnsetVolumeChangeCondition(c.clientset, vmi); err != nil {
return err
}
migVols, err := volumemig.GenerateMigratedVolumes(c.pvcStore, vmi, vm)
if err != nil {
log.Log.Object(vm).Errorf("failed to generate the migrating volumes for vm: %v", err)
return err
}
if err := volumemig.ValidateVolumesUpdateMigration(vmi, vm, migVols); err != nil {
log.Log.Object(vm).Errorf("cannot migrate the VMI: %v", err)
setRestartRequired(vm, err.Error())
return nil
}
if err := volumemig.PatchVMIStatusWithMigratedVolumes(c.clientset, migVols, vmi); err != nil {
log.Log.Object(vm).Errorf("failed to update migrating volumes for vmi:%v", err)
return err
}
if _, err := volumemig.PatchVMIVolumes(c.clientset, vmi, vm); err != nil {
log.Log.Object(vm).Errorf("failed to update volumes for vmi:%v", err)
return err
}
if vm.Status.VolumeUpdateState == nil {
vm.Status.VolumeUpdateState = &virtv1.VolumeUpdateState{}
}
if len(migVols) > 0 {
vm.Status.VolumeUpdateState.VolumeMigrationState = &virtv1.VolumeMigrationState{
MigratedVolumes: migVols,
}
}
default:
return fmt.Errorf("updateVolumes strategy not recognized: %s", *vm.Spec.UpdateVolumesStrategy)
}
return nil
}
func (c *Controller) addStartRequest(vm *virtv1.VirtualMachine) error {
desiredStateChangeRequests := append(vm.Status.StateChangeRequests, virtv1.VirtualMachineStateChangeRequest{Action: virtv1.StartRequest})
patchSet := patch.New()
patchSet.AddOption(patch.WithAdd("/status/stateChangeRequests", desiredStateChangeRequests))
patchBytes, err := patchSet.GeneratePayload()
if err != nil {
return err
}
patchedVM, err := c.clientset.VirtualMachine(vm.Namespace).PatchStatus(context.Background(), vm.Name, types.JSONPatchType, patchBytes, metav1.PatchOptions{})
if err != nil {
return err
}
vm.Status = patchedVM.Status
return nil
}
func (c *Controller) syncRunStrategy(vm *virtv1.VirtualMachine, vmi *virtv1.VirtualMachineInstance, runStrategy virtv1.VirtualMachineRunStrategy) (*virtv1.VirtualMachine, common.SyncError) {
vmKey, err := controller.KeyFunc(vm)
if err != nil {
log.Log.Object(vm).Errorf(fetchingVMKeyErrFmt, err)
return vm, common.NewSyncError(err, failedCreateReason)
}
log.Log.Object(vm).V(4).Infof("VirtualMachine RunStrategy: %s", runStrategy)
switch runStrategy {
case virtv1.RunStrategyAlways:
// For this RunStrategy, a VMI should always be running. If a StateChangeRequest
// asks to stop a VMI, a new one must be immediately re-started.
if vmi != nil {
var forceRestart bool
if forceRestart = hasStopRequestForVMI(vm, vmi); forceRestart {
log.Log.Object(vm).Infof("processing forced restart request for VMI with phase %s and VM runStrategy: %s", vmi.Status.Phase, runStrategy)
}
if forceRestart || vmi.IsFinal() {
if vmi.IsDecentralizedMigration() {
if vmi.IsMigrationCompleted() {
log.Log.Object(vm).Infof("decentralized migration completed, setting runStrategy to halted")
// decentralized migration completed, mark the VM as halted. In this case the VM is now in a different
// namespace/cluster and we need to stop the VM.
vm.Spec.RunStrategy = pointer.P(virtv1.RunStrategyHalted)
// return here and let the halted runstrategy stop the VMI.
return vm, nil
}
// It is possible that the VMI has not synchronized yet with the completed migration status, but the VMI is
// marked as succeeded. This will normally trigger a restart due to the runStrategy. But we want to wait for
// the migration to complete and then mark the run strategy as halted.
log.Log.Object(vm).V(4).Infof("decentralized migration not completed, adding to queue, waiting 2 seconds")