forked from kubevirt/hyperconverged-cluster-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkubevirt.go
514 lines (437 loc) · 16.9 KB
/
kubevirt.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
package operands
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/yaml"
hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/pkg/apis/hco/v1beta1"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/controller/common"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/util"
hcoutil "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util"
conditionsv1 "github.com/openshift/custom-resource-status/conditions/v1"
corev1 "k8s.io/api/core/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kubevirtv1 "kubevirt.io/client-go/api/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
kubevirtDefaultNetworkInterfaceValue = "masquerade"
// We can import the constants below from Kubevirt virt-config package
// after Kubevirt will consume k8s.io v0.19.2 or higher
FeatureGatesKey = "feature-gates"
MachineTypeKey = "machine-type"
UseEmulationKey = "debug.useEmulation"
MigrationsConfigKey = "migrations"
NetworkInterfaceKey = "default-network-interface"
SmbiosConfigKey = "smbios"
SELinuxLauncherTypeKey = "selinuxLauncherType"
DefaultNetworkInterface = "bridge"
SELinuxLauncherType = "virt_launcher.process"
)
// env vars
const (
kvmEmulationEnvName = "KVM_EMULATION"
smbiosEnvName = "SMBIOS"
machineTypeEnvName = "MACHINETYPE"
)
// KubeVirt hard coded FeatureGates
// These feature gates are set by HCO in the KubeVirt CR and can't be modified by the end user.
const (
// indicates that we support turning on DataVolume workflows. This means using DataVolumes in the VM and VMI
// definitions. There was a period of time where this was in alpha and needed to be explicility enabled.
// It also means that someone is using KubeVirt with CDI. So by not enabling this feature gate, someone can safely
// use kubevirt without CDI and know that users of kubevirt will not be able to post VM/VMIs that use CDI workflows
// that aren't available to them
kvDataVolumesGate = "DataVolumes"
// Enable Single-root input/output virtualization
kvSRIOVGate = "SRIOV"
// Enables VMIs to be live migrated. Without this, migrations are not possible and will be blocked
kvLiveMigrationGate = "LiveMigration"
// Enables the CPUManager feature gate to label the nodes which have the Kubernetes CPUManager running. VMIs that
// require dedicated CPU resources will automatically be scheduled on the labeled nodes
kvCPUManagerGate = "CPUManager"
// Enables schedule VMIs according to their CPU model
kvCPUNodeDiscoveryGate = "CPUNodeDiscovery"
// Enables the alpha offline snapshot functionality
kvSnapshotGate = "Snapshot"
// Allow attaching a data volume to a running VMI
kvHotplugVolumesGate = "HotplugVolumes"
// Allow assigning GPU and vGPU devices to virtual machines
kvGPUGate = "GPU"
// Allow assigning host devices to virtual machines
kvHostDevicesGate = "HostDevices"
)
var (
hardCodeKvFgs = []string{
kvDataVolumesGate,
kvSRIOVGate,
kvLiveMigrationGate,
kvCPUManagerGate,
kvCPUNodeDiscoveryGate,
kvSnapshotGate,
kvHotplugVolumesGate,
kvGPUGate,
kvHostDevicesGate,
}
// holds a list of mandatory KubeVirt feature gates. Some of them are the hard coded feature gates and some of
// them are added according to conditions; e.g. if SSP is deployed.
mandatoryKvFeatureGates []string
)
// These KubeVirt feature gates are automatically enabled in KubeVirt if SSP is deployed
const (
// Support migration for VMs with host-model CPU mode
kvWithHostModelCPU = "WithHostModelCPU"
// Enable HyperV strict host checking for HyperV enlightenments
kvHypervStrictCheck = "HypervStrictCheck"
)
var (
sspConditionKvFgs = []string{
kvWithHostModelCPU,
kvHypervStrictCheck,
}
)
// KubeVirt feature gates that are exposed in HCO API
const (
kvWithHostPassthroughCPU = "WithHostPassthroughCPU"
)
// ************ KubeVirt Handler **************
type kubevirtHandler genericOperand
func newKubevirtHandler(Client client.Client, Scheme *runtime.Scheme) *kubevirtHandler {
return &kubevirtHandler{
Client: Client,
Scheme: Scheme,
crType: "KubeVirt",
removeExistingOwner: false,
setControllerReference: true,
isCr: true,
hooks: &kubevirtHooks{},
}
}
type kubevirtHooks struct {
cache *kubevirtv1.KubeVirt
}
func (h *kubevirtHooks) getFullCr(hc *hcov1beta1.HyperConverged) (client.Object, error) {
if h.cache == nil {
kv, err := NewKubeVirt(hc)
if err != nil {
return nil, err
}
h.cache = kv
}
return h.cache, nil
}
func (h kubevirtHooks) getEmptyCr() client.Object { return &kubevirtv1.KubeVirt{} }
func (h kubevirtHooks) validate() error { return nil }
func (h kubevirtHooks) postFound(*common.HcoRequest, runtime.Object) error { return nil }
func (h kubevirtHooks) getConditions(cr runtime.Object) []conditionsv1.Condition {
return translateKubeVirtConds(cr.(*kubevirtv1.KubeVirt).Status.Conditions)
}
func (h kubevirtHooks) checkComponentVersion(cr runtime.Object) bool {
found := cr.(*kubevirtv1.KubeVirt)
return checkComponentVersion(hcoutil.KubevirtVersionEnvV, found.Status.ObservedKubeVirtVersion)
}
func (h kubevirtHooks) getObjectMeta(cr runtime.Object) *metav1.ObjectMeta {
return &cr.(*kubevirtv1.KubeVirt).ObjectMeta
}
func (h *kubevirtHooks) reset() {
h.cache = nil
}
func (h *kubevirtHooks) updateCr(req *common.HcoRequest, Client client.Client, exists runtime.Object, required runtime.Object) (bool, bool, error) {
virt, ok1 := required.(*kubevirtv1.KubeVirt)
found, ok2 := exists.(*kubevirtv1.KubeVirt)
if !ok1 || !ok2 {
return false, false, errors.New("can't convert to KubeVirt")
}
if !reflect.DeepEqual(found.Spec, virt.Spec) ||
!reflect.DeepEqual(found.Labels, virt.Labels) {
if req.HCOTriggered {
req.Logger.Info("Updating existing KubeVirt's Spec to new opinionated values")
} else {
req.Logger.Info("Reconciling an externally updated KubeVirt's Spec to its opinionated values")
}
util.DeepCopyLabels(&virt.ObjectMeta, &found.ObjectMeta)
virt.Spec.DeepCopyInto(&found.Spec)
err := Client.Update(req.Ctx, found)
if err != nil {
return false, false, err
}
return true, !req.HCOTriggered, nil
}
return false, false, nil
}
func NewKubeVirt(hc *hcov1beta1.HyperConverged, opts ...string) (*kubevirtv1.KubeVirt, error) {
config, err := getKVConfig(hc)
if err != nil {
return nil, err
}
spec := kubevirtv1.KubeVirtSpec{
UninstallStrategy: kubevirtv1.KubeVirtUninstallStrategyBlockUninstallIfWorkloadsExist,
Infra: hcoConfig2KvConfig(hc.Spec.Infra),
Workloads: hcoConfig2KvConfig(hc.Spec.Workloads),
Configuration: *config,
}
// TODO: support passing certificate rotation configuration to KubeVirt spec
kv := NewKubeVirtWithNameOnly(hc, opts...)
kv.Spec = spec
if err := applyPatchToSpec(hc, common.JSONPatchKVAnnotationName, kv); err != nil {
return nil, err
}
return kv, nil
}
func getKVConfig(hc *hcov1beta1.HyperConverged) (*kubevirtv1.KubeVirtConfiguration, error) {
devConfig, err := getKVDevConfig(hc)
if err != nil {
return nil, err
}
kvLiveMigration, err := hcLiveMigrationToKv(hc.Spec.LiveMigrationConfig)
if err != nil {
return nil, err
}
config := &kubevirtv1.KubeVirtConfiguration{
DeveloperConfiguration: devConfig,
SELinuxLauncherType: SELinuxLauncherType,
NetworkConfiguration: &kubevirtv1.NetworkConfiguration{
NetworkInterface: string(kubevirtv1.MasqueradeInterface),
},
MigrationConfiguration: kvLiveMigration,
PermittedHostDevices: toKvPermittedHostDevices(hc.Spec.PermittedHostDevices),
}
if smbiosConfig, ok := os.LookupEnv(smbiosEnvName); ok {
if smbiosConfig = strings.TrimSpace(smbiosConfig); smbiosConfig != "" {
config.SMBIOSConfig = &kubevirtv1.SMBiosConfiguration{}
err := yaml.NewYAMLOrJSONDecoder(strings.NewReader(smbiosConfig), 1024).Decode(config.SMBIOSConfig)
if err != nil {
return nil, err
}
}
}
if val, ok := os.LookupEnv(machineTypeEnvName); ok {
if val = strings.TrimSpace(val); val != "" {
config.MachineType = val
}
}
return config, nil
}
func toKvPermittedHostDevices(permittedDevices *hcov1beta1.PermittedHostDevices) *kubevirtv1.PermittedHostDevices {
if permittedDevices == nil {
return nil
}
return &kubevirtv1.PermittedHostDevices{
PciHostDevices: toKvPciHostDevices(permittedDevices.PciHostDevices),
MediatedDevices: toKvMediatedDevices(permittedDevices.MediatedDevices),
}
}
func toKvPciHostDevices(hcoPciHostdevices []hcov1beta1.PciHostDevice) []kubevirtv1.PciHostDevice {
if len(hcoPciHostdevices) > 0 {
pciHostDevices := make([]kubevirtv1.PciHostDevice, len(hcoPciHostdevices))
for i, hcoPciHostDevice := range hcoPciHostdevices {
pciHostDevices[i] = kubevirtv1.PciHostDevice{
PCIVendorSelector: hcoPciHostDevice.PCIVendorSelector,
ResourceName: hcoPciHostDevice.ResourceName,
ExternalResourceProvider: hcoPciHostDevice.ExternalResourceProvider,
}
}
return pciHostDevices
}
return nil
}
func toKvMediatedDevices(hcoMediatedDevices []hcov1beta1.MediatedHostDevice) []kubevirtv1.MediatedHostDevice {
if len(hcoMediatedDevices) > 0 {
mediatedDevices := make([]kubevirtv1.MediatedHostDevice, len(hcoMediatedDevices))
for i, hcoMediatedHostDevice := range hcoMediatedDevices {
mediatedDevices[i] = kubevirtv1.MediatedHostDevice{
MDEVNameSelector: hcoMediatedHostDevice.MDEVNameSelector,
ResourceName: hcoMediatedHostDevice.ResourceName,
ExternalResourceProvider: hcoMediatedHostDevice.ExternalResourceProvider,
}
}
return mediatedDevices
}
return nil
}
func hcLiveMigrationToKv(lm hcov1beta1.LiveMigrationConfigurations) (*kubevirtv1.MigrationConfiguration, error) {
var bandwidthPerMigration *resource.Quantity = nil
if lm.BandwidthPerMigration != nil {
bandwidthPerMigrationObject, err := resource.ParseQuantity(*lm.BandwidthPerMigration)
if err != nil {
return nil, fmt.Errorf("failed to parse the LiveMigrationConfig.bandwidthPerMigration field; %w", err)
}
bandwidthPerMigration = &bandwidthPerMigrationObject
}
return &kubevirtv1.MigrationConfiguration{
BandwidthPerMigration: bandwidthPerMigration,
CompletionTimeoutPerGiB: lm.CompletionTimeoutPerGiB,
ParallelOutboundMigrationsPerNode: lm.ParallelOutboundMigrationsPerNode,
ParallelMigrationsPerCluster: lm.ParallelMigrationsPerCluster,
ProgressTimeout: lm.ProgressTimeout,
}, nil
}
func getKVDevConfig(hc *hcov1beta1.HyperConverged) (*kubevirtv1.DeveloperConfiguration, error) {
fgs := getKvFeatureGateList(&hc.Spec.FeatureGates)
var kvmEmulation = false
kvmEmulationStr, ok := os.LookupEnv(kvmEmulationEnvName)
if ok {
if kvmEmulationStr = strings.TrimSpace(kvmEmulationStr); kvmEmulationStr != "" {
var err error
kvmEmulation, err = strconv.ParseBool(kvmEmulationStr)
if err != nil {
return nil, err
}
}
}
if len(fgs) > 0 || kvmEmulation {
return &kubevirtv1.DeveloperConfiguration{
FeatureGates: fgs,
UseEmulation: kvmEmulation,
}, nil
}
return nil, nil
}
func NewKubeVirtWithNameOnly(hc *hcov1beta1.HyperConverged, opts ...string) *kubevirtv1.KubeVirt {
return &kubevirtv1.KubeVirt{
ObjectMeta: metav1.ObjectMeta{
Name: "kubevirt-" + hc.Name,
Labels: getLabels(hc, hcoutil.AppComponentCompute),
Namespace: getNamespace(hc.Namespace, opts),
},
}
}
func hcoConfig2KvConfig(hcoConfig hcov1beta1.HyperConvergedConfig) *kubevirtv1.ComponentConfig {
if hcoConfig.NodePlacement != nil {
kvConfig := &kubevirtv1.ComponentConfig{}
kvConfig.NodePlacement = &kubevirtv1.NodePlacement{}
if hcoConfig.NodePlacement.Affinity != nil {
kvConfig.NodePlacement.Affinity = &corev1.Affinity{}
hcoConfig.NodePlacement.Affinity.DeepCopyInto(kvConfig.NodePlacement.Affinity)
}
if hcoConfig.NodePlacement.NodeSelector != nil {
kvConfig.NodePlacement.NodeSelector = make(map[string]string)
for k, v := range hcoConfig.NodePlacement.NodeSelector {
kvConfig.NodePlacement.NodeSelector[k] = v
}
}
for _, hcoTolr := range hcoConfig.NodePlacement.Tolerations {
kvTolr := corev1.Toleration{}
hcoTolr.DeepCopyInto(&kvTolr)
kvConfig.NodePlacement.Tolerations = append(kvConfig.NodePlacement.Tolerations, kvTolr)
}
return kvConfig
}
return nil
}
type featureGateChecks map[string]func() bool
func getFeatureGateChecks(featureGates *hcov1beta1.HyperConvergedFeatureGates) featureGateChecks {
return map[string]func() bool{
kvWithHostPassthroughCPU: featureGates.IsWithHostPassthroughCPUEnabled,
}
}
// *********** KubeVirt Priority Class ************
type kvPriorityClassHandler genericOperand
func newKvPriorityClassHandler(Client client.Client, Scheme *runtime.Scheme) *kvPriorityClassHandler {
return &kvPriorityClassHandler{
Client: Client,
Scheme: Scheme,
crType: "KubeVirtPriorityClass",
removeExistingOwner: false,
setControllerReference: false,
isCr: false,
hooks: &kvPriorityClassHooks{},
}
}
type kvPriorityClassHooks struct{}
func (h kvPriorityClassHooks) getFullCr(hc *hcov1beta1.HyperConverged) (client.Object, error) {
return NewKubeVirtPriorityClass(hc), nil
}
func (h kvPriorityClassHooks) getEmptyCr() client.Object { return &schedulingv1.PriorityClass{} }
func (h kvPriorityClassHooks) validate() error { return nil }
func (h kvPriorityClassHooks) postFound(_ *common.HcoRequest, _ runtime.Object) error { return nil }
func (h kvPriorityClassHooks) getConditions(_ runtime.Object) []conditionsv1.Condition { return nil }
func (h kvPriorityClassHooks) checkComponentVersion(_ runtime.Object) bool { return true }
func (h kvPriorityClassHooks) getObjectMeta(cr runtime.Object) *metav1.ObjectMeta {
return &cr.(*schedulingv1.PriorityClass).ObjectMeta
}
func (h kvPriorityClassHooks) reset() { /* no implementation */ }
func (h *kvPriorityClassHooks) updateCr(req *common.HcoRequest, Client client.Client, exists runtime.Object, required runtime.Object) (bool, bool, error) {
pc, ok1 := required.(*schedulingv1.PriorityClass)
found, ok2 := exists.(*schedulingv1.PriorityClass)
if !ok1 || !ok2 {
return false, false, errors.New("can't convert to PriorityClass")
}
// at this point we found the object in the cache and we check if something was changed
if (pc.Name == found.Name) && (pc.Value == found.Value) &&
(pc.Description == found.Description) && reflect.DeepEqual(pc.Labels, found.Labels) {
return false, false, nil
}
if req.HCOTriggered {
req.Logger.Info("Updating existing KubeVirt's Spec to new opinionated values")
} else {
req.Logger.Info("Reconciling an externally updated KubeVirt's Spec to its opinionated values")
}
// something was changed but since we can't patch a priority class object, we remove it
err := Client.Delete(req.Ctx, found, &client.DeleteOptions{})
if err != nil {
return false, false, err
}
// create the new object
err = Client.Create(req.Ctx, pc, &client.CreateOptions{})
if err != nil {
return false, false, err
}
return true, !req.HCOTriggered, nil
}
func NewKubeVirtPriorityClass(hc *hcov1beta1.HyperConverged) *schedulingv1.PriorityClass {
return &schedulingv1.PriorityClass{
TypeMeta: metav1.TypeMeta{
APIVersion: "scheduling.k8s.io/v1",
Kind: "PriorityClass",
},
ObjectMeta: metav1.ObjectMeta{
Name: "kubevirt-cluster-critical",
Labels: getLabels(hc, hcoutil.AppComponentCompute),
},
// 1 billion is the highest value we can set
// https://kubernetes.io/docs/concepts/configuration/pod-priority-preemption/#priorityclass
Value: 1000000000,
GlobalDefault: false,
Description: "This priority class should be used for KubeVirt core components only.",
}
}
// translateKubeVirtConds translates list of KubeVirt conditions to a list of custom resource
// conditions.
func translateKubeVirtConds(orig []kubevirtv1.KubeVirtCondition) []conditionsv1.Condition {
translated := make([]conditionsv1.Condition, len(orig))
for i, origCond := range orig {
translated[i] = conditionsv1.Condition{
Type: conditionsv1.ConditionType(origCond.Type),
Status: origCond.Status,
Reason: origCond.Reason,
Message: origCond.Message,
}
}
return translated
}
func getMandatoryKvFeatureGates(isOpenshiftCluster bool) []string {
mandatoryFeatureGates := append(hardCodeKvFgs)
if isOpenshiftCluster {
mandatoryFeatureGates = append(mandatoryFeatureGates, sspConditionKvFgs...)
}
return mandatoryFeatureGates
}
// get list of feature gates or KV FG list
func getKvFeatureGateList(fgs *hcov1beta1.HyperConvergedFeatureGates) []string {
checks := getFeatureGateChecks(fgs)
res := make([]string, 0, len(checks)+len(mandatoryKvFeatureGates))
res = append(res, mandatoryKvFeatureGates...)
for gate, check := range checks {
if check() {
res = append(res, gate)
}
}
return res
}