-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathvmprovider_vm.go
More file actions
3114 lines (2599 loc) · 87 KB
/
vmprovider_vm.go
File metadata and controls
3114 lines (2599 loc) · 87 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
// © Broadcom. All Rights Reserved.
// The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package vsphere
import (
"context"
"errors"
"fmt"
"maps"
"math/rand"
"path"
"strings"
"sync"
"text/template"
"time"
"github.com/go-logr/logr"
"github.com/vmware/govmomi/fault"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/pbm"
pbmtypes "github.com/vmware/govmomi/pbm/types"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vapi/tags"
"github.com/vmware/govmomi/vim25/mo"
vimtypes "github.com/vmware/govmomi/vim25/types"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apierrorsutil "k8s.io/apimachinery/pkg/util/errors"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
imgregv1a1 "github.com/vmware-tanzu/image-registry-operator-api/api/v1alpha1"
imgregv1 "github.com/vmware-tanzu/image-registry-operator-api/api/v1alpha2"
vmopv1 "github.com/vmware-tanzu/vm-operator/api/v1alpha6"
"github.com/vmware-tanzu/vm-operator/api/v1alpha6/common"
pkgcnd "github.com/vmware-tanzu/vm-operator/pkg/conditions"
pkgcfg "github.com/vmware-tanzu/vm-operator/pkg/config"
pkgconst "github.com/vmware-tanzu/vm-operator/pkg/constants"
pkgctx "github.com/vmware-tanzu/vm-operator/pkg/context"
ctxop "github.com/vmware-tanzu/vm-operator/pkg/context/operation"
pkgerr "github.com/vmware-tanzu/vm-operator/pkg/errors"
pkglog "github.com/vmware-tanzu/vm-operator/pkg/log"
"github.com/vmware-tanzu/vm-operator/pkg/providers"
vcclient "github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/client"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/clustermodules"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/constants"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/network"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/placement"
res "github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/resources"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/session"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/storage"
upgradevm "github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/upgrade/virtualmachine"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/vcenter"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/virtualmachine"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/vmlifecycle"
"github.com/vmware-tanzu/vm-operator/pkg/topology"
pkgutil "github.com/vmware-tanzu/vm-operator/pkg/util"
kubeutil "github.com/vmware-tanzu/vm-operator/pkg/util/kube"
"github.com/vmware-tanzu/vm-operator/pkg/util/kube/cource"
"github.com/vmware-tanzu/vm-operator/pkg/util/paused"
"github.com/vmware-tanzu/vm-operator/pkg/util/ptr"
vmopv1util "github.com/vmware-tanzu/vm-operator/pkg/util/vmopv1"
pkgvol "github.com/vmware-tanzu/vm-operator/pkg/util/volumes"
vmutil "github.com/vmware-tanzu/vm-operator/pkg/util/vsphere/vm"
vmconfbootoptions "github.com/vmware-tanzu/vm-operator/pkg/vmconfig/bootoptions"
vmconfcrypto "github.com/vmware-tanzu/vm-operator/pkg/vmconfig/crypto"
vmconfdiskpromo "github.com/vmware-tanzu/vm-operator/pkg/vmconfig/diskpromo"
vmconfpolicy "github.com/vmware-tanzu/vm-operator/pkg/vmconfig/policy"
vmconfunmanagedvolsreg "github.com/vmware-tanzu/vm-operator/pkg/vmconfig/volumes/unmanaged/register"
)
var (
ErrSetPowerState = res.ErrSetPowerState
ErrUpgradeSchema = upgradevm.ErrUpgradeSchema
ErrUpgradeObject = upgradevm.ErrUpgradeObject
ErrBackup = virtualmachine.ErrBackingUp
ErrBootstrapReconfigure = vmlifecycle.ErrBootstrapReconfigure
ErrBootstrapCustomize = vmlifecycle.ErrBootstrapCustomize
ErrReconfigure = session.ErrReconfigure
ErrRestart = pkgerr.NoRequeueNoErr("restarted vm")
ErrUpgradeHardwareVersion = session.ErrUpgradeHardwareVersion
ErrIsPaused = pkgerr.NoRequeueNoErr("is paused")
ErrHasTask = pkgerr.NoRequeueNoErr("has outstanding task")
ErrPromoteDisks = vmconfdiskpromo.ErrPromoteDisks
ErrCreate = pkgerr.NoRequeueNoErr("created vm")
ErrUpdate = pkgerr.NoRequeueNoErr("updated vm")
ErrSnapshotRevert = pkgerr.NoRequeueNoErr("reverted snapshot")
ErrPolicyNotReady = vmconfpolicy.ErrPolicyNotReady
ErrRegisterVolumes = vmconfunmanagedvolsreg.ErrPendingRegister
ErrAddedInstanceStorageVols = pkgerr.NoRequeueNoErr("added instance storage volumes")
)
// VMCreateArgs contains the arguments needed to create a VM on VC.
type VMCreateArgs struct {
vmlifecycle.CreateArgs
vmlifecycle.BootstrapData
VMClass vmopv1.VirtualMachineClass
ResourcePolicy *vmopv1.VirtualMachineSetResourcePolicy
ImageObj ctrlclient.Object
ImageSpec vmopv1.VirtualMachineImageSpec
ImageStatus vmopv1.VirtualMachineImageStatus
Storage storage.VMStorageData
HasInstanceStorage bool
ChildResourcePoolName string
ChildFolderName string
ClusterMoRef vimtypes.ManagedObjectReference
NetworkResults network.NetworkInterfaceResults
}
// TODO: Until we sort out what the Session becomes.
type vmUpdateArgs = session.VMUpdateArgs
type vmResizeArgs = session.VMResizeArgs
var (
createCountLock sync.Mutex
concurrentCreateCount int
// currentlyReconciling tracks the VMs currently being created in a
// non-blocking goroutine.
currentlyReconciling sync.Map
// SkipVMImageCLProviderCheck skips the checks that a VM Image has a Content Library item provider
// since a VirtualMachineImage created for a VM template won't have either. This has been broken for
// a long time but was otherwise masked on how the tests used to be organized.
SkipVMImageCLProviderCheck = false
)
func (vs *vSphereVMProvider) CreateOrUpdateVirtualMachine(
ctx context.Context,
vm *vmopv1.VirtualMachine) error {
_, err := vs.createOrUpdateVirtualMachine(ctx, vm, false)
return err
}
func (vs *vSphereVMProvider) CreateOrUpdateVirtualMachineAsync(
ctx context.Context,
vm *vmopv1.VirtualMachine) (<-chan error, error) {
return vs.createOrUpdateVirtualMachine(ctx, vm, true)
}
func (vs *vSphereVMProvider) createOrUpdateVirtualMachine(
ctx context.Context,
vm *vmopv1.VirtualMachine,
async bool) (chan error, error) {
logger := pkglog.FromContextOrDefault(ctx)
logger.V(4).Info("Entering createOrUpdateVirtualMachine")
if vm.APIVersion == "" || vm.Kind == "" {
// Updating to controller-runtime v0.22.3 also updates the k8s.io/yaml
// dependency, which now returns an error when marshalling objects from
// JSON to YAML if the object's GVK is missing. Since client-go does not
// set the API Version or Kind when unmarshaling an object from the API
// server (see https://github.com/kubernetes/client-go/issues/541), this
// seems like a bug/issue with their interop. Since backup does need to
// marshal from JSON-to-YAML, ensure the VM's GVK is set correctly early
// in case others encounter this as well.
if err := kubeutil.SyncGVKToObject(
vm,
vs.k8sClient.Scheme()); err != nil {
return nil, fmt.Errorf("failed to sync vm gvk: %w", err)
}
}
vmNamespacedName := vm.NamespacedName()
if _, ok := currentlyReconciling.Load(vmNamespacedName); ok {
// Do not process the VM again if it is already being reconciled in a
// goroutine.
return nil, providers.ErrReconcileInProgress
}
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "createOrUpdateVM"),
vm,
true,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return nil, err
}
// Set the VC UUID annotation on the VM before attempting creation or
// update. Among other things, the annotation facilitates differential
// handling of restore and fail-over operations.
if vm.Annotations == nil {
vm.Annotations = make(map[string]string)
}
vCenterInstanceUUID := client.VimClient().ServiceContent.About.InstanceUuid
vm.Annotations[vmopv1.ManagerID] = vCenterInstanceUUID
// Check to see if the VM can be found on the underlying platform.
foundVM, err := vs.getVM(vmCtx, client, false)
if err != nil {
vmCtx.Logger.Error(err, "failed to find vm")
return nil, err
}
if foundVM != nil {
// Mark that this is an update operation.
ctxop.MarkUpdate(vmCtx)
vmCtx.Logger.V(4).Info("found VM and updating")
return nil, vs.updateVirtualMachine(vmCtx, foundVM, client)
}
// Mark that this is a create operation.
ctxop.MarkCreate(vmCtx)
// Do not allow more than N create threads/goroutines.
//
// - In blocking create mode, this ensures there are reconciler threads
// available to reconcile non-create operations.
//
// - In non-blocking create mode, this ensures the number of goroutines
// spawned to create VMs does not take up too much memory.
allowed, decrementConcurrentCreatesFn := vs.vmCreateConcurrentAllowed(vmCtx)
if !allowed {
return nil, providers.ErrTooManyCreates
}
// cleanupFn tracks the function(s) that must be invoked upon leaving this
// function during a blocking create or after an async create.
cleanupFn := decrementConcurrentCreatesFn
if !async {
defer cleanupFn()
vmCtx.Logger.V(4).Info("Doing a blocking create")
createArgs, err := vs.getCreateArgs(vmCtx, client)
if err != nil {
return nil, err
}
if _, err := vs.createVirtualMachine(
vmCtx,
client,
createArgs); err != nil {
return nil, err
}
return nil, nil
}
if _, ok := currentlyReconciling.LoadOrStore(
vmNamespacedName,
struct{}{}); ok {
// If the VM is already being created in a goroutine, then there is no
// need to create it again.
//
// However, we need to make sure we decrement the number of concurrent
// creates before returning.
cleanupFn()
return nil, providers.ErrReconcileInProgress
}
vmCtx.Logger.V(4).Info("Doing a non-blocking create")
// Update the cleanup function to include indicating a concurrent create is
// no longer occurring.
cleanupFn = func() {
currentlyReconciling.Delete(vmNamespacedName)
decrementConcurrentCreatesFn()
}
var asyncCreateStarted bool
defer func() {
// If the async create go routine was started then it will call
// the cleanupFn when it is done.
if !asyncCreateStarted {
cleanupFn()
}
}()
createArgs, err := vs.getCreateArgs(vmCtx, client)
if err != nil {
return nil, err
}
// Create a copy of the context and replace its VM with a copy to
// ensure modifications in the goroutine below are not impacted or
// impact the operations above us in the call stack.
copyOfCtx := vmCtx
copyOfCtx.VM = vmCtx.VM.DeepCopy()
// Start a goroutine to create the VM in the background.
chanErr := make(chan error)
go vs.createVirtualMachineAsync(
copyOfCtx,
client,
createArgs,
chanErr,
cleanupFn)
asyncCreateStarted = true
// Return with the error channel. The VM will be re-enqueued once the create
// completes with success or failure.
return chanErr, nil
}
// CleanupVirtualMachine cleans and sanitizes the vSphere VM before it
// is unregistered from Supervisor. This is used when a VM custom
// resource with
// "vmoperator.vmware.com.protected/skip-delete-platform-resource"
// annotation is deleted.
func (vs *vSphereVMProvider) CleanupVirtualMachine(
ctx context.Context,
vm *vmopv1.VirtualMachine) error {
vmNamespacedName := vm.NamespacedName()
if _, ok := currentlyReconciling.Load(vmNamespacedName); ok {
// If the VM is already being reconciled in a goroutine then it cannot
// be cleaned up yet. Return and requeue.
return providers.ErrReconcileInProgress
}
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "cleanupVM"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return err
}
vcVM, err := vs.getVM(vmCtx, client, false)
if err != nil {
return err
} else if vcVM == nil {
// VM does not exist, nothing to clean up.
vmCtx.Logger.Info("VM does not exist in vCenter, skipping cleanup")
return nil
}
// Clean up all VM Operator modifications from the vCenter VM.
if err := virtualmachine.CleanupVMServiceState(
vmCtx,
vcVM); err != nil {
return fmt.Errorf("failed to cleanup VM service state: %w", err)
}
return nil
}
func (vs *vSphereVMProvider) DeleteVirtualMachine(
ctx context.Context,
vm *vmopv1.VirtualMachine) error {
vmNamespacedName := vm.NamespacedName()
if _, ok := currentlyReconciling.Load(vmNamespacedName); ok {
// If the VM is already being reconciled in a goroutine then it cannot
// be deleted yet.
return providers.ErrReconcileInProgress
}
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "deleteVM"),
vm,
true,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return err
}
vcVM, err := vs.getVM(vmCtx, client, false)
if err != nil {
return err
} else if vcVM == nil {
// VM does not exist.
return nil
}
if err := vcVM.Properties(
vmCtx,
vcVM.Reference(),
virtualmachine.VMDeletePropertiesSelector,
&vmCtx.MoVM); err != nil {
return fmt.Errorf("failed to fetch props when deleting VM: %w", err)
}
// Only process connected VMs or if the connection state is empty.
if cs := vmCtx.MoVM.Summary.Runtime.ConnectionState; cs != "" && cs !=
vimtypes.VirtualMachineConnectionStateConnected {
// Return a NoRequeueError so the VM is not requeued for
// reconciliation.
//
// The watcher service ensures that VMs will be reconciled
// immediately upon their summary.runtime.connectionState value
// changing.
//
// TODO(akutz) Determine if we should surface some type of condition
// that indicates this state.
return fmt.Errorf("failed to delete vm: %w", pkgerr.NoRequeueError{
Message: fmt.Sprintf("unsupported connection state: %s", cs),
})
}
if paused.ByAdmin(vmCtx.MoVM) {
if vmCtx.VM.Labels == nil {
vmCtx.VM.Labels = make(map[string]string)
}
vmCtx.VM.Labels[vmopv1.PausedVMLabelKey] = "admin"
// Throw an error to distinguish from successful deletion.
return fmt.Errorf("failed to delete vm: %w", pkgerr.NoRequeueError{
Message: constants.VMPausedByAdminError,
})
}
// If the disk promotion task is still running, try to cancel since it has the
// VM locked and delete cannot happen while it is running.
if pkgcfg.FromContext(vmCtx).Features.FastDeploy {
ctxWithRecentTaskInfo, err := vs.getRecentTaskInfo(vmCtx, client)
if err != nil {
return fmt.Errorf("failed to fetch recent tasks: %w", err)
}
vmCtx.Context = ctxWithRecentTaskInfo
for _, t := range pkgctx.GetVMRecentTasks(vmCtx) {
if t.State == vimtypes.TaskInfoStateRunning &&
t.DescriptionId == vmconfdiskpromo.PromoteDisksTaskKey {
task := object.NewTask(vcVM.Client(), t.Task)
if err := task.Cancel(vmCtx); err != nil {
return fmt.Errorf("failed to cancel disk promotion task: %w", err)
}
}
}
}
return virtualmachine.DeleteVirtualMachine(vmCtx, vcVM, client.Datacenter())
}
func (vs *vSphereVMProvider) PublishVirtualMachine(
ctx context.Context,
vm *vmopv1.VirtualMachine,
vmPub *vmopv1.VirtualMachinePublishRequest,
cl *imgregv1a1.ContentLibrary,
actID string) (string, error) {
logger := pkglog.FromContextOrDefault(ctx).WithValues(
"clName", cl.Namespace+"/"+cl.Name)
ctx = logr.NewContext(ctx, logger)
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "publishVM"),
vm,
)
ctx = vmCtx.Context
// For CL publishing ensure the activation ID is at the end of the ID
// so we can correlate this underlying publish task.
id := ctx.Value(vimtypes.ID{})
if opID, ok := id.(string); ok {
opID += "-" + actID
ctx = context.WithValue(ctx, vimtypes.ID{}, opID)
vmCtx.Context = ctx
}
client, err := vs.getVcClient(ctx)
if err != nil {
return "", fmt.Errorf("failed to get vCenter client: %w", err)
}
if pkgcfg.FromContext(ctx).Features.InventoryContentLibrary {
v1a2contentLibrary := &imgregv1.ContentLibrary{}
objKey := ctrlclient.ObjectKey{
Name: vmPub.Spec.Target.Location.Name,
Namespace: vmPub.Namespace,
}
if err := vs.k8sClient.Get(ctx, objKey, v1a2contentLibrary); err != nil {
return "", fmt.Errorf("failed to get v1a2 content library %v: %w", objKey, err)
}
if v1a2contentLibrary.Spec.Type == imgregv1.LibraryTypeInventory {
var (
storagePolicyID string
err error
)
storageClassName := v1a2contentLibrary.Spec.StorageClass
if storageClassName != "" {
sc := storagev1.StorageClass{}
if err := vs.k8sClient.Get(vmCtx, ctrlclient.ObjectKey{Name: storageClassName}, &sc); err != nil {
return "", fmt.Errorf("failed to get storage class %q: %w", storageClassName, err)
}
storagePolicyID, err = kubeutil.GetStoragePolicyIDFromStorageClass(sc)
if err != nil {
return "", err
}
}
logger.V(4).Info("Publishing VM as cloned template", "activationID", actID)
return virtualmachine.CloneVM(vmCtx, client.VimClient(), vmPub, v1a2contentLibrary, storagePolicyID)
}
}
logger.V(4).Info("Publishing VM as OVF", "activationID", actID)
return virtualmachine.CreateOVF(vmCtx, client.RestClient(), vmPub, cl, actID)
}
func (vs *vSphereVMProvider) GetVirtualMachineGuestHeartbeat(
ctx context.Context,
vm *vmopv1.VirtualMachine) (vmopv1.GuestHeartbeatStatus, error) {
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "heartbeat"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return "", err
}
vcVM, err := vs.getVM(vmCtx, client, true)
if err != nil {
return "", err
}
status, err := virtualmachine.GetGuestHeartBeatStatus(vmCtx, vcVM)
if err != nil {
return "", err
}
return status, nil
}
func (vs *vSphereVMProvider) GetVirtualMachineProperties(
ctx context.Context,
vm *vmopv1.VirtualMachine,
propertyPaths []string) (map[string]any, error) {
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "properties"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(vmCtx)
if err != nil {
return nil, err
}
vcVM, err := vs.getVM(vmCtx, client, true)
if err != nil {
return nil, err
}
propSet := []vimtypes.PropertySpec{{Type: "VirtualMachine"}}
if len(propertyPaths) == 0 {
propSet[0].All = vimtypes.NewBool(true)
} else {
propSet[0].PathSet = propertyPaths
}
rep, err := property.DefaultCollector(client.VimClient()).RetrieveProperties(
ctx,
vimtypes.RetrieveProperties{
SpecSet: []vimtypes.PropertyFilterSpec{
{
ObjectSet: []vimtypes.ObjectSpec{
{
Obj: vcVM.Reference(),
},
},
PropSet: propSet,
},
},
})
if err != nil {
return nil, err
}
if len(rep.Returnval) == 0 {
return nil, fmt.Errorf("no properties")
}
result := map[string]any{}
for i := range rep.Returnval[0].PropSet {
dp := rep.Returnval[0].PropSet[i]
result[dp.Name] = dp.Val
}
return result, nil
}
func (vs *vSphereVMProvider) GetVirtualMachineFiles(
ctx context.Context,
vm *vmopv1.VirtualMachine) ([]vimtypes.VirtualMachineFileLayoutExFileInfo, error) {
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "vmFiles"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return nil, err
}
vcVM, err := vs.getVM(vmCtx, client, true)
if err != nil {
return nil, err
}
var o mo.VirtualMachine
err = vcVM.Properties(vmCtx, vcVM.Reference(), []string{"layoutEx"}, &o)
if err != nil {
return nil, err
}
if o.LayoutEx != nil {
return o.LayoutEx.File, nil
}
return nil, nil
}
func (vs *vSphereVMProvider) GetVirtualMachineWebMKSTicket(
ctx context.Context,
vm *vmopv1.VirtualMachine,
pubKey string) (string, error) {
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "webconsole"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return "", err
}
vcVM, err := vs.getVM(vmCtx, client, true)
if err != nil {
return "", err
}
ticket, err := virtualmachine.GetWebConsoleTicket(vmCtx, vcVM, pubKey)
if err != nil {
return "", err
}
return ticket, nil
}
func (vs *vSphereVMProvider) GetVirtualMachineHardwareVersion(
ctx context.Context,
vm *vmopv1.VirtualMachine) (vimtypes.HardwareVersion, error) {
vmCtx := pkgctx.NewVirtualMachineContext(
pkgctx.WithVCOpID(ctx, vm, "hwVersion"),
vm,
)
ctx = vmCtx.Context
client, err := vs.getVcClient(ctx)
if err != nil {
return 0, err
}
vcVM, err := vs.getVM(vmCtx, client, true)
if err != nil {
return 0, err
}
var o mo.VirtualMachine
err = vcVM.Properties(vmCtx, vcVM.Reference(), []string{"config.version"}, &o)
if err != nil {
return 0, err
}
return vimtypes.ParseHardwareVersion(o.Config.Version)
}
func (vs *vSphereVMProvider) vmCreatePathName(
vmCtx pkgctx.VirtualMachineContext,
vcClient *vcclient.Client,
createArgs *VMCreateArgs) error {
if hw := vmCtx.VM.Spec.Hardware; hw == nil || len(hw.Cdrom) == 0 {
return nil // only needed when deploying ISO library items
}
if createArgs.StorageProfileID == "" {
return nil
}
if createArgs.ConfigSpec.Files == nil {
createArgs.ConfigSpec.Files = &vimtypes.VirtualMachineFileInfo{}
}
if createArgs.ConfigSpec.Files.VmPathName != "" {
return nil
}
vc := vcClient.VimClient()
pc, err := pbm.NewClient(vmCtx, vc)
if err != nil {
return err
}
ds, err := pc.DatastoreMap(vmCtx, vc, createArgs.ClusterMoRef)
if err != nil {
return err
}
req := []pbmtypes.BasePbmPlacementRequirement{
&pbmtypes.PbmPlacementCapabilityProfileRequirement{
ProfileId: pbmtypes.PbmProfileId{UniqueId: createArgs.StorageProfileID},
},
}
res, err := pc.CheckRequirements(vmCtx, ds.PlacementHub, nil, req)
if err != nil {
return err
}
hubs := res.CompatibleDatastores()
if len(hubs) == 0 {
return nil
}
hub := hubs[rand.Intn(len(hubs))] //nolint:gosec
createArgs.ConfigSpec.Files.VmPathName = (&object.DatastorePath{
Datastore: ds.Name[hub.HubId],
}).String()
vmCtx.Logger.Info("vmCreatePathName", "VmPathName", createArgs.ConfigSpec.Files.VmPathName)
return nil
}
func (vs *vSphereVMProvider) vmCreatePathNameFromDatastoreRecommendation(
vmCtx pkgctx.VirtualMachineContext,
createArgs *VMCreateArgs) error {
if createArgs.ConfigSpec.Files == nil {
createArgs.ConfigSpec.Files = &vimtypes.VirtualMachineFileInfo{}
}
if createArgs.ConfigSpec.Files.VmPathName != "" {
return nil
}
if len(createArgs.Datastores) == 0 {
return errors.New("no compatible datastores")
}
createArgs.ConfigSpec.Files.VmPathName = fmt.Sprintf(
"[%s] %s/%s.vmx",
createArgs.Datastores[0].Name,
vmCtx.VM.UID,
vmCtx.VM.Name)
vmCtx.Logger.Info(
"vmCreatePathName",
"VmPathName", createArgs.ConfigSpec.Files.VmPathName)
return nil
}
func (vs *vSphereVMProvider) getCreateArgs(
vmCtx pkgctx.VirtualMachineContext,
vcClient *vcclient.Client) (*VMCreateArgs, error) {
createArgs, err := vs.vmCreateGetArgs(vmCtx, vcClient)
if err != nil {
return nil, err
}
if err := vs.vmCreateDoPlacement(vmCtx, vcClient, createArgs); err != nil {
return nil, err
}
if err := vs.vmCreateGetFolderAndRPMoIDs(vmCtx, vcClient, createArgs); err != nil {
return nil, err
}
if pkgcfg.FromContext(vmCtx).Features.FastDeploy {
if err := vs.vmCreateGetSourceFilePaths(vmCtx, vcClient, createArgs); err != nil {
return nil, err
}
if err := vs.vmCreatePathNameFromDatastoreRecommendation(vmCtx, createArgs); err != nil {
return nil, err
}
} else {
if err := vs.vmCreatePathName(vmCtx, vcClient, createArgs); err != nil {
return nil, err
}
}
if err := vs.vmCreateIsReady(vmCtx, createArgs); err != nil {
return nil, err
}
return createArgs, nil
}
func (vs *vSphereVMProvider) createVirtualMachine(
ctx pkgctx.VirtualMachineContext,
vcClient *vcclient.Client,
args *VMCreateArgs) (*object.VirtualMachine, error) {
moRef, err := vmlifecycle.CreateVirtualMachine(
ctx,
vs.k8sClient,
vcClient.RestClient(),
vcClient.VimClient(),
vcClient.Finder(),
&args.CreateArgs)
if err != nil {
ctx.Logger.Error(err, "CreateVirtualMachine failed")
pkgcnd.MarkError(
ctx.VM,
vmopv1.VirtualMachineConditionCreated,
"Error",
err)
if pkgcfg.FromContext(ctx).Features.FastDeploy {
pkgcnd.MarkError(
ctx.VM,
vmopv1.VirtualMachineConditionPlacementReady,
"Error",
err)
}
return nil, err
}
ctx.VM.Status.UniqueID = moRef.Reference().Value
pkgcnd.MarkTrue(ctx.VM, vmopv1.VirtualMachineConditionCreated)
if pkgcfg.FromContext(ctx).Features.FastDeploy {
if zoneName := args.ZoneName; zoneName != "" {
if ctx.VM.Labels == nil {
ctx.VM.Labels = map[string]string{}
}
ctx.VM.Labels[corev1.LabelTopologyZone] = zoneName
}
}
return object.NewVirtualMachine(vcClient.VimClient(), *moRef), ErrCreate
}
func (vs *vSphereVMProvider) createVirtualMachineAsync(
ctx pkgctx.VirtualMachineContext,
vcClient *vcclient.Client,
args *VMCreateArgs,
chanErr chan error,
cleanupFn func()) {
defer func() {
close(chanErr)
cleanupFn()
}()
moRef, vimErr := vmlifecycle.CreateVirtualMachine(
ctx,
vs.k8sClient,
vcClient.RestClient(),
vcClient.VimClient(),
vcClient.Finder(),
&args.CreateArgs)
if vimErr != nil {
ctx.Logger.Error(vimErr, "CreateVirtualMachine failed")
chanErr <- vimErr
} else {
chanErr <- ErrCreate
}
objPatch := ctrlclient.MergeFrom(ctx.VM.DeepCopy())
if vimErr != nil {
pkgcnd.MarkError(
ctx.VM,
vmopv1.VirtualMachineConditionCreated,
"Error",
vimErr)
} else {
if pkgcfg.FromContext(ctx).Features.FastDeploy {
if zoneName := args.ZoneName; zoneName != "" {
if ctx.VM.Labels == nil {
ctx.VM.Labels = map[string]string{}
}
ctx.VM.Labels[corev1.LabelTopologyZone] = zoneName
}
}
ctx.VM.Status.UniqueID = moRef.Reference().Value
pkgcnd.MarkTrue(ctx.VM, vmopv1.VirtualMachineConditionCreated)
}
if err := vs.k8sClient.Status().Patch(ctx, ctx.VM, objPatch); err != nil {
ctx.Logger.Error(err, "Failed to patch VM status after create")
chanErr <- err
}
}
// VMUpdatePropertiesSelector is the set of VM properties fetched at the start
// of updateVirtualMachine.
var VMUpdatePropertiesSelector = []string{
"config",
"guest",
"layoutEx",
"recentTask",
"resourcePool",
"runtime",
"snapshot",
"summary",
}
func getReconcileErr(msg string, reconcileErr, err error) error {
err = fmt.Errorf("failed to reconcile %s: %w", msg, err)
if reconcileErr == nil {
return err
}
return fmt.Errorf("%w, %w", err, reconcileErr)
}
func errOrReconcileErr(reconcileErr, err error) error {
if reconcileErr != nil {
return reconcileErr
}
return err
}
// updateVirtualMachine performs the following operations in the stated order:
//
// 1. Fetch properties
// 2. Fetch recent tasks
// 3. Fetch attached tags
// 4. Fetch volume info
// 5. Reconcile status
// 6. Reconcile schema upgrade
// 7. Reconcile backup state
// 8. Reconcile snapshot revert
// 9. Reconcile config
// 10. Reconcile power state
// 11. Reconcile snapshot create
func (vs *vSphereVMProvider) updateVirtualMachine(
vmCtx pkgctx.VirtualMachineContext,
vcVM *object.VirtualMachine,
vcClient *vcclient.Client) error {
vmCtx.Logger.V(4).Info("Updating VirtualMachine")
var reconcileErr error
//
// 1. Fetch properties
//
if err := vcVM.Properties(
vmCtx,
vcVM.Reference(),
VMUpdatePropertiesSelector,
&vmCtx.MoVM); err != nil {
return fmt.Errorf("failed to fetch vm properties: %w", err)
}
//
// 2. Get the recent tasks.
//
ctxWithRecentTaskInfo, err := vs.getRecentTaskInfo(vmCtx, vcClient)
if err != nil {