forked from oVirt/cluster-api-provider-ovirt
/
impl.go
551 lines (497 loc) · 17.8 KB
/
impl.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
/*
Copyright oVirt Authors
SPDX-License-Identifier: Apache-2.0
*/
package ovirt
import (
"fmt"
machinev1 "github.com/openshift/api/machine/v1beta1"
ovirtconfigv1 "github.com/openshift/cluster-api-provider-ovirt/pkg/apis/ovirtprovider/v1beta1"
"github.com/openshift/machine-api-operator/pkg/util"
ovirtsdk "github.com/ovirt/go-ovirt"
ovirtclient "github.com/ovirt/go-ovirt-client"
kloglogger "github.com/ovirt/go-ovirt-client-log-klog"
"github.com/pkg/errors"
"k8s.io/klog"
"math"
"regexp"
"time"
)
var _ Client = (*ovirtClient)(nil)
const (
BytesInMB = 1048576
)
// CreateVMByMachine creates an oVirt VM according to the ovirt provider spec.
func (is *ovirtClient) CreateVMByMachine(
machineName string,
ovirtClusterID string,
ignition []byte,
providerSpec *ovirtconfigv1.OvirtMachineProviderSpec) (instance *Instance, err error) {
if machineName == "" {
return nil, errors.New("machine name must be specified to create instance")
}
if ovirtClusterID == "" {
return nil, errors.New("ovirtClusterID must be specified to create instance")
}
if providerSpec == nil {
return nil, errors.New("oVirt machine providerSpec must be specified to create instance")
}
cluster := ovirtsdk.NewClusterBuilder().Id(providerSpec.ClusterId).MustBuild()
template := ovirtsdk.NewTemplateBuilder().Name(providerSpec.TemplateName).MustBuild()
init := ovirtsdk.NewInitializationBuilder().
CustomScript(string(ignition)).
HostName(machineName).
MustBuild()
vmBuilder := ovirtsdk.NewVmBuilder().
Name(machineName).
Cluster(cluster).
Template(template).
Initialization(init)
if providerSpec.VMType != "" {
vmBuilder.Type(ovirtsdk.VmType(providerSpec.VMType))
}
if providerSpec.InstanceTypeId != "" {
vmBuilder.InstanceTypeBuilder(
ovirtsdk.NewInstanceTypeBuilder().
Id(providerSpec.InstanceTypeId))
} else {
if providerSpec.CPU != nil {
vmBuilder.CpuBuilder(
ovirtsdk.NewCpuBuilder().
TopologyBuilder(ovirtsdk.NewCpuTopologyBuilder().
Cores(int64(providerSpec.CPU.Cores)).
Sockets(int64(providerSpec.CPU.Sockets)).
Threads(int64(providerSpec.CPU.Threads))))
}
if providerSpec.MemoryMB > 0 {
vmBuilder.Memory(int64(BytesInMB) * int64(providerSpec.MemoryMB))
}
if providerSpec.GuaranteedMemoryMB > 0 {
memoryPolicyBuilder := ovirtsdk.NewMemoryPolicyBuilder()
memoryPolicyBuilder.Guaranteed(int64(BytesInMB) * int64(providerSpec.GuaranteedMemoryMB))
memoryPolicy, err := memoryPolicyBuilder.Build()
if err != nil {
return nil, errors.Wrap(
err, "error applying Guaranteed Memory for VM ")
}
vmBuilder.MemoryPolicy(memoryPolicy)
}
}
isAutoPinning := false
if providerSpec.AutoPinningPolicy != "" {
autoPinningPolicy := mapAutoPinningPolicy(providerSpec.AutoPinningPolicy)
// if we have a policy, we need to set the pinning to all the hosts in the cluster.
if autoPinningPolicy != ovirtsdk.AUTOPINNINGPOLICY_DISABLED {
isAutoPinning = true
hostsInCluster, err := is.getHostsInCluster(providerSpec.ClusterId)
if err != nil {
return nil, errors.Wrapf(
err, "error finding hosts in cluster %s", providerSpec.ClusterId)
}
placementPolicyBuilder := ovirtsdk.NewVmPlacementPolicyBuilder()
placementPolicy, err := placementPolicyBuilder.Hosts(hostsInCluster).
Affinity(ovirtsdk.VMAFFINITY_MIGRATABLE).Build()
if err != nil {
return nil, errors.Wrap(err, "failed to build the placement policy of the vm")
}
vmBuilder.PlacementPolicy(placementPolicy)
}
}
if providerSpec.Hugepages > 0 {
customProp, err := ovirtsdk.NewCustomPropertyBuilder().
Name("hugepages").
Value(fmt.Sprint(providerSpec.Hugepages)).
Build()
if err != nil {
return nil, errors.Wrap(err, "error setting hugepages custom property")
}
vmBuilder.CustomPropertiesOfAny(customProp)
}
vm, err := vmBuilder.Build()
if err != nil {
return nil, errors.Wrap(err, "failed to construct VM struct")
}
klog.Infof("creating VM: %v", vm.MustName())
response, err := is.connection.SystemService().VmsService().Add().Vm(vm).Send()
if err != nil {
klog.Errorf("Failed creating VM %v", err)
return nil, errors.Wrap(err, "error creating VM")
}
vmID := response.MustVm().MustId()
err = is.connection.WaitForVM(vmID, ovirtsdk.VMSTATUS_DOWN, time.Minute)
if err != nil {
return nil, errors.Wrap(err, "timed out waiting for the VM creation to finish")
}
vmService := is.connection.SystemService().VmsService().VmService(vmID)
if providerSpec.OSDisk != nil {
err = is.handleDiskExtension(vmService, response, providerSpec)
if err != nil {
return nil, err
}
}
err = is.handleNics(vmService, providerSpec)
if err != nil {
return nil, errors.Wrapf(err, "failed handling nics creation for VM %s", vm.MustName())
}
if isAutoPinning {
err = is.handleAutoPinning(vmID, mapAutoPinningPolicy(providerSpec.AutoPinningPolicy))
if err != nil {
klog.Errorf("updating the VM (%s) with auto pinning policy failed! %v", vmID, err)
}
}
_, err = is.connection.SystemService().VmsService().
VmService(response.MustVm().MustId()).
TagsService().Add().
Tag(ovirtsdk.NewTagBuilder().Name(ovirtClusterID).MustBuild()).
Send()
if err != nil {
klog.Errorf("Failed to add tag to VM, skipping %v", err)
}
err = is.handleAffinityGroups(
response.MustVm(),
providerSpec.ClusterId,
providerSpec.AffinityGroupsNames)
if err != nil {
return nil, err
}
return &Instance{response.MustVm()}, nil
}
func (is *ovirtClient) handleDiskExtension(vmService *ovirtsdk.VmService, createdVM *ovirtsdk.VmsServiceAddResponse, providerSpec *ovirtconfigv1.OvirtMachineProviderSpec) error {
attachmentsResponse, err := vmService.DiskAttachmentsService().List().Send()
if err != nil {
return errors.Wrap(err, "error finding disk attachment")
}
var bootableDiskAttachment *ovirtsdk.DiskAttachment
for _, disk := range attachmentsResponse.MustAttachments().Slice() {
if disk.MustBootable() {
// found the os disk
bootableDiskAttachment = disk
}
}
if bootableDiskAttachment == nil {
return fmt.Errorf("VM %s(%s) doesn't have a bootable disk",
createdVM.MustVm().MustName(), createdVM.MustVm().MustId())
}
// extend the disk if requested size is bigger than template. We won't support shrinking it.
newDiskSize := providerSpec.OSDisk.SizeGB * int64(math.Pow(2, 30))
// get the disk
getDisk, err := vmService.Connection().SystemService().DisksService().DiskService(bootableDiskAttachment.MustId()).Get().Send()
if err != nil {
return errors.Wrap(err, "error getting disk")
}
size := getDisk.MustDisk().MustProvisionedSize()
if newDiskSize < size {
klog.Warning("The machine spec specified new disk size %d, and the current disk size is %d. Shrinking is "+
"not supported.", newDiskSize, size)
}
if newDiskSize > size {
klog.Infof("Extending the OS disk from %d to %d", size, newDiskSize)
bootableDiskAttachment.SetDisk(getDisk.MustDisk())
bootableDiskAttachment.
MustDisk().
SetProvisionedSize(newDiskSize)
_, err := vmService.DiskAttachmentsService().
AttachmentService(bootableDiskAttachment.MustId()).
Update().
DiskAttachment(bootableDiskAttachment).
Send()
if err != nil {
return errors.Wrap(err, "failed to update the OS disk")
}
klog.Infof("Waiting while extending the OS disk")
// wait for the disk extension to be over
err = is.connection.WaitForDisk(bootableDiskAttachment.MustId(), ovirtsdk.DISKSTATUS_OK, 20*time.Minute)
if err != nil {
return errors.Wrap(err, "error while waiting for disk")
}
}
return nil
}
// DeleteVM deletes a VM with the given ID from the oVirt engine
func (is *ovirtClient) DeleteVM(id string) error {
klog.Infof("Deleting VM with ID: %s", id)
vmService := is.connection.SystemService().VmsService().VmService(id)
_, err := vmService.Stop().Send()
if err != nil {
return fmt.Errorf("error stopping VM %s: %w", id, err)
}
err = util.PollImmediate(time.Second*10, time.Minute*5, func() (bool, error) {
vmResponse, err := vmService.Get().Send()
if err != nil {
return false, nil
}
vm, ok := vmResponse.Vm()
if !ok {
return false, err
}
return vm.MustStatus() == ovirtsdk.VMSTATUS_DOWN, nil
})
if err != nil {
return fmt.Errorf("error waiting for VM %s to be down: %w", id, err)
}
// Detach all the disks that are not the bootable disk, to prevent them from being deleted
diskAttachmentsResp, err := vmService.DiskAttachmentsService().List().Send()
diskAttachments, ok := diskAttachmentsResp.Attachments()
if !ok {
return fmt.Errorf("error getting attachments from vm %s, error is: %w", id, err)
}
for _, da := range diskAttachments.Slice() {
bootable, ok := da.Bootable()
if !ok {
return fmt.Errorf("error while checking if disk attachment for vm %s is bootable: %w", id, err)
}
if !bootable {
_, err = vmService.DiskAttachmentsService().AttachmentService(da.MustId()).Remove().Send()
if err != nil {
return fmt.Errorf("error while detaching disk attachment %s for vm %s : %w", da.MustId(), id, err)
}
}
}
_, err = vmService.Remove().Send()
if err != nil {
return fmt.Errorf("error removing VM %s: %w", id, err)
}
// poll till VM doesn't exist
err = util.PollImmediate(time.Second*10, time.Minute*5, func() (bool, error) {
_, err := vmService.Get().Send()
return err != nil, nil
})
if err != nil {
return fmt.Errorf("error waiting for VM %s to be removed: %w", id, err)
}
return nil
}
// GetVMByMachine returns the VM instance corresponding to the machine object
// If there is no VM corresponding to the machine object then nil will be returned
func (is *ovirtClient) GetVMByMachine(machine machinev1.Machine) (instance *Instance, err error) {
if machine.Spec.ProviderID != nil && *machine.Spec.ProviderID != "" {
instance, err = is.GetVMByID(*machine.Spec.ProviderID)
if err == nil {
return instance, err
}
}
instance, err = is.GetVMByName(machine.Name)
return instance, err
}
// GetVMByID returns an oVirt VM instance in case it exists in the oVirt env
// If there is no VM with the given ID then nil will be returned
func (is *ovirtClient) GetVMByID(id string) (instance *Instance, err error) {
klog.Infof("Fetching VM by ID: %s", id)
if id == "" {
return nil, fmt.Errorf("vm id should be specified")
}
response, err := is.connection.SystemService().VmsService().VmService(id).Get().Send()
if err != nil {
return nil, fmt.Errorf("error getting VM with ID %s: %w", id, err)
}
klog.Infof("Got VM by ID: %s", response.MustVm().MustName())
return &Instance{Vm: response.MustVm()}, nil
}
// GetVMByName returns an oVirt VM instance in case it exists in the oVirt env
// If there is no VM with the given name then nil will be returned
func (is *ovirtClient) GetVMByName(mName string) (*Instance, error) {
response, err := is.connection.SystemService().VmsService().
List().Search("name=" + mName).Send()
if err != nil {
klog.Errorf("Failed to fetch VM by name")
return nil, fmt.Errorf("error getting VM with name %s: %w", mName, err)
}
for _, vm := range response.MustVms().Slice() {
if name, ok := vm.Name(); ok {
if name == mName {
return &Instance{Vm: vm}, nil
}
}
}
// returning an nil instance if we didn't find a match
return nil, nil
}
func (is *ovirtClient) StartVM(id string) error {
vmService := is.connection.SystemService().VmsService().VmService(id)
if _, err := vmService.Start().Send(); err != nil {
return errors.Wrap(err, "error starting oVirt VM")
}
return nil
}
func (is *ovirtClient) handleNics(vmService *ovirtsdk.VmService, spec *ovirtconfigv1.OvirtMachineProviderSpec) error {
if spec.NetworkInterfaces == nil || len(spec.NetworkInterfaces) == 0 {
return nil
}
nicList, err := vmService.NicsService().List().Send()
if err != nil {
return errors.Wrap(err, "failed fetching VM network interfaces")
}
// remove all existing nics
for _, n := range nicList.MustNics().Slice() {
_, err := vmService.NicsService().NicService(n.MustId()).Remove().Send()
if err != nil {
return errors.Wrap(err, "failed clearing all interfaces before populating new ones")
}
}
// re-add nics
for i, nic := range spec.NetworkInterfaces {
_, err := vmService.NicsService().Add().Nic(
ovirtsdk.NewNicBuilder().
Name(fmt.Sprintf("nic%d", i+1)).
VnicProfileBuilder(ovirtsdk.NewVnicProfileBuilder().Id(nic.VNICProfileID)).
MustBuild()).
Send()
if err != nil {
return errors.Wrap(err, "failed to create network interface")
}
}
return nil
}
// Find virtual machine IP Address by ID
func (is *ovirtClient) FindVirtualMachineIP(id string, excludeAddr map[string]int) (string, error) {
vmService := is.connection.SystemService().VmsService().VmService(id)
// Get the guest reported devices
reportedDeviceResp, err := vmService.ReportedDevicesService().List().Send()
if err != nil {
return "", fmt.Errorf("failed to get reported devices list, reason: %w", err)
}
reportedDeviceSlice, _ := reportedDeviceResp.ReportedDevice()
if len(reportedDeviceSlice.Slice()) == 0 {
return "", fmt.Errorf("cannot find NICs for vmId: %s", id)
}
var nicRegex = regexp.MustCompile(`^(eth|en|br\-ex).*`)
for _, reportedDevice := range reportedDeviceSlice.Slice() {
nicName, _ := reportedDevice.Name()
if !nicRegex.MatchString(nicName) {
klog.Infof("ovirt vm id: %s, skipped nic %s , naming regex mismatch", id, nicName)
continue
}
ips, hasIps := reportedDevice.Ips()
if hasIps {
for _, ip := range ips.Slice() {
ipAddress, hasAddress := ip.Address()
if _, ok := excludeAddr[ipAddress]; ok {
klog.Infof("ipAddress %s is excluded from usable IPs", ipAddress)
continue
}
if hasAddress {
klog.Infof("ovirt vm id: %s , found usable IP %s", id, ipAddress)
return ipAddress, nil
}
}
}
}
return "", fmt.Errorf("coudlnt find usable IP address for vm id: %s", id)
}
func (is *ovirtClient) getAffinityGroups(cID string, agNames []string) (ag []*ovirtsdk.AffinityGroup, err error) {
res, err := is.connection.SystemService().ClustersService().
ClusterService(cID).AffinityGroupsService().
List().Send()
if err != nil {
return nil, fmt.Errorf("error listing affinity groups in cluster %s: %w", cID, err)
}
agNamesMap := make(map[string]*ovirtsdk.AffinityGroup)
for _, af := range res.MustGroups().Slice() {
agNamesMap[af.MustName()] = af
}
for _, agName := range agNames {
if _, ok := agNamesMap[agName]; !ok {
return nil, fmt.Errorf("affinity group %v was not found on cluster %v", agName, cID)
}
ag = append(ag, agNamesMap[agName])
}
return ag, nil
}
// handleAffinityGroups adds the VM to the provided affinity groups
func (is *ovirtClient) handleAffinityGroups(vm *ovirtsdk.Vm, cID string, agsName []string) error {
ags, err := is.getAffinityGroups(cID, agsName)
if err != nil {
return errors.Wrap(err, "error getting affinity groups")
}
agService := is.connection.SystemService().ClustersService().
ClusterService(cID).AffinityGroupsService()
for _, ag := range ags {
klog.Infof("Adding machine %v to affinity group %v", vm.MustName(), ag.MustName())
_, err = agService.GroupService(ag.MustId()).VmsService().Add().Vm(vm).Send()
// TODO: bug 1932320: Remove error handling workaround when BZ#1931932 is resolved and backported
if err != nil && !errors.Is(err, ovirtsdk.XMLTagNotMatchError{ActualTag: "action", ExpectedTag: "vm"}) {
return fmt.Errorf(
"failed to add VM %s to AffinityGroup %s, error: %w",
vm.MustName(),
ag.MustName(),
err)
}
}
return nil
}
// getHostsInCluster will return a HostSlice of the hosts in a given cluster ID.
func (is *ovirtClient) getHostsInCluster(clusterID string) (*ovirtsdk.HostSlice, error) {
clusterService := is.connection.SystemService().ClustersService().ClusterService(clusterID)
clusterGet, err := clusterService.Get().Send()
if err != nil {
return nil, fmt.Errorf("failed to get cluster %s: %w", clusterID, err)
}
clusterName := clusterGet.MustCluster().MustName()
hostsInCluster, err := is.connection.SystemService().HostsService().List().Search(
fmt.Sprintf("cluster=%s", clusterName)).Send()
if err != nil {
return nil, fmt.Errorf(
"failed to get the list of hosts in the cluster %s: %w", clusterID, err)
}
return hostsInCluster.MustHosts(), nil
}
// handleAutoPinning updates the VM after creation to set the auto pinning policy configuration.
func (is *ovirtClient) handleAutoPinning(id string, autoPinningPolicy ovirtsdk.AutoPinningPolicy) error {
vmService := is.connection.SystemService().VmsService().VmService(id)
optimizeCPUSettings := autoPinningPolicy == ovirtsdk.AUTOPINNINGPOLICY_ADJUST
_, err := vmService.AutoPinCpuAndNumaNodes().OptimizeCpuSettings(optimizeCPUSettings).Send()
if err != nil {
return errors.Errorf("failed to set the auto pinning policy on the VM!, %v", err)
}
return nil
}
func mapAutoPinningPolicy(policy string) ovirtsdk.AutoPinningPolicy {
switch policy {
case "none":
return ovirtsdk.AUTOPINNINGPOLICY_DISABLED
case "resize_and_pin":
return ovirtsdk.AUTOPINNINGPOLICY_ADJUST
default:
return ovirtsdk.AUTOPINNINGPOLICY_DISABLED
}
}
func (is *ovirtClient) GetEngineVersion() (*ovirtsdk.Version, error) {
return is.connection.SystemService().Get().MustSend().MustApi().MustProductInfo().MustVersion(), nil
}
// CreateAPIConnection returns a a client to oVirt's API endpoint by using the given credentials
func CreateAPIConnection(creds *Creds) (*ovirtsdk.Connection, error) {
connection, err := ovirtsdk.NewConnectionBuilder().
URL(creds.URL).
Username(creds.Username).
Password(creds.Password).
CAFile(creds.CAFile).
Insecure(creds.Insecure).
Build()
if err != nil {
return nil, errors.Wrap(err, "error creating API connection")
}
return connection, nil
}
// NewClient returns a ovirt client by using the given credentials
func NewClient(creds *Creds) (ovirtclient.Client, error) {
tls := ovirtclient.TLS()
if creds.Insecure {
tls.Insecure()
}
if creds.CAFile != "" {
tls.CACertsFromFile(creds.CAFile)
}
logger := kloglogger.New()
client, err := ovirtclient.New(
creds.URL,
creds.Username,
creds.Password,
tls,
logger,
nil,
)
if err != nil {
return nil, err
}
return client, nil
}