/
template.go
1468 lines (1294 loc) · 49.6 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the KubeVirt project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2017, 2018 Red Hat, Inc.
*
*/
package services
import (
"fmt"
"math/rand"
"strconv"
"strings"
networkv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/cache"
"k8s.io/kubectl/pkg/cmd/util/podcmd"
"k8s.io/utils/pointer"
v1 "kubevirt.io/api/core/v1"
exportv1 "kubevirt.io/api/export/v1alpha1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/client-go/log"
"kubevirt.io/client-go/precond"
containerdisk "kubevirt.io/kubevirt/pkg/container-disk"
"kubevirt.io/kubevirt/pkg/hooks"
"kubevirt.io/kubevirt/pkg/network/istio"
"kubevirt.io/kubevirt/pkg/network/namescheme"
"kubevirt.io/kubevirt/pkg/network/vmispec"
"kubevirt.io/kubevirt/pkg/storage/reservation"
"kubevirt.io/kubevirt/pkg/storage/types"
"kubevirt.io/kubevirt/pkg/util"
"kubevirt.io/kubevirt/pkg/util/net/dns"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
"kubevirt.io/kubevirt/pkg/virt-controller/watch/topology"
"kubevirt.io/kubevirt/pkg/virt-launcher/virtwrap/api"
)
const (
containerDisks = "container-disks"
hotplugDisks = "hotplug-disks"
hookSidecarSocks = "hook-sidecar-sockets"
varRun = "/var/run"
virtBinDir = "virt-bin-share-dir"
hotplugDisk = "hotplug-disk"
virtExporter = "virt-exporter"
)
const KvmDevice = "devices.kubevirt.io/kvm"
const TunDevice = "devices.kubevirt.io/tun"
const VhostNetDevice = "devices.kubevirt.io/vhost-net"
const SevDevice = "devices.kubevirt.io/sev"
const VhostVsockDevice = "devices.kubevirt.io/vhost-vsock"
const PrDevice = "devices.kubevirt.io/pr-helper"
const debugLogs = "debugLogs"
const logVerbosity = "logVerbosity"
const virtiofsDebugLogs = "virtiofsdDebugLogs"
const MultusNetworksAnnotation = "k8s.v1.cni.cncf.io/networks"
const qemuTimeoutJitterRange = 120
const (
CAP_NET_BIND_SERVICE = "NET_BIND_SERVICE"
CAP_NET_RAW = "NET_RAW"
CAP_SYS_NICE = "SYS_NICE"
)
// LibvirtStartupDelay is added to custom liveness and readiness probes initial delay value.
// Libvirt needs roughly 10 seconds to start.
const LibvirtStartupDelay = 10
// These perfixes for node feature discovery, are used in a NodeSelector on the pod
// to match a VirtualMachineInstance CPU model(Family) and/or features to nodes that support them.
const NFD_CPU_MODEL_PREFIX = "cpu-model.node.kubevirt.io/"
const NFD_CPU_FEATURE_PREFIX = "cpu-feature.node.kubevirt.io/"
const NFD_KVM_INFO_PREFIX = "hyperv.node.kubevirt.io/"
const IntelVendorName = "Intel"
const MULTUS_RESOURCE_NAME_ANNOTATION = "k8s.v1.cni.cncf.io/resourceName"
const MULTUS_DEFAULT_NETWORK_CNI_ANNOTATION = "v1.multus-cni.io/default-network"
// Istio list of virtual interfaces whose inbound traffic (from VM) will be treated as outbound traffic in envoy
const ISTIO_KUBEVIRT_ANNOTATION = "traffic.sidecar.istio.io/kubevirtInterfaces"
const VELERO_PREBACKUP_HOOK_CONTAINER_ANNOTATION = "pre.hook.backup.velero.io/container"
const VELERO_PREBACKUP_HOOK_COMMAND_ANNOTATION = "pre.hook.backup.velero.io/command"
const VELERO_POSTBACKUP_HOOK_CONTAINER_ANNOTATION = "post.hook.backup.velero.io/container"
const VELERO_POSTBACKUP_HOOK_COMMAND_ANNOTATION = "post.hook.backup.velero.io/command"
const ENV_VAR_LIBVIRT_DEBUG_LOGS = "LIBVIRT_DEBUG_LOGS"
const ENV_VAR_VIRTIOFSD_DEBUG_LOGS = "VIRTIOFSD_DEBUG_LOGS"
const ENV_VAR_VIRT_LAUNCHER_LOG_VERBOSITY = "VIRT_LAUNCHER_LOG_VERBOSITY"
const ENV_VAR_POD_NAME = "POD_NAME"
// extensive log verbosity threshold after which libvirt debug logs will be enabled
const EXT_LOG_VERBOSITY_THRESHOLD = 5
const ephemeralStorageOverheadSize = "50M"
const (
VirtLauncherMonitorOverhead = "25Mi" // The `ps` RSS for virt-launcher-monitor
VirtLauncherOverhead = "100Mi" // The `ps` RSS for the virt-launcher process
VirtlogdOverhead = "20Mi" // The `ps` RSS for virtlogd
VirtqemudOverhead = "35Mi" // The `ps` RSS for virtqemud
QemuOverhead = "30Mi" // The `ps` RSS for qemu, minus the RAM of its (stressed) guest, minus the virtual page table
// Default: limits.memory = 2*requests.memory
DefaultMemoryLimitOverheadRatio = float64(2.0)
)
const customSELinuxType = "virt_launcher.process"
type TemplateService interface {
RenderMigrationManifest(vmi *v1.VirtualMachineInstance, sourcePod *k8sv1.Pod) (*k8sv1.Pod, error)
RenderLaunchManifest(vmi *v1.VirtualMachineInstance) (*k8sv1.Pod, error)
RenderHotplugAttachmentPodTemplate(volume []*v1.Volume, ownerPod *k8sv1.Pod, vmi *v1.VirtualMachineInstance, claimMap map[string]*k8sv1.PersistentVolumeClaim, tempPod bool) (*k8sv1.Pod, error)
RenderHotplugAttachmentTriggerPodTemplate(volume *v1.Volume, ownerPod *k8sv1.Pod, vmi *v1.VirtualMachineInstance, pvcName string, isBlock bool, tempPod bool) (*k8sv1.Pod, error)
RenderLaunchManifestNoVm(*v1.VirtualMachineInstance) (*k8sv1.Pod, error)
RenderExporterManifest(vmExport *exportv1.VirtualMachineExport, namePrefix string) *k8sv1.Pod
GetLauncherImage() string
IsPPC64() bool
IsARM64() bool
}
type templateService struct {
launcherImage string
exporterImage string
launcherQemuTimeout int
virtShareDir string
virtLibDir string
ephemeralDiskDir string
containerDiskDir string
hotplugDiskDir string
imagePullSecret string
persistentVolumeClaimStore cache.Store
virtClient kubecli.KubevirtClient
clusterConfig *virtconfig.ClusterConfig
launcherSubGid int64
resourceQuotaStore cache.Store
namespaceStore cache.Store
sidecarCreators []SidecarCreatorFunc
}
func isFeatureStateEnabled(fs *v1.FeatureState) bool {
return fs != nil && fs.Enabled != nil && *fs.Enabled
}
func setNodeAffinityForPod(vmi *v1.VirtualMachineInstance, pod *k8sv1.Pod) {
setNodeAffinityForHostModelCpuModel(vmi, pod)
setNodeAffinityForbiddenFeaturePolicy(vmi, pod)
}
func setNodeAffinityForHostModelCpuModel(vmi *v1.VirtualMachineInstance, pod *k8sv1.Pod) {
if vmi.Spec.Domain.CPU == nil || vmi.Spec.Domain.CPU.Model == "" || vmi.Spec.Domain.CPU.Model == v1.CPUModeHostModel {
pod.Spec.Affinity = modifyNodeAffintyToRejectLabel(pod.Spec.Affinity, v1.NodeHostModelIsObsoleteLabel)
}
}
func setNodeAffinityForbiddenFeaturePolicy(vmi *v1.VirtualMachineInstance, pod *k8sv1.Pod) {
if vmi.Spec.Domain.CPU == nil || vmi.Spec.Domain.CPU.Features == nil {
return
}
for _, feature := range vmi.Spec.Domain.CPU.Features {
if feature.Policy == "forbid" {
pod.Spec.Affinity = modifyNodeAffintyToRejectLabel(pod.Spec.Affinity, NFD_CPU_FEATURE_PREFIX+feature.Name)
}
}
}
func modifyNodeAffintyToRejectLabel(origAffinity *k8sv1.Affinity, labelToReject string) *k8sv1.Affinity {
affinity := origAffinity.DeepCopy()
requirement := k8sv1.NodeSelectorRequirement{
Key: labelToReject,
Operator: k8sv1.NodeSelectorOpDoesNotExist,
}
term := k8sv1.NodeSelectorTerm{
MatchExpressions: []k8sv1.NodeSelectorRequirement{requirement}}
nodeAffinity := &k8sv1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &k8sv1.NodeSelector{
NodeSelectorTerms: []k8sv1.NodeSelectorTerm{term},
},
}
if affinity != nil && affinity.NodeAffinity != nil {
if affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {
terms := affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms
// Since NodeSelectorTerms are ORed , the anti affinity requirement will be added to each term.
for i, selectorTerm := range terms {
affinity.NodeAffinity.
RequiredDuringSchedulingIgnoredDuringExecution.
NodeSelectorTerms[i].MatchExpressions = append(selectorTerm.MatchExpressions, requirement)
}
} else {
affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = &k8sv1.NodeSelector{
NodeSelectorTerms: []k8sv1.NodeSelectorTerm{term},
}
}
} else if affinity != nil {
affinity.NodeAffinity = nodeAffinity
} else {
affinity = &k8sv1.Affinity{
NodeAffinity: nodeAffinity,
}
}
return affinity
}
func sysprepVolumeSource(sysprepVolume v1.SysprepSource) (k8sv1.VolumeSource, error) {
logger := log.DefaultLogger()
if sysprepVolume.Secret != nil {
return k8sv1.VolumeSource{
Secret: &k8sv1.SecretVolumeSource{
SecretName: sysprepVolume.Secret.Name,
},
}, nil
} else if sysprepVolume.ConfigMap != nil {
return k8sv1.VolumeSource{
ConfigMap: &k8sv1.ConfigMapVolumeSource{
LocalObjectReference: k8sv1.LocalObjectReference{
Name: sysprepVolume.ConfigMap.Name,
},
},
}, nil
}
errorStr := fmt.Sprintf("Sysprep must have Secret or ConfigMap reference set %v", sysprepVolume)
logger.Errorf(errorStr)
return k8sv1.VolumeSource{}, fmt.Errorf(errorStr)
}
func (t *templateService) GetLauncherImage() string {
return t.launcherImage
}
func (t *templateService) RenderLaunchManifestNoVm(vmi *v1.VirtualMachineInstance) (*k8sv1.Pod, error) {
return t.renderLaunchManifest(vmi, nil, true)
}
func (t *templateService) RenderMigrationManifest(vmi *v1.VirtualMachineInstance, pod *k8sv1.Pod) (*k8sv1.Pod, error) {
reproducibleImageIDs, err := containerdisk.ExtractImageIDsFromSourcePod(vmi, pod)
if err != nil {
return nil, fmt.Errorf("can not proceed with the migration when no reproducible image digest can be detected: %v", err)
}
podManifest, err := t.renderLaunchManifest(vmi, reproducibleImageIDs, false)
if err != nil {
return nil, err
}
if namescheme.PodHasOrdinalInterfaceName(NonDefaultMultusNetworksIndexedByIfaceName(pod)) {
ordinalNameScheme := namescheme.CreateOrdinalNetworkNameScheme(vmi.Spec.Networks)
multusNetworksAnnotation, err := GenerateMultusCNIAnnotationFromNameScheme(
vmi.Namespace, vmi.Spec.Domain.Devices.Interfaces, vmi.Spec.Networks, ordinalNameScheme, t.clusterConfig)
if err != nil {
return nil, err
}
podManifest.Annotations[networkv1.NetworkAttachmentAnnot] = multusNetworksAnnotation
}
return podManifest, err
}
func (t *templateService) RenderLaunchManifest(vmi *v1.VirtualMachineInstance) (*k8sv1.Pod, error) {
return t.renderLaunchManifest(vmi, nil, false)
}
func (t *templateService) IsPPC64() bool {
return t.clusterConfig.GetClusterCPUArch() == "ppc64le"
}
func (t *templateService) IsARM64() bool {
return t.clusterConfig.GetClusterCPUArch() == "arm64"
}
func generateQemuTimeoutWithJitter(qemuTimeoutBaseSeconds int) string {
timeout := rand.Intn(qemuTimeoutJitterRange) + qemuTimeoutBaseSeconds
return fmt.Sprintf("%ds", timeout)
}
func computePodSecurityContext(vmi *v1.VirtualMachineInstance, seccomp *k8sv1.SeccompProfile) *k8sv1.PodSecurityContext {
psc := &k8sv1.PodSecurityContext{}
if util.IsNonRootVMI(vmi) {
nonRootUser := int64(util.NonRootUID)
psc.RunAsUser = &nonRootUser
psc.RunAsGroup = &nonRootUser
psc.RunAsNonRoot = pointer.Bool(true)
psc.FSGroup = &nonRootUser
} else {
rootUser := int64(util.RootUser)
psc.RunAsUser = &rootUser
}
psc.SeccompProfile = seccomp
return psc
}
func (t *templateService) renderLaunchManifest(vmi *v1.VirtualMachineInstance, imageIDs map[string]string, tempPod bool) (*k8sv1.Pod, error) {
precond.MustNotBeNil(vmi)
domain := precond.MustNotBeEmpty(vmi.GetObjectMeta().GetName())
namespace := precond.MustNotBeEmpty(vmi.GetObjectMeta().GetNamespace())
var userId int64 = util.RootUser
nonRoot := util.IsNonRootVMI(vmi)
if nonRoot {
userId = util.NonRootUID
}
gracePeriodSeconds := gracePeriodInSeconds(vmi)
imagePullSecrets := imgPullSecrets(vmi.Spec.Volumes...)
if t.imagePullSecret != "" {
imagePullSecrets = appendUniqueImagePullSecret(imagePullSecrets, k8sv1.LocalObjectReference{
Name: t.imagePullSecret,
})
}
// Pad the virt-launcher grace period.
// Ideally we want virt-handler to handle tearing down
// the vmi without virt-launcher's termination forcing
// the vmi down.
gracePeriodSeconds = gracePeriodSeconds + int64(15)
gracePeriodKillAfter := gracePeriodSeconds + int64(15)
networkToResourceMap, err := getNetworkToResourceMap(t.virtClient, vmi)
if err != nil {
return nil, err
}
resourceRenderer, err := t.newResourceRenderer(vmi, networkToResourceMap)
if err != nil {
return nil, err
}
resources := resourceRenderer.ResourceRequirements()
ovmfPath := t.clusterConfig.GetOVMFPath(vmi.Spec.Architecture)
var requestedHookSidecarList hooks.HookSidecarList
for _, sidecarCreator := range t.sidecarCreators {
sidecars, err := sidecarCreator(vmi, t.clusterConfig.GetConfig())
if err != nil {
return nil, err
}
requestedHookSidecarList = append(requestedHookSidecarList, sidecars...)
}
var command []string
if tempPod {
logger := log.DefaultLogger()
logger.Infof("RUNNING doppleganger pod for %s", vmi.Name)
command = []string{"/bin/bash",
"-c",
"echo", "bound PVCs"}
} else {
command = []string{"/usr/bin/virt-launcher-monitor",
"--qemu-timeout", generateQemuTimeoutWithJitter(t.launcherQemuTimeout),
"--name", domain,
"--uid", string(vmi.UID),
"--namespace", namespace,
"--kubevirt-share-dir", t.virtShareDir,
"--ephemeral-disk-dir", t.ephemeralDiskDir,
"--container-disk-dir", t.containerDiskDir,
"--grace-period-seconds", strconv.Itoa(int(gracePeriodSeconds)),
"--hook-sidecars", strconv.Itoa(len(requestedHookSidecarList)),
"--ovmf-path", ovmfPath,
}
if nonRoot {
command = append(command, "--run-as-nonroot")
}
if customDebugFilters, exists := vmi.Annotations[v1.CustomLibvirtLogFiltersAnnotation]; exists {
log.Log.Object(vmi).Infof("Applying custom debug filters for vmi %s: %s", vmi.Name, customDebugFilters)
command = append(command, "--libvirt-log-filters", customDebugFilters)
}
}
if t.clusterConfig.AllowEmulation() {
command = append(command, "--allow-emulation")
}
if checkForKeepLauncherAfterFailure(vmi) {
command = append(command, "--keep-after-failure")
}
_, ok := vmi.Annotations[v1.FuncTestLauncherFailFastAnnotation]
if ok {
command = append(command, "--simulate-crash")
}
volumeRenderer, err := t.newVolumeRenderer(vmi, namespace, requestedHookSidecarList)
if err != nil {
return nil, err
}
compute := t.newContainerSpecRenderer(vmi, volumeRenderer, resources, userId).Render(command)
for networkName, resourceName := range networkToResourceMap {
varName := fmt.Sprintf("KUBEVIRT_RESOURCE_NAME_%s", networkName)
compute.Env = append(compute.Env, k8sv1.EnvVar{Name: varName, Value: resourceName})
}
virtLauncherLogVerbosity := t.clusterConfig.GetVirtLauncherVerbosity()
if verbosity, isSet := vmi.Labels[logVerbosity]; isSet || virtLauncherLogVerbosity != virtconfig.DefaultVirtLauncherLogVerbosity {
// Override the cluster wide verbosity level if a specific value has been provided for this VMI
verbosityStr := fmt.Sprint(virtLauncherLogVerbosity)
if isSet {
verbosityStr = verbosity
verbosityInt, err := strconv.Atoi(verbosity)
if err != nil {
return nil, fmt.Errorf("verbosity %s cannot cast to int: %v", verbosity, err)
}
virtLauncherLogVerbosity = uint(verbosityInt)
}
compute.Env = append(compute.Env, k8sv1.EnvVar{Name: ENV_VAR_VIRT_LAUNCHER_LOG_VERBOSITY, Value: verbosityStr})
}
if labelValue, ok := vmi.Labels[debugLogs]; (ok && strings.EqualFold(labelValue, "true")) || virtLauncherLogVerbosity > EXT_LOG_VERBOSITY_THRESHOLD {
compute.Env = append(compute.Env, k8sv1.EnvVar{Name: ENV_VAR_LIBVIRT_DEBUG_LOGS, Value: "1"})
}
if labelValue, ok := vmi.Labels[virtiofsDebugLogs]; (ok && strings.EqualFold(labelValue, "true")) || virtLauncherLogVerbosity > EXT_LOG_VERBOSITY_THRESHOLD {
compute.Env = append(compute.Env, k8sv1.EnvVar{Name: ENV_VAR_VIRTIOFSD_DEBUG_LOGS, Value: "1"})
}
compute.Env = append(compute.Env, k8sv1.EnvVar{
Name: ENV_VAR_POD_NAME,
ValueFrom: &k8sv1.EnvVarSource{
FieldRef: &k8sv1.ObjectFieldSelector{
FieldPath: "metadata.name",
},
},
})
// Make sure the compute container is always the first since the mutating webhook shipped with the sriov operator
// for adding the requested resources to the pod will add them to the first container of the list
containers := []k8sv1.Container{compute}
containersDisks := containerdisk.GenerateContainers(vmi, t.clusterConfig, imageIDs, containerDisks, virtBinDir)
containers = append(containers, containersDisks...)
kernelBootContainer := containerdisk.GenerateKernelBootContainer(vmi, t.clusterConfig, imageIDs, containerDisks, virtBinDir)
if kernelBootContainer != nil {
log.Log.Object(vmi).Infof("kernel boot container generated")
containers = append(containers, *kernelBootContainer)
}
virtiofsContainers := generateVirtioFSContainers(vmi, t.launcherImage, t.clusterConfig)
if virtiofsContainers != nil {
containers = append(containers, virtiofsContainers...)
}
sconsolelogContainer := generateSerialConsoleLogContainer(vmi, t.launcherImage, t.clusterConfig, virtLauncherLogVerbosity)
if sconsolelogContainer != nil {
containers = append(containers, *sconsolelogContainer)
}
for i, requestedHookSidecar := range requestedHookSidecarList {
containers = append(
containers,
newSidecarContainerRenderer(
sidecarContainerName(i), vmi, sidecarResources(vmi, t.clusterConfig), requestedHookSidecar, userId).Render(requestedHookSidecar.Command))
}
podAnnotations, err := generatePodAnnotations(vmi, t.clusterConfig)
if err != nil {
return nil, err
}
if tempPod {
// mark pod as temp - only used for provisioning
podAnnotations[v1.EphemeralProvisioningObject] = "true"
}
var initContainers []k8sv1.Container
if HaveContainerDiskVolume(vmi.Spec.Volumes) || util.HasKernelBootContainerImage(vmi) {
initContainerCommand := []string{"/usr/bin/cp",
"/usr/bin/container-disk",
"/init/usr/bin/container-disk",
}
initContainers = append(
initContainers,
t.newInitContainerRenderer(vmi,
initContainerVolumeMount(),
initContainerResourceRequirementsForVMI(vmi, v1.ContainerDisk, t.clusterConfig),
userId).Render(initContainerCommand))
// this causes containerDisks to be pre-pulled before virt-launcher starts.
initContainers = append(initContainers, containerdisk.GenerateInitContainers(vmi, t.clusterConfig, imageIDs, containerDisks, virtBinDir)...)
kernelBootInitContainer := containerdisk.GenerateKernelBootInitContainer(vmi, t.clusterConfig, imageIDs, containerDisks, virtBinDir)
if kernelBootInitContainer != nil {
initContainers = append(initContainers, *kernelBootInitContainer)
}
}
hostName := dns.SanitizeHostname(vmi)
enableServiceLinks := false
var podSeccompProfile *k8sv1.SeccompProfile = nil
if seccompConf := t.clusterConfig.GetConfig().SeccompConfiguration; seccompConf != nil && seccompConf.VirtualMachineInstanceProfile != nil {
vmProfile := seccompConf.VirtualMachineInstanceProfile
if customProfile := vmProfile.CustomProfile; customProfile != nil {
if customProfile.LocalhostProfile != nil {
podSeccompProfile = &k8sv1.SeccompProfile{
Type: k8sv1.SeccompProfileTypeLocalhost,
LocalhostProfile: customProfile.LocalhostProfile,
}
} else if customProfile.RuntimeDefaultProfile {
podSeccompProfile = &k8sv1.SeccompProfile{
Type: k8sv1.SeccompProfileTypeRuntimeDefault,
}
}
}
}
pod := k8sv1.Pod{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "virt-launcher-" + domain + "-",
Labels: podLabels(vmi, hostName),
Annotations: podAnnotations,
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(vmi, v1.VirtualMachineInstanceGroupVersionKind),
},
},
Spec: k8sv1.PodSpec{
Hostname: hostName,
Subdomain: vmi.Spec.Subdomain,
SecurityContext: computePodSecurityContext(vmi, podSeccompProfile),
TerminationGracePeriodSeconds: &gracePeriodKillAfter,
RestartPolicy: k8sv1.RestartPolicyNever,
Containers: containers,
InitContainers: initContainers,
NodeSelector: t.newNodeSelectorRenderer(vmi).Render(),
Volumes: volumeRenderer.Volumes(),
ImagePullSecrets: imagePullSecrets,
DNSConfig: vmi.Spec.DNSConfig,
DNSPolicy: vmi.Spec.DNSPolicy,
ReadinessGates: readinessGates(),
EnableServiceLinks: &enableServiceLinks,
SchedulerName: vmi.Spec.SchedulerName,
Tolerations: vmi.Spec.Tolerations,
TopologySpreadConstraints: vmi.Spec.TopologySpreadConstraints,
},
}
alignPodMultiCategorySecurity(&pod, vmi, t.clusterConfig.GetSELinuxLauncherType(), t.clusterConfig.DockerSELinuxMCSWorkaroundEnabled(), t.clusterConfig.CustomSELinuxPolicyDisabled())
// If we have a runtime class specified, use it, otherwise don't set a runtimeClassName
runtimeClassName := t.clusterConfig.GetDefaultRuntimeClass()
if runtimeClassName != "" {
pod.Spec.RuntimeClassName = &runtimeClassName
}
if vmi.Spec.PriorityClassName != "" {
pod.Spec.PriorityClassName = vmi.Spec.PriorityClassName
}
if vmi.Spec.Affinity != nil {
pod.Spec.Affinity = vmi.Spec.Affinity.DeepCopy()
}
setNodeAffinityForPod(vmi, &pod)
serviceAccountName := serviceAccount(vmi.Spec.Volumes...)
if len(serviceAccountName) > 0 {
pod.Spec.ServiceAccountName = serviceAccountName
automount := true
pod.Spec.AutomountServiceAccountToken = &automount
} else if istio.ProxyInjectionEnabled(vmi) {
automount := true
pod.Spec.AutomountServiceAccountToken = &automount
} else {
automount := false
pod.Spec.AutomountServiceAccountToken = &automount
}
return &pod, nil
}
func (t *templateService) newNodeSelectorRenderer(vmi *v1.VirtualMachineInstance) *NodeSelectorRenderer {
var opts []NodeSelectorRendererOption
if vmi.IsCPUDedicated() {
opts = append(opts, WithDedicatedCPU())
}
if t.clusterConfig.HypervStrictCheckEnabled() {
opts = append(opts, WithHyperv(vmi.Spec.Domain.Features))
}
if modelLabel, err := CPUModelLabelFromCPUModel(vmi); err == nil {
opts = append(
opts,
WithModelAndFeatureLabels(modelLabel, CPUFeatureLabelsFromCPUFeatures(vmi)...),
)
}
if topology.IsManualTSCFrequencyRequired(vmi) {
opts = append(opts, WithTSCTimer(vmi.Status.TopologyHints.TSCFrequency))
}
return NewNodeSelectorRenderer(
vmi.Spec.NodeSelector,
t.clusterConfig.GetNodeSelectors(),
vmi.Spec.Architecture,
opts...,
)
}
func initContainerVolumeMount() k8sv1.VolumeMount {
return k8sv1.VolumeMount{
Name: virtBinDir,
MountPath: "/init/usr/bin",
}
}
func newSidecarContainerRenderer(sidecarName string, vmiSpec *v1.VirtualMachineInstance, resources k8sv1.ResourceRequirements, requestedHookSidecar hooks.HookSidecar, userId int64) *ContainerSpecRenderer {
sidecarOpts := []Option{
WithResourceRequirements(resources),
WithVolumeMounts(sidecarVolumeMount()),
WithArgs(requestedHookSidecar.Args),
}
if util.IsNonRootVMI(vmiSpec) {
sidecarOpts = append(sidecarOpts, WithNonRoot(userId))
sidecarOpts = append(sidecarOpts, WithDropALLCapabilities())
}
return NewContainerSpecRenderer(
sidecarName,
requestedHookSidecar.Image,
requestedHookSidecar.ImagePullPolicy,
sidecarOpts...)
}
func (t *templateService) newInitContainerRenderer(vmiSpec *v1.VirtualMachineInstance, initContainerVolumeMount k8sv1.VolumeMount, initContainerResources k8sv1.ResourceRequirements, userId int64) *ContainerSpecRenderer {
const containerDisk = "container-disk-binary"
cpInitContainerOpts := []Option{
WithVolumeMounts(initContainerVolumeMount),
WithResourceRequirements(initContainerResources),
WithNoCapabilities(),
}
if util.IsNonRootVMI(vmiSpec) {
cpInitContainerOpts = append(cpInitContainerOpts, WithNonRoot(userId))
}
if t.IsPPC64() {
cpInitContainerOpts = append(cpInitContainerOpts, WithPrivileged())
}
return NewContainerSpecRenderer(containerDisk, t.launcherImage, t.clusterConfig.GetImagePullPolicy(), cpInitContainerOpts...)
}
func (t *templateService) newContainerSpecRenderer(vmi *v1.VirtualMachineInstance, volumeRenderer *VolumeRenderer, resources k8sv1.ResourceRequirements, userId int64) *ContainerSpecRenderer {
computeContainerOpts := []Option{
WithVolumeDevices(volumeRenderer.VolumeDevices()...),
WithVolumeMounts(volumeRenderer.Mounts()...),
WithResourceRequirements(resources),
WithPorts(vmi),
WithCapabilities(vmi),
}
if util.IsNonRootVMI(vmi) {
computeContainerOpts = append(computeContainerOpts, WithNonRoot(userId))
computeContainerOpts = append(computeContainerOpts, WithDropALLCapabilities())
}
if t.IsPPC64() {
computeContainerOpts = append(computeContainerOpts, WithPrivileged())
}
if vmi.Spec.ReadinessProbe != nil {
computeContainerOpts = append(computeContainerOpts, WithReadinessProbe(vmi))
}
if vmi.Spec.LivenessProbe != nil {
computeContainerOpts = append(computeContainerOpts, WithLivelinessProbe(vmi))
}
const computeContainerName = "compute"
containerRenderer := NewContainerSpecRenderer(
computeContainerName, t.launcherImage, t.clusterConfig.GetImagePullPolicy(), computeContainerOpts...)
return containerRenderer
}
func (t *templateService) newVolumeRenderer(vmi *v1.VirtualMachineInstance, namespace string, requestedHookSidecarList hooks.HookSidecarList) (*VolumeRenderer, error) {
volumeOpts := []VolumeRendererOption{
withVMIConfigVolumes(vmi.Spec.Domain.Devices.Disks, vmi.Spec.Volumes),
withVMIVolumes(t.persistentVolumeClaimStore, vmi.Spec.Volumes, vmi.Status.VolumeStatus),
withAccessCredentials(vmi.Spec.AccessCredentials),
withBackendStorage(vmi),
}
if len(requestedHookSidecarList) != 0 {
volumeOpts = append(volumeOpts, withSidecarVolumes(requestedHookSidecarList))
}
if util.HasHugePages(vmi) {
volumeOpts = append(volumeOpts, withHugepages())
}
if !vmi.Spec.Domain.Devices.DisableHotplug {
volumeOpts = append(volumeOpts, withHotplugSupport(t.hotplugDiskDir))
}
if vmispec.SRIOVInterfaceExist(vmi.Spec.Domain.Devices.Interfaces) {
volumeOpts = append(volumeOpts, withSRIOVPciMapAnnotation())
}
if util.IsVMIVirtiofsEnabled(vmi) {
volumeOpts = append(volumeOpts, withVirioFS())
}
volumeRenderer, err := NewVolumeRenderer(
namespace,
t.ephemeralDiskDir,
t.containerDiskDir,
t.virtShareDir,
volumeOpts...)
if err != nil {
return nil, err
}
return volumeRenderer, nil
}
func (t *templateService) newResourceRenderer(vmi *v1.VirtualMachineInstance, networkToResourceMap map[string]string) (*ResourceRenderer, error) {
vmiResources := vmi.Spec.Domain.Resources
baseOptions := []ResourceRendererOption{
WithEphemeralStorageRequest(),
WithVirtualizationResources(getRequiredResources(vmi, t.clusterConfig.AllowEmulation())),
}
if err := validatePermittedHostDevices(&vmi.Spec, t.clusterConfig); err != nil {
return nil, err
}
options := append(baseOptions, t.VMIResourcePredicates(vmi, networkToResourceMap).Apply()...)
return NewResourceRenderer(vmiResources.Limits, vmiResources.Requests, options...), nil
}
func sidecarVolumeMount() k8sv1.VolumeMount {
return k8sv1.VolumeMount{
Name: hookSidecarSocks,
MountPath: hooks.HookSocketsSharedDirectory,
}
}
func gracePeriodInSeconds(vmi *v1.VirtualMachineInstance) int64 {
if vmi.Spec.TerminationGracePeriodSeconds != nil {
return *vmi.Spec.TerminationGracePeriodSeconds
}
return v1.DefaultGracePeriodSeconds
}
func sidecarContainerName(i int) string {
return fmt.Sprintf("hook-sidecar-%d", i)
}
func (t *templateService) RenderHotplugAttachmentPodTemplate(volumes []*v1.Volume, ownerPod *k8sv1.Pod, vmi *v1.VirtualMachineInstance, claimMap map[string]*k8sv1.PersistentVolumeClaim, tempPod bool) (*k8sv1.Pod, error) {
zero := int64(0)
runUser := int64(util.NonRootUID)
sharedMount := k8sv1.MountPropagationHostToContainer
command := []string{"/bin/sh", "-c", "/usr/bin/container-disk --copy-path /path/hp"}
pod := &k8sv1.Pod{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "hp-volume-",
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(ownerPod, schema.GroupVersionKind{
Group: k8sv1.SchemeGroupVersion.Group,
Version: k8sv1.SchemeGroupVersion.Version,
Kind: "Pod",
}),
},
Labels: map[string]string{
v1.AppLabel: hotplugDisk,
},
},
Spec: k8sv1.PodSpec{
Containers: []k8sv1.Container{
{
Name: hotplugDisk,
Image: t.launcherImage,
Command: command,
Resources: hotplugContainerResourceRequirementsForVMI(vmi, t.clusterConfig),
SecurityContext: &k8sv1.SecurityContext{
AllowPrivilegeEscalation: pointer.Bool(false),
RunAsNonRoot: pointer.Bool(true),
RunAsUser: &runUser,
SeccompProfile: &k8sv1.SeccompProfile{
Type: k8sv1.SeccompProfileTypeRuntimeDefault,
},
Capabilities: &k8sv1.Capabilities{
Drop: []k8sv1.Capability{"ALL"},
},
SELinuxOptions: &k8sv1.SELinuxOptions{
// If SELinux is enabled on the host, this level will be adjusted below to match the level
// of its companion virt-launcher pod to allow it to consume our disk images.
Type: t.clusterConfig.GetSELinuxLauncherType(),
Level: "s0",
},
},
VolumeMounts: []k8sv1.VolumeMount{
{
Name: hotplugDisks,
MountPath: "/path",
MountPropagation: &sharedMount,
},
},
},
},
Affinity: &k8sv1.Affinity{
NodeAffinity: &k8sv1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &k8sv1.NodeSelector{
NodeSelectorTerms: []k8sv1.NodeSelectorTerm{
{
MatchExpressions: []k8sv1.NodeSelectorRequirement{
{
Key: "kubernetes.io/hostname",
Operator: k8sv1.NodeSelectorOpIn,
Values: []string{ownerPod.Spec.NodeName},
},
},
},
},
},
},
},
Volumes: []k8sv1.Volume{emptyDirVolume(hotplugDisks)},
TerminationGracePeriodSeconds: &zero,
},
}
err := matchSELinuxLevelOfVMI(pod, vmi)
if err != nil {
return nil, err
}
hotplugVolumeStatusMap := make(map[string]v1.VolumePhase)
for _, status := range vmi.Status.VolumeStatus {
if status.HotplugVolume != nil {
hotplugVolumeStatusMap[status.Name] = status.Phase
}
}
for _, volume := range volumes {
claimName := types.PVCNameFromVirtVolume(volume)
if claimName == "" {
continue
}
skipMount := false
if hotplugVolumeStatusMap[volume.Name] == v1.VolumeReady || hotplugVolumeStatusMap[volume.Name] == v1.HotplugVolumeMounted {
skipMount = true
}
pod.Spec.Volumes = append(pod.Spec.Volumes, k8sv1.Volume{
Name: volume.Name,
VolumeSource: k8sv1.VolumeSource{
PersistentVolumeClaim: &k8sv1.PersistentVolumeClaimVolumeSource{
ClaimName: claimName,
},
},
})
pvc := claimMap[volume.Name]
if pvc == nil {
continue
}
if types.IsPVCBlock(pvc.Spec.VolumeMode) {
pod.Spec.Containers[0].VolumeDevices = append(pod.Spec.Containers[0].VolumeDevices, k8sv1.VolumeDevice{
Name: volume.Name,
DevicePath: fmt.Sprintf("/path/%s/%s", volume.Name, pvc.GetUID()),
})
} else {
if !skipMount {
pod.Spec.Containers[0].VolumeMounts = append(pod.Spec.Containers[0].VolumeMounts, k8sv1.VolumeMount{
Name: volume.Name,
MountPath: fmt.Sprintf("/%s", volume.Name),
})
}
}
}
return pod, nil
}
func (t *templateService) RenderHotplugAttachmentTriggerPodTemplate(volume *v1.Volume, ownerPod *k8sv1.Pod, vmi *v1.VirtualMachineInstance, pvcName string, isBlock bool, tempPod bool) (*k8sv1.Pod, error) {
zero := int64(0)
runUser := int64(util.NonRootUID)
sharedMount := k8sv1.MountPropagationHostToContainer
var command []string
if tempPod {
command = []string{"/bin/bash",
"-c",
"exit", "0"}
} else {
command = []string{"/bin/sh", "-c", "/usr/bin/container-disk --copy-path /path/hp"}
}
annotationsList := make(map[string]string)
if tempPod {
// mark pod as temp - only used for provisioning
annotationsList[v1.EphemeralProvisioningObject] = "true"
}
pod := &k8sv1.Pod{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "hp-volume-",
OwnerReferences: []metav1.OwnerReference{
*metav1.NewControllerRef(ownerPod, schema.GroupVersionKind{
Group: k8sv1.SchemeGroupVersion.Group,
Version: k8sv1.SchemeGroupVersion.Version,
Kind: "Pod",
}),
},
Labels: map[string]string{
v1.AppLabel: hotplugDisk,
},
Annotations: annotationsList,
},
Spec: k8sv1.PodSpec{
Containers: []k8sv1.Container{
{
Name: hotplugDisk,
Image: t.launcherImage,
Command: command,
Resources: hotplugContainerResourceRequirementsForVMI(vmi, t.clusterConfig),
SecurityContext: &k8sv1.SecurityContext{
AllowPrivilegeEscalation: pointer.Bool(false),
RunAsNonRoot: pointer.Bool(true),
RunAsUser: &runUser,
SeccompProfile: &k8sv1.SeccompProfile{
Type: k8sv1.SeccompProfileTypeRuntimeDefault,
},
Capabilities: &k8sv1.Capabilities{
Drop: []k8sv1.Capability{"ALL"},
},
SELinuxOptions: &k8sv1.SELinuxOptions{
Level: "s0",
},
},
VolumeMounts: []k8sv1.VolumeMount{
{
Name: hotplugDisks,
MountPath: "/path",
MountPropagation: &sharedMount,
},
},
},
},
Affinity: &k8sv1.Affinity{
PodAffinity: &k8sv1.PodAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []k8sv1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchLabels: ownerPod.GetLabels(),
},
TopologyKey: "kubernetes.io/hostname",
},
},
},
},
Volumes: []k8sv1.Volume{
{
Name: volume.Name,
VolumeSource: k8sv1.VolumeSource{
PersistentVolumeClaim: &k8sv1.PersistentVolumeClaimVolumeSource{
ClaimName: pvcName,
ReadOnly: false,
},
},
},
emptyDirVolume(hotplugDisks),
},
TerminationGracePeriodSeconds: &zero,
},
}
err := matchSELinuxLevelOfVMI(pod, vmi)
if err != nil {
return nil, err
}
if isBlock {
pod.Spec.Containers[0].VolumeDevices = []k8sv1.VolumeDevice{
{