-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsync_kvvm.go
More file actions
1308 lines (1144 loc) · 43.9 KB
/
Copy pathsync_kvvm.go
File metadata and controls
1308 lines (1144 loc) · 43.9 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
/*
Copyright 2024 Flant JSC
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 internal
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/component-base/featuregate"
virtv1 "kubevirt.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/deckhouse/virtualization-controller/pkg/common"
"github.com/deckhouse/virtualization-controller/pkg/common/annotations"
"github.com/deckhouse/virtualization-controller/pkg/common/network"
"github.com/deckhouse/virtualization-controller/pkg/common/object"
"github.com/deckhouse/virtualization-controller/pkg/common/patch"
vmutil "github.com/deckhouse/virtualization-controller/pkg/common/vm"
"github.com/deckhouse/virtualization-controller/pkg/controller/conditions"
"github.com/deckhouse/virtualization-controller/pkg/controller/kvbuilder"
"github.com/deckhouse/virtualization-controller/pkg/controller/service"
"github.com/deckhouse/virtualization-controller/pkg/controller/service/inplaceresize"
"github.com/deckhouse/virtualization-controller/pkg/controller/vm/internal/state"
"github.com/deckhouse/virtualization-controller/pkg/controller/vmchange"
"github.com/deckhouse/virtualization-controller/pkg/dvcr"
"github.com/deckhouse/virtualization-controller/pkg/eventrecord"
"github.com/deckhouse/virtualization-controller/pkg/logger"
"github.com/deckhouse/virtualization/api/core/v1alpha2"
"github.com/deckhouse/virtualization/api/core/v1alpha2/vmcondition"
)
const nameSyncKvvmHandler = "SyncKvvmHandler"
var errWaitForNetworkReady = errors.New("wait for SDN to configure network interfaces on the pod")
type syncVolumesService interface {
SyncVolumes(ctx context.Context, s state.VirtualMachineState, restartRequired bool) (reconcile.Result, error)
}
func NewSyncKvvmHandler(
dvcrSettings *dvcr.Settings,
client client.Client,
recorder eventrecord.EventRecorderLogger,
featureGate featuregate.FeatureGate,
syncVolumesService syncVolumesService,
) *SyncKvvmHandler {
return &SyncKvvmHandler{
dvcrSettings: dvcrSettings,
client: client,
recorder: recorder,
featureGate: featureGate,
syncVolumesService: syncVolumesService,
inplaceResize: inplaceresize.New(featureGate, client),
}
}
type SyncKvvmHandler struct {
client client.Client
recorder eventrecord.EventRecorderLogger
dvcrSettings *dvcr.Settings
featureGate featuregate.FeatureGate
syncVolumesService syncVolumesService
inplaceResize *inplaceresize.Service
}
func (h *SyncKvvmHandler) Handle(ctx context.Context, s state.VirtualMachineState) (reconcile.Result, error) {
log, ctx := logger.GetHandlerContext(ctx, nameSyncKvvmHandler)
if s.VirtualMachine().IsEmpty() {
return reconcile.Result{}, nil
}
current := s.VirtualMachine().Current()
changed := s.VirtualMachine().Changed()
cbConfApplied := conditions.NewConditionBuilder(vmcondition.TypeConfigurationApplied).
Generation(current.GetGeneration()).
Status(metav1.ConditionUnknown).
Reason(conditions.ReasonUnknown)
cbAwaitingRestart := conditions.NewConditionBuilder(vmcondition.TypeAwaitingRestartToApplyConfiguration).
Generation(current.GetGeneration()).
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonNoRestartRequired)
defer func() {
switch changed.Status.Phase {
case v1alpha2.MachinePending, v1alpha2.MachineStarting, v1alpha2.MachineStopped:
conditions.RemoveCondition(vmcondition.TypeConfigurationApplied, &changed.Status.Conditions)
conditions.RemoveCondition(vmcondition.TypeAwaitingRestartToApplyConfiguration, &changed.Status.Conditions)
default:
if cbConfApplied.Condition().Status == metav1.ConditionFalse {
conditions.SetCondition(cbConfApplied, &changed.Status.Conditions)
} else {
conditions.RemoveCondition(vmcondition.TypeConfigurationApplied, &changed.Status.Conditions)
}
if cbAwaitingRestart.Condition().Status == metav1.ConditionTrue {
conditions.SetCondition(cbAwaitingRestart, &changed.Status.Conditions)
} else {
conditions.RemoveCondition(vmcondition.TypeAwaitingRestartToApplyConfiguration, &changed.Status.Conditions)
}
}
}()
if isDeletion(current) {
return reconcile.Result{}, nil
}
kvvm, err := s.KVVM(ctx)
if err != nil {
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message(service.CapitalizeFirstLetter(err.Error()) + ".")
return reconcile.Result{}, err
}
class, err := s.Class(ctx)
if err != nil {
return reconcile.Result{}, err
}
// 1. Set RestartAwaitingChanges.
var (
lastAppliedSpec *v1alpha2.VirtualMachineSpec
changes vmchange.SpecChanges
allChanges vmchange.SpecChanges
classChanged bool
)
if kvvm != nil {
lastAppliedSpec = h.loadLastAppliedSpec(current, kvvm)
lastClassAppliedSpec := h.loadClassLastAppliedSpec(class, kvvm)
changes = h.detectSpecChanges(ctx, kvvm, ¤t.Spec, lastAppliedSpec)
if !changes.IsEmpty() {
kvvmi, kvvmiErr := s.KVVMI(ctx)
if kvvmiErr == nil {
nonHotpluggableVolumes := nonHotpluggableVolumeRefs(kvvmi)
changes.UpgradeBlockDeviceChangesToRestartIf(func(change vmchange.FieldChange) bool {
return blockDeviceChangeTouchesRefs(change, nonHotpluggableVolumes)
})
}
// Require restart for CPU and memory changes if VM is non migratable.
if h.isVMNonMigratable(current) {
changes.UpgradeHotplugComputeChangesToRestart()
} else {
quotaMessage, insufficientQuota, quotaErr := h.hasInsufficientHotplugMigrationQuota(ctx, current, changes)
if quotaErr != nil {
err = fmt.Errorf("failed to check project quota for hotplug migration: %w", quotaErr)
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message(service.CapitalizeFirstLetter(err.Error()) + ".")
return reconcile.Result{}, err
}
if insufficientQuota {
changes.UpgradeHotplugComputeChangesToRestartWithMessage(quotaMessage)
}
}
allChanges.Add(changes.GetAll()...)
}
if class != nil {
classChanges := h.detectClassSpecChanges(ctx, &class.Spec, lastClassAppliedSpec)
if !classChanges.IsEmpty() {
allChanges.Add(classChanges.GetAll()...)
classChanged = classChanges.IsDisruptive()
}
}
}
if kvvm == nil || changes.IsEmpty() {
changed.Status.RestartAwaitingChanges = nil
} else {
changed.Status.RestartAwaitingChanges, err = changes.ConvertPendingRestartChanges()
if err != nil {
err = fmt.Errorf("failed to generate pending configuration changes: %w", err)
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message(service.CapitalizeFirstLetter(err.Error()) + ".")
return reconcile.Result{}, err
}
if len(changed.Status.RestartAwaitingChanges) == 0 {
changed.Status.RestartAwaitingChanges = nil
}
}
// 2. Wait if dependent resources are not ready yet.
if h.isWaiting(changed) {
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message(
"Waiting for the dependent resources. Be careful restarting the virtual machine: " +
"the virtual machine cannot be restarted immediately to apply pending configuration changes " +
"as it is awaiting the availability of dependent resources.",
)
return reconcile.Result{RequeueAfter: time.Minute}, nil
}
var errs error
// 3. Create or update KVVM.
synced, kvvmSyncErr := h.syncKVVM(ctx, s, allChanges)
waitForNetwork := errors.Is(kvvmSyncErr, errWaitForNetworkReady)
if kvvmSyncErr != nil && !waitForNetwork {
errs = errors.Join(errs, fmt.Errorf("failed to sync the internal virtual machine: %w", kvvmSyncErr))
}
if synced {
// 3.1. Changes are applied, consider current spec as last applied.
changed.Status.RestartAwaitingChanges = nil
}
kvvmi, err := s.KVVMI(ctx)
if err != nil {
return reconcile.Result{}, err
}
inplaceResizeInProgress := kvvmi != nil && h.inplaceResize.InProgress(kvvmi)
// 4. Set ConfigurationApplied condition.
switch {
case waitForNetwork:
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message("Waiting for SDN to configure network interfaces.")
case kvvmSyncErr != nil:
h.recorder.Event(current, corev1.EventTypeWarning, v1alpha2.ReasonErrVmNotSynced, kvvmSyncErr.Error())
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message(service.CapitalizeFirstLetter(kvvmSyncErr.Error()) + ".")
case len(changed.Status.RestartAwaitingChanges) > 0:
h.recorder.Event(current, corev1.EventTypeNormal, v1alpha2.ReasonErrRestartAwaitingChanges, "The virtual machine configuration successfully synced")
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message("Waiting for the user to restart in order to apply the configuration changes.")
restartMessages := changes.GetRestartMessages()
additionalMessage := ""
if len(restartMessages) > 0 {
additionalMessage = strings.Join(restartMessages, " ")
}
cbAwaitingRestart.
Status(metav1.ConditionTrue).
Reason(vmcondition.ReasonChangesPendingRestart).
Message("Waiting for the user to restart in order to apply the configuration changes. " + additionalMessage)
case classChanged:
h.recorder.Event(current, corev1.EventTypeNormal, v1alpha2.ReasonErrRestartAwaitingChanges, "Restart required to propagate changes from the vmclass spec")
cbConfApplied.
Status(metav1.ConditionFalse).
Reason(vmcondition.ReasonConfigurationNotApplied).
Message("VirtualMachineClass.spec has been modified. Waiting for the user to restart in order to apply the configuration changes.")
cbAwaitingRestart.
Status(metav1.ConditionTrue).
Reason(vmcondition.ReasonChangesPendingRestart).
Message("VirtualMachineClass.spec has been modified. Waiting for the user to restart in order to apply the configuration changes.")
case inplaceResizeInProgress:
msg := h.buildInProgressInplaceResizeMsg(kvvmi)
h.recorder.Event(current, corev1.EventTypeNormal, h.resizingEventReason(kvvmi), msg)
cbConfApplied.Status(metav1.ConditionFalse).Reason(vmcondition.ReasonConfigurationNotApplied).Message(msg)
case synced:
h.recorder.Event(current, corev1.EventTypeNormal, v1alpha2.ReasonErrVmSynced, "The virtual machine configuration successfully synced")
cbConfApplied.Status(metav1.ConditionTrue).Reason(vmcondition.ReasonConfigurationApplied)
default:
log.Error("Unexpected case during kvvm sync, please report a bug")
}
// 5. Set RestartRequired from KVVM condition.
if cbAwaitingRestart.Condition().Status == metav1.ConditionFalse && kvvm != nil {
// The check for StateChangeRequests is added to ignore the RestartRequired condition when it is set while
// the virtual machine is in the process of rebooting.
cond, _ := conditions.GetKVVMCondition(virtv1.VirtualMachineRestartRequired, kvvm.Status.Conditions)
if cond.Status == corev1.ConditionTrue && len(kvvm.Status.StateChangeRequests) == 0 {
msg := "Please restart the virtual machine to synchronize its configuration."
log.Error(msg)
cbAwaitingRestart.
Status(metav1.ConditionTrue).
Reason(vmcondition.ReasonUnexpectedState).
Message(msg)
}
}
// 6. Sync migrating volumes if needed.
result, migrateVolumesErr := h.syncVolumesService.SyncVolumes(ctx, s, cbAwaitingRestart.Condition().Status == metav1.ConditionTrue)
if migrateVolumesErr != nil {
errs = errors.Join(errs, fmt.Errorf("failed to sync migrating volumes: %w", migrateVolumesErr))
}
if waitForNetwork && result.RequeueAfter == 0 {
result.RequeueAfter = 5 * time.Second
}
return result, errs
}
func (h *SyncKvvmHandler) Name() string {
return nameSyncKvvmHandler
}
func (h *SyncKvvmHandler) isWaiting(vm *v1alpha2.VirtualMachine) bool {
return !virtualMachineDependenciesAreReady(vm)
}
func (h *SyncKvvmHandler) syncKVVM(ctx context.Context, s state.VirtualMachineState, allChanges vmchange.SpecChanges) (bool, error) {
if s.VirtualMachine().IsEmpty() {
return false, fmt.Errorf("the virtual machine is empty, please report a bug")
}
kvvm, err := s.KVVM(ctx)
if err != nil {
return false, fmt.Errorf("find the internal virtual machine: %w", err)
}
if kvvm == nil {
err = h.createKVVM(ctx, s)
if err != nil {
return false, fmt.Errorf("create the internal virtual machine: %w", err)
}
return true, nil
}
kvvmi, err := s.KVVMI(ctx)
if err != nil {
return false, fmt.Errorf("find the internal virtual machine instance: %w", err)
}
pod, err := s.Pod(ctx)
if err != nil {
return false, fmt.Errorf("find the virtual machine pod: %w", err)
}
switch {
// This workaround is required due to a bug in the KVVM workflow.
// When a KVVM is created with conflicting placement rules and cannot be scheduled,
// it remains unschedulable even if these rules are changed or removed.
case h.isVMUnschedulable(s.VirtualMachine().Current(), kvvm) && h.isPlacementPolicyChanged(allChanges):
err := h.updateKVVM(ctx, s)
if err != nil {
return false, fmt.Errorf("failed to update internal virtual machine: %w", err)
}
err = object.DeleteObject(ctx, h.client, pod)
if err != nil {
return false, fmt.Errorf("failed to delete the internal virtual machine instance's pod: %w", err)
}
return true, nil
case h.isVMStopped(s.VirtualMachine().Current(), kvvm, pod):
// KVVM should be updated when VM become stopped.
// It is safe to update KVVM at this point in general and also all related resources
// can be changed during the restoration process: e.g. VirtualDisks, VMIPs, etc.
// For example, the PVC of the VirtualDisk will be changed,
// and the volume with this PVC must be updated in the KVVM specification.
err := h.updateKVVM(ctx, s)
if err != nil {
return false, fmt.Errorf("update internal virtual machine in 'Stopped' state: %w", err)
}
return true, nil
case h.hasNoneDisruptiveChanges(s.VirtualMachine().Current(), kvvm, kvvmi, allChanges):
// No need to wait, apply changes to KVVM immediately.
err = h.applyVMChangesToKVVM(ctx, s, allChanges)
if err != nil {
return false, fmt.Errorf("apply changes to the internal virtual machine: %w", err)
}
return true, nil
case allChanges.IsEmpty():
outOfSync, err := h.networksOutOfSync(ctx, s, kvvm)
if err != nil {
return false, fmt.Errorf("check network sync: %w", err)
}
if outOfSync {
if err := h.applyNetworkReadinessSync(ctx, s); err != nil {
return false, fmt.Errorf("apply network readiness sync: %w", err)
}
}
return true, nil
default:
// Delay changes propagation to KVVM until user restarts VM.
return false, nil
}
}
// createKVVM constructs and creates new KubeVirt VirtualMachine based on d8 VirtualMachine spec.
func (h *SyncKvvmHandler) createKVVM(ctx context.Context, s state.VirtualMachineState) error {
log := logger.FromContext(ctx)
if s.VirtualMachine().IsEmpty() {
return fmt.Errorf("the virtual machine is empty, please report a bug")
}
kvvm, err := MakeKVVMFromVMSpec(ctx, s)
if err != nil {
return fmt.Errorf("failed to make the internal virtual machine: %w", err)
}
err = h.client.Create(ctx, kvvm)
if err != nil {
if k8serrors.IsAlreadyExists(err) {
log.Warn("The KubeVirt VM already exists", "name", kvvm.Name)
return nil
}
return fmt.Errorf("failed to create the internal virtual machine: %w", err)
}
log.Info("Created new KubeVirt VM", "name", kvvm.Name)
log.Debug("Created new KubeVirt VM", "name", kvvm.Name, "kvvm", kvvm)
return nil
}
// updateKVVM constructs and creates new KubeVirt VirtualMachine based on d8 VirtualMachine spec.
func (h *SyncKvvmHandler) updateKVVM(ctx context.Context, s state.VirtualMachineState) error {
log := logger.FromContext(ctx)
if s.VirtualMachine().IsEmpty() {
return fmt.Errorf("the virtual machine is empty, please report a bug")
}
newKVVM, err := MakeKVVMFromVMSpec(ctx, s)
if err != nil {
return fmt.Errorf("update internal virtual machine: make kvvm from the virtual machine spec: %w", err)
}
currentKVVM, err := s.KVVM(ctx)
if err != nil {
return fmt.Errorf("get current kvvm: %w", err)
}
// Check for changes to skip unneeded updated.
isChanged := IsKVVMChanged(currentKVVM, newKVVM)
if isChanged {
// Update can't handle proper reset of memory fields, so patch-after-update:
// (1) make memory copy, (2) reset memory in newKVVM and (3) patch memory field after update.
domainMemory := saveKVVMDomainMemoryForPatching(currentKVVM, newKVVM)
if domainMemory != nil {
newKVVM.Spec.Template.Spec.Domain.Memory = currentKVVM.Spec.Template.Spec.Domain.Memory
}
if err = h.client.Update(ctx, newKVVM); err != nil {
return fmt.Errorf("update internal virtual machine: %w", err)
}
log.Info("Update internal virtual machine done", "name", newKVVM.Name)
log.Debug("Update internal virtual machine done", "name", newKVVM.Name, "kvvm", newKVVM)
if domainMemory != nil {
jsonPatch := patch.JSONPatch{}
// Removing memory.maxGuest is not enough, replace memory.guest is needed to pass the vm-validator webhook.
jsonPatch.Append(
patch.WithRemove("/spec/template/spec/domain/memory/maxGuest"),
patch.WithReplace("/spec/template/spec/domain/memory/guest", domainMemory.Guest.String()),
)
patchBytes, err := jsonPatch.Bytes()
if err != nil {
return fmt.Errorf("prepare json patch for internal virtual machine: %w", err)
}
if err = h.client.Patch(ctx, newKVVM, client.RawPatch(types.JSONPatchType, patchBytes)); err != nil {
return fmt.Errorf("patch internal virtual machine before update: %w", err)
}
}
} else {
log.Debug("Update internal virtual machine is not needed", "name", newKVVM.Name, "kvvm", newKVVM)
}
return nil
}
// saveKVVMDomainMemoryForPatching returns copy of domain memory if maxGuest becomes 0.
//
// Note: maxGuest=0 is an invalid value for the vm-validator webhook,
// kvbuilder sets maxGuest to 0 to indicate that KVVM needs to be patched
// to clear maxGuest value: it is not possible to clear the value with the Update
// once it was set previously.
func saveKVVMDomainMemoryForPatching(prevKVVM, newKVVM *virtv1.VirtualMachine) *virtv1.Memory {
prevMemory := prevKVVM.Spec.Template.Spec.Domain.Memory
newMemory := newKVVM.Spec.Template.Spec.Domain.Memory
if newMemory != nil && newMemory.MaxGuest != nil && newMemory.MaxGuest.IsZero() &&
prevMemory != nil && prevMemory.MaxGuest != nil && !prevMemory.MaxGuest.IsZero() {
return newMemory.DeepCopy()
}
return nil
}
func MakeKVVMFromVMSpec(ctx context.Context, s state.VirtualMachineState) (*virtv1.VirtualMachine, error) {
if s.VirtualMachine().IsEmpty() {
return nil, nil
}
current := s.VirtualMachine().Current()
kvvmName := object.NamespacedName(current)
kvvmOpts := kvbuilder.DefaultOptions(current)
kvvm, err := s.KVVM(ctx)
if err != nil {
return nil, err
}
var kvvmBuilder *kvbuilder.KVVM
if kvvm == nil {
kvvmBuilder = kvbuilder.NewEmptyKVVM(kvvmName, kvvmOpts)
} else {
kvvmBuilder = kvbuilder.NewKVVM(kvvm.DeepCopy(), kvvmOpts)
}
bdState := NewBlockDeviceState(s)
err = bdState.Reload(ctx)
if err != nil {
return nil, fmt.Errorf("failed to reload blockdevice state for the virtual machine: %w", err)
}
class, err := s.Class(ctx)
if err != nil {
return nil, err
}
ip, err := s.IPAddress(ctx)
if err != nil {
return nil, err
}
ipAddress := ""
if ip != nil {
if ip.Status.Address == "" {
return nil, fmt.Errorf("the IP address is not found for the virtual machine")
} else {
ipAddress = ip.Status.Address
}
}
vmmacs, err := s.VirtualMachineMACAddresses(ctx)
if err != nil {
return nil, err
}
filteredVM, err := filterReadyNetworks(ctx, s.Client(), current)
if err != nil {
return nil, err
}
networkSpec := network.CreateNetworkSpec(filteredVM, vmmacs)
kvvmi, err := s.KVVMI(ctx)
if err != nil {
return nil, err
}
// Create kubevirt VirtualMachine resource from d8 VirtualMachine spec.
err = kvbuilder.ApplyVirtualMachineSpec(
kvvmBuilder,
current,
bdState.VDByName,
bdState.VIByName,
bdState.CVIByName,
bdState.VMBDAByBlockDeviceRef,
class,
ipAddress,
networkSpec,
kvvmi != nil && kvvmi.Status.Phase == virtv1.Running,
)
if err != nil {
return nil, err
}
pvTerms, err := s.PVNodeAffinityTerms(ctx)
if err != nil {
return nil, fmt.Errorf("failed to collect PV node affinities: %w", err)
}
kvvmBuilder.ApplyPVNodeAffinity(pvTerms)
newKVVM := kvvmBuilder.GetResource()
err = kvbuilder.SetLastAppliedSpec(newKVVM, current)
if err != nil {
return nil, fmt.Errorf("set vm last applied spec on the internal virtual machine: %w", err)
}
err = kvbuilder.SetLastAppliedClassSpec(newKVVM, class)
if err != nil {
return nil, fmt.Errorf("set vmclass last applied spec on the internal virtual machine: %w", err)
}
return newKVVM, nil
}
// IsKVVMChanged returns whether kvvm spec or special annotations are changed.
func IsKVVMChanged(prevKVVM, newKVVM *virtv1.VirtualMachine) bool {
prevKVVMLastAppliedSpecAnnotations, ok := prevKVVM.Annotations[annotations.AnnVMLastAppliedSpec]
if !ok {
prevKVVMLastAppliedSpecAnnotations = prevKVVM.Annotations[annotations.AnnVMLastAppliedSpecLegacy]
}
newKVVMLastAppliedSpecAnnotations, ok := newKVVM.Annotations[annotations.AnnVMLastAppliedSpec]
if !ok {
newKVVMLastAppliedSpecAnnotations = newKVVM.Annotations[annotations.AnnVMLastAppliedSpecLegacy]
}
if prevKVVMLastAppliedSpecAnnotations != newKVVMLastAppliedSpecAnnotations {
return true
}
prevKVVMClassLastAppliedSpecAnnotations, ok := prevKVVM.Annotations[annotations.AnnVMClassLastAppliedSpec]
if !ok {
prevKVVMClassLastAppliedSpecAnnotations = prevKVVM.Annotations[annotations.AnnVMClassLastAppliedSpecLegacy]
}
newKVVMClassLastAppliedSpecAnnotations, ok := newKVVM.Annotations[annotations.AnnVMClassLastAppliedSpec]
if !ok {
newKVVMClassLastAppliedSpecAnnotations = newKVVM.Annotations[annotations.AnnVMClassLastAppliedSpecLegacy]
}
if prevKVVMClassLastAppliedSpecAnnotations != newKVVMClassLastAppliedSpecAnnotations {
return true
}
return !reflect.DeepEqual(prevKVVM.Spec, newKVVM.Spec)
}
func (h *SyncKvvmHandler) loadLastAppliedSpec(vm *v1alpha2.VirtualMachine, kvvm *virtv1.VirtualMachine) *v1alpha2.VirtualMachineSpec {
if kvvm == nil || vm == nil {
return nil
}
lastSpec, err := kvbuilder.LoadLastAppliedSpec(kvvm)
// TODO Add smarter handler for empty/invalid annotation.
if lastSpec == nil && err == nil {
h.recorder.Event(vm, corev1.EventTypeWarning, v1alpha2.ReasonVMLastAppliedSpecIsInvalid, "Could not find last applied spec. Possible old VM or partial backup restore. Restart or recreate VM to adopt it.")
lastSpec = &v1alpha2.VirtualMachineSpec{}
}
if err != nil {
msg := fmt.Sprintf("Could not restore last applied spec: %v. Possible old VM or partial backup restore. Restart or recreate VM to adopt it.", err)
h.recorder.Event(vm, corev1.EventTypeWarning, v1alpha2.ReasonVMLastAppliedSpecIsInvalid, msg)
// In Automatic mode changes are applied immediately, so last-applied-spec annotation will be restored.
if vmutil.ApprovalMode(vm) == v1alpha2.Automatic {
lastSpec = &v1alpha2.VirtualMachineSpec{}
}
if vmutil.ApprovalMode(vm) == v1alpha2.Manual {
// Manual mode requires meaningful content in status.pendingChanges.
// There are different paths:
// 1. Return err and do nothing, user should restore annotation or recreate VM.
// 2. Use empty VirtualMachineSpec and show full replace in status.pendingChanges.
// This may lead to unexpected restart.
// 3. Restore some fields from KVVM spec to prevent unexpected restarts and reduce
// content in status.pendingChanges.
//
// At this time, variant 2 is chosen.
// TODO(future): Implement variant 3: restore some fields from KVVM.
lastSpec = &v1alpha2.VirtualMachineSpec{}
}
}
return lastSpec
}
func (h *SyncKvvmHandler) loadClassLastAppliedSpec(class *v1alpha2.VirtualMachineClass, kvvm *virtv1.VirtualMachine) *v1alpha2.VirtualMachineClassSpec {
if kvvm == nil || class == nil {
return nil
}
lastSpec, err := kvbuilder.LoadLastAppliedClassSpec(kvvm)
// TODO Add smarter handler for empty/invalid annotation.
if lastSpec == nil && err == nil {
h.recorder.Event(class, corev1.EventTypeWarning, v1alpha2.ReasonVMClassLastAppliedSpecInvalid, "Could not find last applied spec. Possible old VMClass or partial backup restore. Restart or recreate VM to adopt it.")
lastSpec = &v1alpha2.VirtualMachineClassSpec{}
}
if err != nil {
msg := fmt.Sprintf("Could not restore last applied spec: %v. Possible old VMClass or partial backup restore. Restart or recreate VM to adopt it.", err)
h.recorder.Event(class, corev1.EventTypeWarning, v1alpha2.ReasonVMClassLastAppliedSpecInvalid, msg)
lastSpec = &v1alpha2.VirtualMachineClassSpec{}
}
return lastSpec
}
// detectSpecChanges compares KVVM generated from current VM spec with in cluster KVVM
// to calculate changes and action needed to apply these changes.
func (h *SyncKvvmHandler) detectSpecChanges(
ctx context.Context,
kvvm *virtv1.VirtualMachine,
currentSpec, lastSpec *v1alpha2.VirtualMachineSpec,
) vmchange.SpecChanges {
log := logger.FromContext(ctx)
// Not applicable if KVVM is absent.
if kvvm == nil || lastSpec == nil {
return vmchange.SpecChanges{}
}
// Compare VM spec applied to the underlying KVVM
// with the current VM spec (maybe edited by the user).
specChanges := vmchange.NewVMSpecComparator(h.featureGate).Compare(lastSpec, currentSpec)
log.Info(fmt.Sprintf("detected VM changes: empty %v, disruptive %v, actionType %v", specChanges.IsEmpty(), specChanges.IsDisruptive(), specChanges.ActionType()))
log.Info(fmt.Sprintf("detected VM changes JSON: %s", specChanges.ToJSON()))
return specChanges
}
func (h *SyncKvvmHandler) detectClassSpecChanges(ctx context.Context, currentClassSpec, lastClassSpec *v1alpha2.VirtualMachineClassSpec) vmchange.SpecChanges {
log := logger.FromContext(ctx)
specChanges := vmchange.CompareClassSpecs(currentClassSpec, lastClassSpec)
log.Info(fmt.Sprintf("detected VMClass changes: empty %v, disruptive %v, actionType %v", specChanges.IsEmpty(), specChanges.IsDisruptive(), specChanges.ActionType()))
log.Info(fmt.Sprintf("detected VMClass changes JSON: %s", specChanges.ToJSON()))
return specChanges
}
// IsVmStopped return true if the instance of the KVVM is not created or Pod is in the Complete state.
func (h *SyncKvvmHandler) isVMStopped(
vm *v1alpha2.VirtualMachine,
kvvm *virtv1.VirtualMachine,
pod *corev1.Pod,
) bool {
if vm == nil {
return false
}
podStopped := true
if pod != nil {
phase := pod.Status.Phase
podStopped = phase != corev1.PodPending && phase != corev1.PodRunning
}
return isVMStopped(kvvm) && (!isKVVMICreated(kvvm) || podStopped)
}
// canApplyChanges returns true if changes can be applied right now.
//
// Wait if changes are disruptive, and approval mode is manual, and VM is still running.
func (h *SyncKvvmHandler) hasNoneDisruptiveChanges(
vm *v1alpha2.VirtualMachine,
kvvm *virtv1.VirtualMachine,
kvvmi *virtv1.VirtualMachineInstance,
changes vmchange.SpecChanges,
) bool {
if vm == nil || changes.IsEmpty() {
return false
}
if !changes.IsDisruptive() || kvvmi == nil {
return true
}
if isVMPending(kvvm) {
return true
}
return false
}
// applyVMChangesToKVVM applies updates to underlying KVVM based on actions type.
func (h *SyncKvvmHandler) applyVMChangesToKVVM(ctx context.Context, s state.VirtualMachineState, changes vmchange.SpecChanges) error {
log := logger.FromContext(ctx)
if changes.IsEmpty() || s.VirtualMachine().IsEmpty() {
return nil
}
current := s.VirtualMachine().Current()
action := changes.ActionType()
kvvmi, err := s.KVVMI(ctx)
if err != nil {
return err
}
if kvvmi == nil && action == vmchange.ActionRestart {
action = vmchange.ActionApplyImmediate
}
kvvm, err := s.KVVM(ctx)
if err != nil {
return err
}
switch action {
case vmchange.ActionRestart:
// Update KVVM spec according the current VM spec.
if err = h.updateKVVM(ctx, s); err != nil {
return fmt.Errorf("update virtual machine instance with new spec: %w", err)
}
case vmchange.ActionApplyImmediate:
message := "Apply changes without restart"
if changes.IsDisruptive() {
message = "Apply disruptive changes without restart"
}
h.recorder.Event(current, corev1.EventTypeNormal, v1alpha2.ReasonVMChangesApplied, message)
log.Debug(message, "vm.name", current.GetName(), "changes", changes)
if hasNetworkChange(changes) {
desired, err := h.patchPodNetworkAnnotation(ctx, s)
if err != nil {
return fmt.Errorf("unable to patch pod network annotation: %w", err)
}
ready, err := h.isNetworkReadyOnPod(ctx, s, desired)
if err != nil {
return fmt.Errorf("unable to check pod network status: %w", err)
}
if !ready {
msg := "Waiting for SDN to configure network interfaces"
log.Info(msg)
h.recorder.Event(current, corev1.EventTypeNormal, v1alpha2.ReasonVMChangesApplied, msg)
return errWaitForNetworkReady
}
}
if err := h.updateKVVM(ctx, s); err != nil {
return fmt.Errorf("unable to update KVVM using new VM spec: %w", err)
}
case vmchange.ActionNone:
log.Info("No changes to underlying KVVM, update last-applied-spec annotation", "vm.name", current.GetName())
class, err := s.Class(ctx)
if err != nil {
return fmt.Errorf("failed to get vmclass: %w", err)
}
if err = h.updateKVVMLastAppliedSpec(ctx, current, kvvm, class); err != nil {
return fmt.Errorf("unable to update last-applied-spec on KVVM: %w", err)
}
}
return nil
}
// updateKVVMLastAppliedSpec updates last-applied-spec annotation on KubeVirt VirtualMachine.
func (h *SyncKvvmHandler) updateKVVMLastAppliedSpec(
ctx context.Context,
vm *v1alpha2.VirtualMachine,
kvvm *virtv1.VirtualMachine,
class *v1alpha2.VirtualMachineClass,
) error {
if vm == nil || kvvm == nil {
return nil
}
err := kvbuilder.SetLastAppliedSpec(kvvm, vm)
if err != nil {
return fmt.Errorf("set vm last applied spec on KubeVirt VM '%s': %w", kvvm.GetName(), err)
}
err = kvbuilder.SetLastAppliedClassSpec(kvvm, class)
if err != nil {
return fmt.Errorf("set vmclass last applied spec on KubeVirt VM '%s': %w", kvvm.GetName(), err)
}
if err := h.client.Update(ctx, kvvm); err != nil {
return fmt.Errorf("unable to update KubeVirt VM '%s': %w", kvvm.GetName(), err)
}
log := logger.FromContext(ctx)
log.Info("Update last applied spec on KubeVirt VM done", "name", kvvm.GetName())
return nil
}
func (h *SyncKvvmHandler) isVMUnschedulable(
vm *v1alpha2.VirtualMachine,
kvvm *virtv1.VirtualMachine,
) bool {
if vm.Status.Phase == v1alpha2.MachinePending && kvvm.Status.PrintableStatus == virtv1.VirtualMachineStatusUnschedulable {
return true
}
return false
}
func (h *SyncKvvmHandler) isVMNonMigratable(
vm *v1alpha2.VirtualMachine,
) bool {
vmMigratable, has := conditions.GetCondition(vmcondition.TypeMigratable, vm.Status.Conditions)
return has && vmMigratable.Status == metav1.ConditionFalse
}
func (h *SyncKvvmHandler) hasInsufficientHotplugMigrationQuota(ctx context.Context, vm *v1alpha2.VirtualMachine, changes vmchange.SpecChanges) (string, bool, error) {
if !hasHotplugComputeApplyImmediateChange(changes) {
return "", false, nil
}
newCPU, newMemory, err := hotplugMigrationRequests(vm)
if err != nil {
return "", false, err
}
var quotaList corev1.ResourceQuotaList
if err = h.client.List(ctx, "aList, client.InNamespace(vm.GetNamespace())); err != nil {
return "", false, fmt.Errorf("list project quotas: %w", err)
}
var messages []string
requests := []struct {
name corev1.ResourceName
req resource.Quantity
}{
{name: corev1.ResourceRequestsCPU, req: newCPU},
{name: corev1.ResourceRequestsMemory, req: newMemory},
}
for i := range quotaList.Items {
quota := "aList.Items[i]
for _, request := range requests {
if message, allowed := quotaAllowsHotplugMigration(quota, request.name, request.req); !allowed {
messages = append(messages, message)
}
}
}
if len(messages) > 0 {
return strings.Join(messages, " "), true, nil
}
return "", false, nil
}
func hasHotplugComputeApplyImmediateChange(changes vmchange.SpecChanges) bool {
for _, change := range changes.GetAll() {
isCPUChange := change.Path == "cpu" || strings.HasPrefix(change.Path, "cpu.")
isMemoryChange := change.Path == "memory" || strings.HasPrefix(change.Path, "memory.")
if (isCPUChange || isMemoryChange) && change.ActionRequired == vmchange.ActionApplyImmediate {
return true
}
}
return false
}
func hotplugMigrationRequests(vm *v1alpha2.VirtualMachine) (newCPU, newMemory resource.Quantity, err error) {
newCPUReq, err := kvbuilder.GetCPURequest(vm.Spec.CPU.Cores, vm.Spec.CPU.CoreFraction)
if err != nil {
return resource.Quantity{}, resource.Quantity{}, fmt.Errorf("calculate new CPU request: %w", err)
}
return *newCPUReq, vm.Spec.Memory.Size, nil
}
func quotaAllowsHotplugMigration(quota *corev1.ResourceQuota, resourceName corev1.ResourceName, newReq resource.Quantity) (string, bool) {
hard, hasHard := quota.Status.Hard[resourceName]
if !hasHard {
hard, hasHard = quota.Spec.Hard[resourceName]
}
if !hasHard {
return "", true
}
if newReq.Cmp(hard) == common.CmpGreater {
return hotplugMigrationQuotaMessage(quota, resourceName, newReq, resource.Quantity{}, hard), false
}
used := quota.Status.Used[resourceName]
duringMigration := used.DeepCopy()
duringMigration.Add(newReq)
if duringMigration.Cmp(hard) == common.CmpGreater {
available := hard.DeepCopy()
available.Sub(used)
if available.Sign() < 0 {
available.Set(0)
}
return hotplugMigrationQuotaMessage(quota, resourceName, newReq, available, hard), false
}
return "", true
}
func hotplugMigrationQuotaMessage(quota *corev1.ResourceQuota, resourceName corev1.ResourceName, newReq, available, hard resource.Quantity) string {
if newReq.Cmp(hard) == common.CmpGreater {
return fmt.Sprintf(
"Hotplug migration cannot start because %s request %s exceeds project quota %q hard limit %s. Restart the virtual machine to apply the changes without live migration.",
resourceName,
newReq.String(),
quota.GetName(),
hard.String(),
)
}
return fmt.Sprintf(
"Hotplug migration cannot start because project quota %q has insufficient %s: required additional %s, available %s. Restart the virtual machine to apply the changes without live migration.",
quota.GetName(),
resourceName,
newReq.String(),
available.String(),
)
}
func (h *SyncKvvmHandler) networksOutOfSync(ctx context.Context, s state.VirtualMachineState, kvvm *virtv1.VirtualMachine) (bool, error) {
if kvvm == nil {