-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathupdate_status.go
More file actions
1938 lines (1651 loc) · 55.9 KB
/
update_status.go
File metadata and controls
1938 lines (1651 loc) · 55.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
// © Broadcom. All Rights Reserved.
// The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package vmlifecycle
import (
"context"
"fmt"
"net"
"reflect"
"regexp"
"slices"
"strings"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/mo"
vimtypes "github.com/vmware/govmomi/vim25/types"
"github.com/vmware/govmomi/vmdk"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apierrorsutil "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
vmopv1 "github.com/vmware-tanzu/vm-operator/api/v1alpha5"
"github.com/vmware-tanzu/vm-operator/api/v1alpha5/common"
"github.com/vmware-tanzu/vm-operator/pkg/conditions"
pkgcfg "github.com/vmware-tanzu/vm-operator/pkg/config"
pkgctx "github.com/vmware-tanzu/vm-operator/pkg/context"
pkglog "github.com/vmware-tanzu/vm-operator/pkg/log"
"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/vcenter"
"github.com/vmware-tanzu/vm-operator/pkg/providers/vsphere/virtualmachine"
vmoprecord "github.com/vmware-tanzu/vm-operator/pkg/record"
"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"
vmopv1util "github.com/vmware-tanzu/vm-operator/pkg/util/vmopv1"
pkgvol "github.com/vmware-tanzu/vm-operator/pkg/util/volumes"
)
type ReconcileStatusData struct {
// NetworkDeviceKeysToSpecIdx maps the network device's DeviceKey to its
// corresponding index in the VM's Spec.Network.Interfaces[].
NetworkDeviceKeysToSpecIdx map[int32]int
}
func ReconcileStatus(
vmCtx pkgctx.VirtualMachineContext,
k8sClient ctrlclient.Client,
vcVM *object.VirtualMachine,
data ReconcileStatusData) error {
vm := vmCtx.VM
// This is implicitly true: ensure the condition is set since it is how we
// determine the old v1a1 Phase.
conditions.MarkTrue(vm, vmopv1.VirtualMachineConditionCreated)
var errs []error
errs = append(errs, reconcileStatusAnno2Conditions(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusClass(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusPowerState(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusIdentifiers(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusHardware(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusHardwareVersion(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusGuest(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusStorage(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusZone(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusNodeName(vmCtx, k8sClient, vcVM, data)...)
errs = append(errs, reconcileStatusController(vmCtx, k8sClient, vcVM, data)...)
if pkgcfg.FromContext(vmCtx).Features.VMSharedDisks {
errs = append(errs, reconcileHardwareCondition(vmCtx, k8sClient, vcVM, data)...)
}
if pkgcfg.FromContext(vmCtx).AsyncSignalEnabled {
errs = append(errs, reconcileStatusProbe(vmCtx, k8sClient, vcVM, data)...)
}
if pkgcfg.FromContext(vmCtx).Features.VMGroups {
errs = append(errs, reconcileStatusGroup(vmCtx, k8sClient, vcVM, data)...)
}
if pkgcfg.FromContext(vmCtx).Features.VMSnapshots {
errs = append(errs, reconcileStatusSnapshot(vmCtx, k8sClient, vcVM, data)...)
}
MarkReconciliationCondition(vmCtx.VM)
return apierrorsutil.NewAggregate(errs)
}
var anno2ConditionRegex = regexp.MustCompile(`^condition.vmoperator.vmware.com.protected/(.+)?$`)
// reconcileStatusAnno2Conditions sets conditions on the VM based on
// annotation values.
func reconcileStatusAnno2Conditions(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
for k, v := range vmCtx.VM.Annotations {
if anno2ConditionRegex.MatchString(k) {
var (
t string
s metav1.ConditionStatus
r string
m string
)
p := strings.Split(v, ";")
if len(p) > 0 {
t = p[0]
}
if len(p) > 1 {
s = metav1.ConditionStatus(p[1])
}
if len(p) > 2 {
r = p[2]
}
if len(p) > 3 {
m = p[3]
}
if t != "" {
switch s {
case metav1.ConditionFalse:
conditions.MarkFalse(vmCtx.VM, t, r, m+"%s", "")
case metav1.ConditionTrue:
conditions.MarkTrue(vmCtx.VM, t)
default:
conditions.MarkUnknown(vmCtx.VM, t, r, m+"%s", "")
}
}
}
}
return nil
}
func reconcileStatusClass(
vmCtx pkgctx.VirtualMachineContext,
k8sClient ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
if vmopv1util.IsClasslessVM(*vmCtx.VM) {
vmCtx.VM.Status.Class = nil
} else if vmCtx.VM.Status.Class == nil {
// When resize is enabled, don't backfill the class from the spec
// since we don't know if the class has been applied to the VM.
// When resize is enabled, this field is updated after a successful
// resize.
if f := pkgcfg.FromContext(vmCtx).Features; !f.VMResize && !f.VMResizeCPUMemory {
vmCtx.VM.Status.Class = &common.LocalObjectRef{
APIVersion: vmopv1.GroupVersion.String(),
Kind: "VirtualMachineClass",
Name: vmCtx.VM.Spec.ClassName,
}
}
}
if f := pkgcfg.FromContext(vmCtx).Features; f.VMResize || f.VMResizeCPUMemory {
MarkVMClassConfigurationSynced(vmCtx, vmCtx.VM, k8sClient)
}
return nil
}
func reconcileStatusGroup(
vmCtx pkgctx.VirtualMachineContext,
k8sClient ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error {
var errs []error
if err := vmopv1util.UpdateGroupLinkedCondition(
vmCtx,
vmCtx.VM,
k8sClient,
); err != nil {
errs = append(errs, err)
}
return errs
}
func reconcileStatusHardware(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
config := vmCtx.MoVM.Config
if config == nil {
return nil
}
var (
cpuTotal = config.Hardware.NumCPU
cpuReservation int64
)
if a := config.CpuAllocation; a != nil {
if a.Reservation != nil && *a.Reservation > 0 {
cpuReservation = *a.Reservation
}
}
if cpuTotal > 0 || cpuReservation > 0 {
if vmCtx.VM.Status.Hardware == nil {
vmCtx.VM.Status.Hardware = &vmopv1.VirtualMachineHardwareStatus{}
}
vmCtx.VM.Status.Hardware.CPU = &vmopv1.VirtualMachineCPUAllocationStatus{
Total: cpuTotal,
Reservation: cpuReservation,
}
}
var (
memTotal = int64(config.Hardware.MemoryMB)
memReservation int64
)
if a := config.MemoryAllocation; a != nil {
if a.Reservation != nil && *a.Reservation > 0 {
memReservation = *a.Reservation
}
}
if memTotal > 0 || memReservation > 0 {
if vmCtx.VM.Status.Hardware == nil {
vmCtx.VM.Status.Hardware = &vmopv1.VirtualMachineHardwareStatus{}
}
vmCtx.VM.Status.Hardware.Memory = &vmopv1.VirtualMachineMemoryAllocationStatus{}
if r := memTotal; r > 0 {
b := r * 1000 * 1000
q := kubeutil.BytesToResource(b)
vmCtx.VM.Status.Hardware.Memory.Total = q
}
if r := memReservation; r > 0 {
b := r * 1000 * 1000
q := kubeutil.BytesToResource(b)
vmCtx.VM.Status.Hardware.Memory.Reservation = q
}
}
if vmCtx.VM.Status.Hardware != nil {
vmCtx.VM.Status.Hardware.VGPUs = nil
}
for _, d := range config.Hardware.Device {
switch td := d.(type) {
//
// PCI Passthrough
//
case *vimtypes.VirtualPCIPassthrough:
//
// nVidia vGPU
//
if b, ok := td.Backing.(*vimtypes.VirtualPCIPassthroughVmiopBackingInfo); ok {
migrationType := vmopv1.VirtualMachineVGPUMigrationTypeNone
if m := b.EnhancedMigrateCapability; m != nil && *m {
migrationType = vmopv1.VirtualMachineVGPUMigrationTypeEnhanced
} else if m := b.MigrateSupported; m != nil && *m {
migrationType = vmopv1.VirtualMachineVGPUMigrationTypeNormal
}
if vmCtx.VM.Status.Hardware == nil {
vmCtx.VM.Status.Hardware = &vmopv1.VirtualMachineHardwareStatus{}
}
vmCtx.VM.Status.Hardware.VGPUs = append(
vmCtx.VM.Status.Hardware.VGPUs,
vmopv1.VirtualMachineHardwareVGPUStatus{
Type: vmopv1.VirtualMachineVGPUTypeNVIDIA,
Profile: b.Vgpu,
MigrationType: migrationType,
})
}
//
// vTPM
//
case *vimtypes.VirtualTPM:
if vmCtx.VM.Status.Crypto == nil {
vmCtx.VM.Status.Crypto = &vmopv1.VirtualMachineCryptoStatus{}
}
vmCtx.VM.Status.Crypto.HasVTPM = true
}
}
return nil
}
func reconcileStatusPowerState(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
vmCtx.VM.Status.PowerState = vmopv1util.ConvertPowerState(vmCtx.Logger,
vmCtx.MoVM.Runtime.PowerState)
if vmCtx.VM.Status.PowerState == vmCtx.VM.Spec.PowerState {
c := conditions.TrueCondition(vmopv1.VirtualMachinePowerStateSynced)
c.Reason = "Synced"
c.Message = string(vmCtx.VM.Spec.PowerState)
conditions.Set(vmCtx.VM, c)
} else {
conditions.MarkFalse(
vmCtx.VM,
vmopv1.VirtualMachinePowerStateSynced,
"NotSynced",
"spec.powerState=%s != status.powerState=%s",
vmCtx.VM.Spec.PowerState, vmCtx.VM.Status.PowerState)
}
return nil
}
func reconcileStatusIdentifiers(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
vmCtx.VM.Status.UniqueID = vmCtx.MoVM.Self.Value
vmCtx.VM.Status.BiosUUID = vmCtx.MoVM.Summary.Config.Uuid
vmCtx.VM.Status.InstanceUUID = vmCtx.MoVM.Summary.Config.InstanceUuid
return nil
}
func reconcileStatusHardwareVersion(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
hardwareVersion, _ := vimtypes.ParseHardwareVersion(
vmCtx.MoVM.Summary.Config.HwVersion)
vmCtx.VM.Status.HardwareVersion = int32(hardwareVersion)
return nil
}
func reconcileStatusZone(
vmCtx pkgctx.VirtualMachineContext,
k8sClient ctrlclient.Client,
vcVM *object.VirtualMachine,
_ ReconcileStatusData) []error {
var errs []error
zoneName := vmCtx.VM.Labels[corev1.LabelTopologyZone]
if zoneName == "" {
clusterMoRef, err := vcenter.GetResourcePoolOwnerMoRef(
vmCtx, vcVM.Client(), vmCtx.MoVM.ResourcePool.Value)
if err != nil {
errs = append(errs, err)
} else {
zoneName, err = topology.LookupZoneForClusterMoID(
vmCtx, k8sClient, clusterMoRef.Value)
if err != nil {
errs = append(errs, err)
} else {
if vmCtx.VM.Labels == nil {
vmCtx.VM.Labels = map[string]string{}
}
vmCtx.VM.Labels[corev1.LabelTopologyZone] = zoneName
}
}
}
if zoneName != "" {
vmCtx.VM.Status.Zone = zoneName
}
return errs
}
func reconcileStatusSnapshot(
vmCtx pkgctx.VirtualMachineContext,
k8sClient ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error {
var errs []error
if err := SyncVMSnapshotTreeStatus(vmCtx, k8sClient); err != nil {
errs = append(errs, err)
}
return errs
}
func reconcileStatusGuest(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
data ReconcileStatusData) []error { //nolint:unparam
var extraConfig map[string]string
if config := vmCtx.MoVM.Config; config != nil {
extraConfig = object.OptionValueList(config.ExtraConfig).StringMap()
}
updateGuestNetworkStatus(
vmCtx.VM,
vmCtx.MoVM.Guest,
extraConfig,
data.NetworkDeviceKeysToSpecIdx)
if vmCtx.MoVM.Summary.Guest != nil && vmCtx.MoVM.Summary.Guest.HostName != "" {
if vmCtx.VM.Status.Network == nil {
vmCtx.VM.Status.Network = &vmopv1.VirtualMachineNetworkStatus{}
}
vmCtx.VM.Status.Network.HostName = vmCtx.MoVM.Summary.Guest.HostName
}
MarkVMToolsRunningStatusCondition(vmCtx.VM, vmCtx.MoVM.Guest)
MarkCustomizationInfoCondition(vmCtx.VM, vmCtx.MoVM.Guest)
MarkBootstrapCondition(vmCtx.VM, extraConfig)
if config := vmCtx.MoVM.Config; config != nil {
guestID := vmCtx.MoVM.Config.GuestId
guestName := vmCtx.MoVM.Config.GuestFullName
if guestID != "" || guestName != "" {
if vmCtx.VM.Status.Guest == nil {
vmCtx.VM.Status.Guest = &vmopv1.VirtualMachineGuestStatus{}
}
vmCtx.VM.Status.Guest.GuestID = guestID
vmCtx.VM.Status.Guest.GuestFullName = guestName
}
}
return nil
}
// reconcileStatusStorage updates the status for all storage-related fields.
func reconcileStatusStorage(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
var errs []error
updateChangeBlockTracking(vmCtx.VM, vmCtx.MoVM)
updateVolumeStatus(vmCtx)
errs = append(errs, updateStorageUsage(vmCtx)...)
return errs
}
func reconcileStatusNodeName(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
vcVM *object.VirtualMachine,
_ ReconcileStatusData) []error {
var errs []error
nodeName, err := getRuntimeHostHostname(
vmCtx, vcVM, vmCtx.MoVM.Summary.Runtime.Host)
if err != nil {
errs = append(errs, err)
} else {
vmCtx.VM.Status.NodeName = nodeName
}
return errs
}
// updateProbeStatus updates a VM's status with the results of the configured
// readiness probes.
// Please note, this function returns early if the configured probe is TCP.
func reconcileStatusProbe(
vmCtx pkgctx.VirtualMachineContext,
_ ctrlclient.Client,
_ *object.VirtualMachine,
_ ReconcileStatusData) []error { //nolint:unparam
p := vmCtx.VM.Spec.ReadinessProbe
if p == nil || p.TCPSocket != nil {
return nil
}
var (
result probeResult
resultMsg string
extraConfig map[string]string
)
if config := vmCtx.MoVM.Config; config != nil {
extraConfig = object.OptionValueList(config.ExtraConfig).StringMap()
}
switch {
case p.GuestHeartbeat != nil:
result, resultMsg = updateProbeStatusHeartbeat(vmCtx.VM, vmCtx.MoVM)
case p.GuestInfo != nil:
result, resultMsg = updateProbeStatusGuestInfo(vmCtx.VM, extraConfig)
}
var cond *metav1.Condition
switch result {
case probeResultSuccess:
cond = conditions.TrueCondition(vmopv1.ReadyConditionType)
case probeResultFailure:
cond = conditions.FalseCondition(
vmopv1.ReadyConditionType, probeReasonNotReady, "%s", resultMsg)
default:
cond = conditions.UnknownCondition(
vmopv1.ReadyConditionType, probeReasonUnknown, "%s", resultMsg)
}
// Emit event whe the condition is added or its status changes.
if c := conditions.Get(vmCtx.VM, cond.Type); c == nil || c.Status != cond.Status {
recorder := vmoprecord.FromContext(vmCtx)
if cond.Status == metav1.ConditionTrue {
recorder.Eventf(vmCtx.VM, probeReasonReady, "")
} else {
recorder.Eventf(vmCtx.VM, cond.Reason, cond.Message)
}
// Log the time when the VM changes its readiness condition.
pkglog.FromContextOrDefault(vmCtx).Info(
"VM resource readiness probe condition updated",
"condition.status", cond.Status,
"time", cond.LastTransitionTime,
"reason", cond.Reason)
}
conditions.Set(vmCtx.VM, cond)
return nil
}
func getRuntimeHostHostname(
ctx context.Context,
vcVM *object.VirtualMachine,
host *vimtypes.ManagedObjectReference) (string, error) {
if host != nil {
return object.NewHostSystem(vcVM.Client(), *host).ObjectName(ctx)
}
return "", nil
}
func guestNicInfoToInterfaceStatus(
name string,
deviceKey int32,
guestNicInfo *vimtypes.GuestNicInfo) vmopv1.VirtualMachineNetworkInterfaceStatus {
status := vmopv1.VirtualMachineNetworkInterfaceStatus{
Name: name,
DeviceKey: deviceKey,
}
if guestNicInfo.MacAddress != "" {
status.IP = &vmopv1.VirtualMachineNetworkInterfaceIPStatus{
MACAddr: guestNicInfo.MacAddress,
}
}
if guestIPConfig := guestNicInfo.IpConfig; guestIPConfig != nil {
if status.IP == nil {
status.IP = &vmopv1.VirtualMachineNetworkInterfaceIPStatus{}
}
status.IP.AutoConfigurationEnabled = guestIPConfig.AutoConfigurationEnabled
status.IP.Addresses = convertNetIPConfigInfoIPAddresses(guestIPConfig.IpAddress)
if guestIPConfig.Dhcp != nil {
status.IP.DHCP = convertNetDhcpConfigInfo(guestIPConfig.Dhcp)
}
}
if dnsConfig := guestNicInfo.DnsConfig; dnsConfig != nil {
status.DNS = convertNetDNSConfigInfo(dnsConfig)
}
return status
}
func guestIPStackInfoToIPStackStatus(guestIPStack *vimtypes.GuestStackInfo) vmopv1.VirtualMachineNetworkIPStackStatus {
status := vmopv1.VirtualMachineNetworkIPStackStatus{}
if dhcpConfig := guestIPStack.DhcpConfig; dhcpConfig != nil {
status.DHCP = convertNetDhcpConfigInfo(dhcpConfig)
}
if dnsConfig := guestIPStack.DnsConfig; dnsConfig != nil {
status.DNS = convertNetDNSConfigInfo(dnsConfig)
}
if ipRouteConfig := guestIPStack.IpRouteConfig; ipRouteConfig != nil {
status.IPRoutes = convertNetIPRouteConfigInfo(ipRouteConfig)
}
status.KernelConfig = convertKeyValueSlice(guestIPStack.IpStackConfig)
return status
}
func convertNetIPConfigInfoIPAddresses(ipAddresses []vimtypes.NetIpConfigInfoIpAddress) []vmopv1.VirtualMachineNetworkInterfaceIPAddrStatus {
if len(ipAddresses) == 0 {
return nil
}
out := make([]vmopv1.VirtualMachineNetworkInterfaceIPAddrStatus, 0, len(ipAddresses))
for _, guestIPAddr := range ipAddresses {
ipAddrStatus := vmopv1.VirtualMachineNetworkInterfaceIPAddrStatus{
Address: guestIPAddr.IpAddress,
Origin: guestIPAddr.Origin,
State: guestIPAddr.State,
}
if guestIPAddr.Lifetime != nil {
ipAddrStatus.Lifetime = metav1.NewTime(*guestIPAddr.Lifetime)
}
out = append(out, ipAddrStatus)
}
return out
}
func convertNetDNSConfigInfo(dnsConfig *vimtypes.NetDnsConfigInfo) *vmopv1.VirtualMachineNetworkDNSStatus {
return &vmopv1.VirtualMachineNetworkDNSStatus{
DHCP: dnsConfig.Dhcp,
DomainName: dnsConfig.DomainName,
HostName: dnsConfig.HostName,
Nameservers: pkgutil.Dedupe(dnsConfig.IpAddress),
SearchDomains: pkgutil.Dedupe(dnsConfig.SearchDomain),
}
}
func convertNetDhcpConfigInfo(dhcpConfig *vimtypes.NetDhcpConfigInfo) *vmopv1.VirtualMachineNetworkDHCPStatus {
if ipv4, ipv6 := dhcpConfig.Ipv4, dhcpConfig.Ipv6; ipv4 != nil || ipv6 != nil {
status := &vmopv1.VirtualMachineNetworkDHCPStatus{}
if ipv4 != nil {
status.IP4.Enabled = ipv4.Enable
status.IP4.Config = convertKeyValueSlice(ipv4.Config)
}
if ipv6 != nil {
status.IP6.Enabled = ipv6.Enable
status.IP6.Config = convertKeyValueSlice(ipv6.Config)
}
return status
}
return nil
}
func convertNetIPRouteConfigInfo(routeConfig *vimtypes.NetIpRouteConfigInfo) []vmopv1.VirtualMachineNetworkIPRouteStatus {
if len(routeConfig.IpRoute) == 0 {
return nil
}
// Try to skip routes that are likely not interesting or useful to external users - especially on
// TKG nodes - that would otherwise just clutter the Status output.
skipRoute := func(ipRoute vimtypes.NetIpRouteConfigInfoIpRoute) bool {
network, prefix := ipRoute.Network, ipRoute.PrefixLength
ip := net.ParseIP(network)
if ip == nil {
return true
}
if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
return true
}
if ip.To4() != nil {
return prefix == 32
}
return ip.To16() == nil || ip.IsInterfaceLocalMulticast() || ip.IsMulticast()
}
out := make([]vmopv1.VirtualMachineNetworkIPRouteStatus, 0, 1)
for _, ipRoute := range routeConfig.IpRoute {
if skipRoute(ipRoute) {
continue
}
out = append(out, vmopv1.VirtualMachineNetworkIPRouteStatus{
Gateway: vmopv1.VirtualMachineNetworkIPRouteGatewayStatus{
Device: ipRoute.Gateway.Device,
Address: ipRoute.Gateway.IpAddress,
},
NetworkAddress: fmt.Sprintf("%s/%d", ipRoute.Network, ipRoute.PrefixLength),
})
}
return out
}
func convertKeyValueSlice(s []vimtypes.KeyValue) []common.KeyValuePair {
if len(s) == 0 {
return nil
}
out := make([]common.KeyValuePair, 0, len(s))
for i := range s {
out = append(out, common.KeyValuePair{Key: s[i].Key, Value: s[i].Value})
}
return out
}
func MarkVMToolsRunningStatusCondition(
vm *vmopv1.VirtualMachine,
guestInfo *vimtypes.GuestInfo) {
if guestInfo == nil || guestInfo.ToolsRunningStatus == "" {
conditions.MarkUnknown(vm, vmopv1.VirtualMachineToolsCondition, "NoGuestInfo", "")
return
}
switch guestInfo.ToolsRunningStatus {
case string(vimtypes.VirtualMachineToolsRunningStatusGuestToolsNotRunning):
conditions.MarkFalse(vm, vmopv1.VirtualMachineToolsCondition, vmopv1.VirtualMachineToolsNotRunningReason, "VMware Tools is not running")
case string(vimtypes.VirtualMachineToolsRunningStatusGuestToolsRunning), string(vimtypes.VirtualMachineToolsRunningStatusGuestToolsExecutingScripts):
conditions.MarkTrue(vm, vmopv1.VirtualMachineToolsCondition)
default:
conditions.MarkUnknown(vm, vmopv1.VirtualMachineToolsCondition, "Unknown", "Unexpected VMware Tools running status")
}
}
func MarkCustomizationInfoCondition(vm *vmopv1.VirtualMachine, guestInfo *vimtypes.GuestInfo) {
if guestInfo == nil || guestInfo.CustomizationInfo == nil {
conditions.MarkUnknown(vm, vmopv1.GuestCustomizationCondition, "NoGuestInfo", "")
return
}
switch guestInfo.CustomizationInfo.CustomizationStatus {
case string(vimtypes.GuestInfoCustomizationStatusTOOLSDEPLOYPKG_IDLE), "":
conditions.MarkTrue(vm, vmopv1.GuestCustomizationCondition)
case string(vimtypes.GuestInfoCustomizationStatusTOOLSDEPLOYPKG_PENDING):
conditions.MarkFalse(vm, vmopv1.GuestCustomizationCondition, vmopv1.GuestCustomizationPendingReason, "")
case string(vimtypes.GuestInfoCustomizationStatusTOOLSDEPLOYPKG_RUNNING):
conditions.MarkFalse(vm, vmopv1.GuestCustomizationCondition, vmopv1.GuestCustomizationRunningReason, "")
case string(vimtypes.GuestInfoCustomizationStatusTOOLSDEPLOYPKG_SUCCEEDED):
conditions.MarkTrue(vm, vmopv1.GuestCustomizationCondition)
case string(vimtypes.GuestInfoCustomizationStatusTOOLSDEPLOYPKG_FAILED):
errorMsg := guestInfo.CustomizationInfo.ErrorMsg
if errorMsg == "" {
errorMsg = "vSphere VM Customization failed due to an unknown error."
}
conditions.MarkFalse(vm, vmopv1.GuestCustomizationCondition, vmopv1.GuestCustomizationFailedReason, "%s", errorMsg)
default:
errorMsg := guestInfo.CustomizationInfo.ErrorMsg
if errorMsg == "" {
errorMsg = "Unexpected VM Customization status"
}
conditions.MarkFalse(vm, vmopv1.GuestCustomizationCondition, "Unknown", "%s", errorMsg)
}
}
func MarkReconciliationCondition(vm *vmopv1.VirtualMachine) {
switch vm.Labels[vmopv1.PausedVMLabelKey] {
case "devops":
conditions.MarkFalse(vm, vmopv1.VirtualMachineReconcileReady, vmopv1.VirtualMachineReconcilePausedReason,
"Virtual Machine reconciliation paused by DevOps")
case "admin":
conditions.MarkFalse(vm, vmopv1.VirtualMachineReconcileReady, vmopv1.VirtualMachineReconcilePausedReason,
"Virtual Machine reconciliation paused by Admin")
case "both":
conditions.MarkFalse(vm, vmopv1.VirtualMachineReconcileReady, vmopv1.VirtualMachineReconcilePausedReason,
"Virtual Machine reconciliation paused by Admin, DevOps")
default:
conditions.MarkTrue(vm, vmopv1.VirtualMachineReconcileReady)
}
}
func MarkBootstrapCondition(
vm *vmopv1.VirtualMachine,
extraConfig map[string]string) {
status, reason, msg, ok := pkgutil.GetBootstrapConditionValues(extraConfig)
if !ok {
conditions.Delete(vm, vmopv1.GuestBootstrapCondition)
return
}
if status {
c := conditions.TrueCondition(vmopv1.GuestBootstrapCondition)
if reason != "" {
c.Reason = reason
}
c.Message = msg
conditions.Set(vm, c)
} else {
conditions.MarkFalse(vm, vmopv1.GuestBootstrapCondition, reason, "%s", msg)
}
}
func MarkVMClassConfigurationSynced(
ctx context.Context,
vm *vmopv1.VirtualMachine,
k8sClient ctrlclient.Client) {
className := vm.Spec.ClassName
if className == "" {
conditions.Delete(vm, vmopv1.VirtualMachineClassConfigurationSynced)
return
}
// NOTE: This performs the same checks as vmopv1util.ResizeNeeded() but we can't use
// just the return value of that function because we need more details, and we want
// to avoid having to fetch the class if we can.
lraName, lraUID, lraGeneration, exists := vmopv1util.GetLastResizedAnnotation(*vm)
if !exists || lraName == "" {
_, sameClassResize := vm.Annotations[vmopv1.VirtualMachineSameVMClassResizeAnnotation]
if sameClassResize {
conditions.MarkFalse(vm, vmopv1.VirtualMachineClassConfigurationSynced, "SameClassResize", "")
} else {
// Brownfield VM so just marked as synced.
conditions.MarkTrue(vm, vmopv1.VirtualMachineClassConfigurationSynced)
}
return
}
if vm.Spec.ClassName != lraName {
// Most common need resize case.
conditions.MarkFalse(vm, vmopv1.VirtualMachineClassConfigurationSynced, "ClassNameChanged", "")
return
}
// Depending on what we did in the prior session update code for this VM, we might already
// have fetched the class but the way the code is structured today, it isn't very easy for
// us to pass that to here. So just refetch it again.
//
// Note that for this situation we'll only do a resize if the SameVMClassResizeAnnotation
// is present but use this condition to inform if the class has changed and a user could
// opt-in to a resize.
vmClass := vmopv1.VirtualMachineClass{}
if err := k8sClient.Get(ctx, ctrlclient.ObjectKey{Name: className, Namespace: vm.Namespace}, &vmClass); err != nil {
if apierrors.IsNotFound(err) {
conditions.MarkUnknown(vm, vmopv1.VirtualMachineClassConfigurationSynced, "ClassNotFound", "")
} else {
conditions.MarkUnknown(vm, vmopv1.VirtualMachineClassConfigurationSynced, err.Error(), "")
}
return
}
if string(vmClass.UID) == lraUID && vmClass.Generation == lraGeneration {
conditions.MarkTrue(vm, vmopv1.VirtualMachineClassConfigurationSynced)
} else {
conditions.MarkFalse(vm, vmopv1.VirtualMachineClassConfigurationSynced, "ClassUpdated", "")
}
}
var (
emptyNetConfig vmopv1.VirtualMachineNetworkConfigStatus
emptyIfaceConfig vmopv1.VirtualMachineNetworkConfigInterfaceStatus
)
// UpdateNetworkStatusConfig updates the provided VM's status.network.config
// field with information from the provided bootstrap arguments. This is useful
// for folks booting VMs without bootstrap engines who may wish to manually
// configure the VM's networking with the valid IP configuration for this VM.
//
//nolint:gocyclo
func UpdateNetworkStatusConfig(vm *vmopv1.VirtualMachine, args BootstrapArgs) {
if vm == nil {
panic("vm is nil")
}
// Define the network configuration to update. However, it is not assigned
// to the VM's status.network.config field unless nc is non-empty before
// this function ends.
var nc vmopv1.VirtualMachineNetworkConfigStatus
// Update the global DNS information.
{
hn, dn, ns, sd := args.HostName, args.DomainName, args.DNSServers, args.SearchSuffixes
lhn, ldn, lns, lsd := len(hn) > 0, len(dn) > 0, len(ns) > 0, len(sd) > 0
if lhn || ldn || lns || lsd {
nc.DNS = &vmopv1.VirtualMachineNetworkConfigDNSStatus{}
if lhn {
nc.DNS.HostName = hn
}
if ldn {
nc.DNS.DomainName = dn
}
if lns {
nc.DNS.Nameservers = ns
}
if lsd {
nc.DNS.SearchDomains = sd
}
}
}
// Iterate over each network result.
for i := range args.NetworkResults.Results {
// Declare the interface's config status.
var ifc vmopv1.VirtualMachineNetworkConfigInterfaceStatus
// Define a short alias for the indexed result.
r := args.NetworkResults.Results[i]
// Grab a temp copy of the result's IP configuration list to make it
// more obvious that the purpose of the next three lines of code is not
// to update the r.IPConfigs directly.
ipConfigs := args.NetworkResults.Results[i].IPConfigs
// The intended DHCP configuration is presented per interface, so if
// there are no resulting IP configs, but DHCP4 or DHCP6 is configured,
// go ahead and create a single, fake IP config so the DHCP info can be
// collected the same way below.
if len(ipConfigs) == 0 && (r.DHCP4 || r.DHCP6) {
ipConfigs = []network.NetworkInterfaceIPConfig{{}}
}
// If there *are* resulting IP configs, then ensure the field ifc.IP
// is not nil so avoid an NPE later. We do not initialize this field
// unless there *are* resulting IP configs to avoid an empty object
// when printing the VM's status.
if len(ipConfigs) > 0 {
ifc.IP = &vmopv1.VirtualMachineNetworkConfigInterfaceIPStatus{}
}
// Iterate over each of the result's IP configurations.
for j := range ipConfigs {
ipc := ipConfigs[j]
// Assign the gateways.
if gw := ipc.Gateway; gw != "" {
if ipc.IsIPv4 && ifc.IP.Gateway4 == "" {
ifc.IP.Gateway4 = gw
} else if !ipc.IsIPv4 && ifc.IP.Gateway6 == "" {
ifc.IP.Gateway6 = gw
}
}
// Append the IP address.
if ip := ipc.IPCIDR; ip != "" {
ifc.IP.Addresses = append(ifc.IP.Addresses, ip)
}
// Update DHCP information.
if v4, v6 := r.DHCP4, r.DHCP6; v4 || v6 {
ifc.IP.DHCP = &vmopv1.VirtualMachineNetworkConfigDHCPStatus{}
if v4 {
ifc.IP.DHCP.IP4 = &vmopv1.VirtualMachineNetworkConfigDHCPOptionsStatus{
Enabled: v4,
}
}
if v6 {
ifc.IP.DHCP.IP6 = &vmopv1.VirtualMachineNetworkConfigDHCPOptionsStatus{
Enabled: v6,
}
}
}
// Update DNS information.
{
ns, sd := r.Nameservers, r.SearchDomains
if ln, ls := len(ns), len(sd); ln > 0 || ls > 0 {
ifc.DNS = &vmopv1.VirtualMachineNetworkConfigDNSStatus{}
if ln > 0 {
ifc.DNS.Nameservers = ns
}
if ls > 0 {
ifc.DNS.SearchDomains = sd
}
}
}
}
if ip := ifc.IP; ip != nil && len(ip.Addresses) > 0 {
slices.Sort(ifc.IP.Addresses)
}
// Only append the interface config if it is not empty.
if !reflect.DeepEqual(ifc, emptyIfaceConfig) {
// Do not assign the name until the very end so as to not disrupt
// the comparison with the empty struct.
ifc.Name = r.Name
nc.Interfaces = append(nc.Interfaces, ifc)
}
}
// If the network config ended up empty, then ensure the VM's field
// status.network.config is nil IFF status.network is non-nil.
// Otherwise, assign the network config to the VM's status.network.config