-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathbootstrap.go
More file actions
613 lines (534 loc) · 14.4 KB
/
Copy pathbootstrap.go
File metadata and controls
613 lines (534 loc) · 14.4 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
package baremetal
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/url"
"os"
"strings"
igntypes "github.com/coreos/ignition/v2/config/v3_2/types"
"github.com/digitalocean/go-libvirt"
"github.com/sirupsen/logrus"
"libvirt.org/go/libvirtxml"
"github.com/openshift/assisted-image-service/pkg/isoeditor"
"github.com/openshift/installer/pkg/asset/ignition"
assetrhcos "github.com/openshift/installer/pkg/asset/rhcos"
)
func newDomain(name string) libvirtxml.Domain {
domainDef := libvirtxml.Domain{
Name: name,
OS: &libvirtxml.DomainOS{
Type: &libvirtxml.DomainOSType{
Type: "hvm",
},
},
Devices: &libvirtxml.DomainDeviceList{
Graphics: []libvirtxml.DomainGraphic{
{
Spice: &libvirtxml.DomainGraphicSpice{
AutoPort: "yes",
},
},
},
Channels: []libvirtxml.DomainChannel{
{
Source: &libvirtxml.DomainChardevSource{
UNIX: &libvirtxml.DomainChardevSourceUNIX{},
},
Target: &libvirtxml.DomainChannelTarget{
VirtIO: &libvirtxml.DomainChannelTargetVirtIO{
Name: "org.qemu.guest_agent.0",
},
},
},
},
Controllers: []libvirtxml.DomainController{
{
Type: "scsi",
Model: "virtio-scsi",
},
},
},
Features: &libvirtxml.DomainFeatureList{
PAE: &libvirtxml.DomainFeature{},
ACPI: &libvirtxml.DomainFeature{},
APIC: &libvirtxml.DomainFeatureAPIC{},
},
CPU: &libvirtxml.DomainCPU{
Mode: "host-passthrough",
},
Memory: &libvirtxml.DomainMemory{
Value: 6,
Unit: "GiB",
},
VCPU: &libvirtxml.DomainVCPU{
Value: 4,
},
}
targetPort := uint(0)
console := libvirtxml.DomainConsole{
Target: &libvirtxml.DomainConsoleTarget{
Port: &targetPort,
},
}
domainDef.Devices.Consoles = append(domainDef.Devices.Consoles, console)
serialLogPath := fmt.Sprintf("/var/log/libvirt/qemu/%s-serial0.log", name)
serial := libvirtxml.DomainSerial{
Log: &libvirtxml.DomainChardevLog{
File: serialLogPath,
Append: "on",
},
}
domainDef.Devices.Serials = append(domainDef.Devices.Serials, serial)
domainDef.Devices.Graphics = []libvirtxml.DomainGraphic{
{
VNC: &libvirtxml.DomainGraphicVNC{
AutoPort: "yes",
Listeners: []libvirtxml.DomainGraphicListener{
{
Address: &libvirtxml.DomainGraphicListenerAddress{
Address: "",
},
},
},
},
},
}
if v := os.Getenv("TERRAFORM_LIBVIRT_TEST_DOMAIN_TYPE"); v != "" {
domainDef.Type = v
} else {
domainDef.Type = "kvm"
}
rngDev := os.Getenv("TF_LIBVIRT_RNG_DEV")
if rngDev == "" {
rngDev = "/dev/urandom"
}
domainDef.Devices.RNGs = []libvirtxml.DomainRNG{
{
Model: "virtio",
Backend: &libvirtxml.DomainRNGBackend{
Random: &libvirtxml.DomainRNGBackendRandom{Device: rngDev},
},
},
}
return domainDef
}
func createStoragePool(virConn *libvirt.Libvirt, config baremetalConfig) (libvirt.StoragePool, error) {
// TODO: check if unique
bootstrapPool := libvirtxml.StoragePool{
Type: "dir",
Name: fmt.Sprintf("%s-bootstrap", config.ClusterID),
Target: &libvirtxml.StoragePoolTarget{
Path: fmt.Sprintf("/var/lib/libvirt/openshift-images/%s-bootstrap", config.ClusterID),
},
}
bootstrapPoolXML, err := xml.Marshal(bootstrapPool)
if err != nil {
return libvirt.StoragePool{}, err
}
pool, err := virConn.StoragePoolDefineXML(string(bootstrapPoolXML), 0)
if err != nil {
return libvirt.StoragePool{}, err
}
err = virConn.StoragePoolBuild(pool, libvirt.StoragePoolBuildNew)
if err != nil {
return libvirt.StoragePool{}, err
}
err = virConn.StoragePoolSetAutostart(pool, 1)
if err != nil {
return libvirt.StoragePool{}, err
}
err = virConn.StoragePoolCreate(pool, libvirt.StoragePoolCreateNormal)
if err != nil {
return libvirt.StoragePool{}, err
}
err = virConn.StoragePoolRefresh(pool, 0)
if err != nil {
return libvirt.StoragePool{}, err
}
return pool, nil
}
func getLiveISO(config baremetalConfig, arch string) (string, error) {
fetcher := assetrhcos.NewBaseISOFetcher(
assetrhcos.NewReleasePayload(
assetrhcos.ExtractConfig{},
config.ReleaseImagePullSpec,
config.PullSecret,
config.MirrorConfig,
), config.OSImageStream)
return fetcher.GetBaseISOFilename(context.Background(), arch)
}
func bootstrapIgnition(config baremetalConfig) (*isoeditor.IgnitionContent, error) {
ign := &igntypes.Config{
Ignition: igntypes.Ignition{
Version: igntypes.MaxVersion.String(),
},
}
fsLabel := "var"
partDev := fmt.Sprintf("/dev/disk/by-partlabel/%s", fsLabel)
format := "xfs"
path := "/var"
ign.Storage.Disks = append(ign.Storage.Disks, igntypes.Disk{
Device: "/dev/vda",
Partitions: []igntypes.Partition{
{
Number: 1,
Label: &fsLabel,
},
},
})
ign.Storage.Filesystems = append(ign.Storage.Filesystems, igntypes.Filesystem{
Device: partDev,
Label: &fsLabel,
Format: &format,
Path: &path,
})
systemdPartDev := strings.ReplaceAll(strings.ReplaceAll(strings.TrimLeft(partDev, "/"), "-", "\\x2d"), "/", "-")
enabled := true
mountUnit := fmt.Sprintf(`[Unit]
Requires=systemd-fsck@%s.service
After=systemd-fsck@%s.service
[Mount]
Where=%s
What=%s
Type=%s
[Install]
RequiredBy=localfs.target
`,
systemdPartDev, systemdPartDev, path, partDev, format)
ign.Systemd.Units = append(ign.Systemd.Units, igntypes.Unit{
Name: fmt.Sprintf("%s.mount", fsLabel),
Contents: &mountUnit,
Enabled: &enabled,
})
ign.Storage.Files = append(ign.Storage.Files, ignition.FileFromString("/etc/no-var-tmpfs", "root", 0o440, ""))
ignData, err := ignition.Marshal(ign)
if err != nil {
return nil, fmt.Errorf("failed to marshal bootstrap Ignition config: %w", err)
}
return &isoeditor.IgnitionContent{
Config: []byte(config.IgnitionBootstrap),
SystemConfigs: map[string][]byte{
"30-scratch-disk.ign": ignData,
},
}, nil
}
func buildBootstrapKargs(arch string, fips bool) []byte {
consoleDevice := map[string]string{
"x86_64": "ttyS0,115200n8",
"aarch64": "ttyAMA0,115200",
"s390x": "ttysclp0",
"ppc64le": "hvc0",
}
var kargs string
if dev, ok := consoleDevice[arch]; ok {
kargs += " console=" + dev
}
if fips {
kargs += " fips=1"
}
if kargs == "" {
return nil
}
return []byte(kargs + "\n")
}
func createLiveVolume(virConn *libvirt.Libvirt, config baremetalConfig, pool libvirt.StoragePool) (libvirt.StorageVol, error) {
capabilities, err := getHostCapabilities(virConn)
if err != nil {
return libvirt.StorageVol{}, fmt.Errorf("failed to get libvirt capabilities: %w", err)
}
arch := capabilities.Host.CPU.Arch
isoFile, err := getLiveISO(config, arch)
if err != nil {
return libvirt.StorageVol{}, err
}
defer os.Remove(isoFile)
ignition, err := bootstrapIgnition(config)
if err != nil {
return libvirt.StorageVol{}, err
}
kargsBytes := buildBootstrapKargs(arch, config.FIPS)
stream, err := isoeditor.NewRHCOSStreamReader(
isoFile,
ignition,
nil,
kargsBytes,
)
if err != nil {
return libvirt.StorageVol{}, err
}
defer stream.Close()
size, err := stream.Seek(0, io.SeekEnd)
if err != nil {
return libvirt.StorageVol{}, err
}
_, err = stream.Seek(0, io.SeekStart)
if err != nil {
return libvirt.StorageVol{}, err
}
bootstrapLiveVolume := libvirtxml.StorageVolume{
Name: fmt.Sprintf("%s-live-provisioner", config.ClusterID),
Type: "file",
Target: &libvirtxml.StorageVolumeTarget{
Format: &libvirtxml.StorageVolumeTargetFormat{
Type: "iso",
},
Permissions: &libvirtxml.StorageVolumeTargetPermissions{
Mode: "644",
},
},
Capacity: &libvirtxml.StorageVolumeSize{
Value: uint64(size),
},
}
bootstrapLiveVolumeXML, err := xml.Marshal(bootstrapLiveVolume)
if err != nil {
return libvirt.StorageVol{}, err
}
liveVolume, err := virConn.StorageVolCreateXML(pool, string(bootstrapLiveVolumeXML), 0)
if err != nil {
return libvirt.StorageVol{}, err
}
err = virConn.StorageVolUpload(liveVolume, stream, 0, uint64(size), 0)
if err != nil {
return libvirt.StorageVol{}, err
}
return liveVolume, nil
}
func createScratchVolume(virConn *libvirt.Libvirt, clusterID string, pool libvirt.StoragePool) (libvirt.StorageVol, error) {
vol := libvirtxml.StorageVolume{
Name: fmt.Sprintf("%s-scratch", clusterID),
Target: &libvirtxml.StorageVolumeTarget{
Format: &libvirtxml.StorageVolumeTargetFormat{
Type: "qcow2",
},
Permissions: &libvirtxml.StorageVolumeTargetPermissions{
Mode: "644",
},
},
Capacity: &libvirtxml.StorageVolumeSize{
Unit: "GiB",
Value: 20,
},
}
scratchVolumeXML, err := xml.Marshal(vol)
if err != nil {
return libvirt.StorageVol{}, err
}
scratchVolume, err := virConn.StorageVolCreateXML(pool, string(scratchVolumeXML), 0)
if err != nil {
return libvirt.StorageVol{}, err
}
return scratchVolume, nil
}
func getHostCapabilities(virConn *libvirt.Libvirt) (libvirtxml.Caps, error) {
var caps libvirtxml.Caps
capsBytes, err := virConn.Capabilities()
if err != nil {
return caps, err
}
err = xml.Unmarshal(capsBytes, &caps)
if err != nil {
return caps, err
}
return caps, nil
}
func configureDomainArch(dom *libvirtxml.Domain, arch string) {
dom.OS.Type.Arch = arch
switch arch {
case "x86_64":
dom.OS.Type.Machine = "q35"
dom.OS.Firmware = "efi"
case "aarch64":
// reference: https://libvirt.org/formatdomain.html#bios-bootloader
dom.OS.Firmware = "efi"
fallthrough
case "s390x", "ppc64le":
dom.Devices.Graphics = nil
}
}
func createBootstrapDomain(virConn *libvirt.Libvirt, config baremetalConfig, pool libvirt.StoragePool, liveCDVolume, scratchVolume libvirt.StorageVol) error {
bootstrapDom := newDomain(fmt.Sprintf("%s-bootstrap", config.ClusterID))
capabilities, err := getHostCapabilities(virConn)
if err != nil {
return fmt.Errorf("failed to get libvirt capabilities: %w", err)
}
arch := capabilities.Host.CPU.Arch
configureDomainArch(&bootstrapDom, arch)
for _, bridge := range config.Bridges {
netIface := libvirtxml.DomainInterface{
Model: &libvirtxml.DomainInterfaceModel{
Type: "virtio",
},
MAC: &libvirtxml.DomainInterfaceMAC{
Address: bridge.MAC,
},
Source: &libvirtxml.DomainInterfaceSource{
Bridge: &libvirtxml.DomainInterfaceSourceBridge{
Bridge: bridge.Name,
},
},
}
bootstrapDom.Devices.Interfaces = append(bootstrapDom.Devices.Interfaces, netIface)
}
liveCD := libvirtxml.DomainDisk{
Device: "cdrom",
Target: &libvirtxml.DomainDiskTarget{
Bus: "scsi",
Dev: "sda",
},
Driver: &libvirtxml.DomainDiskDriver{
Name: "qemu",
Type: "raw",
},
Source: &libvirtxml.DomainDiskSource{
Volume: &libvirtxml.DomainDiskSourceVolume{
Pool: pool.Name,
Volume: liveCDVolume.Name,
},
},
Boot: &libvirtxml.DomainDeviceBoot{
Order: 1,
},
}
if arch == "x86_64" {
// x86 traditionally uses IDE or SATA (only the latter is supported
// with the q35 machine type) for cdrom devices
liveCD.Target.Bus = "sata"
}
scratchDisk := libvirtxml.DomainDisk{
Device: "disk",
Target: &libvirtxml.DomainDiskTarget{
Bus: "virtio",
Dev: "vda",
},
Driver: &libvirtxml.DomainDiskDriver{
Name: "qemu",
Type: "qcow2",
},
Source: &libvirtxml.DomainDiskSource{
Volume: &libvirtxml.DomainDiskSourceVolume{
Pool: pool.Name,
Volume: scratchVolume.Name,
},
},
}
bootstrapDom.Devices.Disks = append(bootstrapDom.Devices.Disks, liveCD, scratchDisk)
bootstrapDom.Resource = nil
bootstrapDomXML, err := xml.Marshal(bootstrapDom)
if err != nil {
return err
}
dom, err := virConn.DomainDefineXML(string(bootstrapDomXML))
if err != nil {
return err
}
err = virConn.DomainCreate(dom)
if err != nil {
return err
}
return nil
}
func createBootstrap(config baremetalConfig) error {
logrus.Debug("libvirt: Creating bootstrap")
uri, err := url.Parse(config.LibvirtURI)
if err != nil {
return err
}
virConn, err := libvirt.ConnectToURI(uri)
if err != nil {
return err
}
logrus.Debug(" Creating storage pool")
pool, err := createStoragePool(virConn, config)
if err != nil {
return err
}
logrus.Debug(" Creating live volume")
liveVolume, err := createLiveVolume(virConn, config, pool)
if err != nil {
return err
}
logrus.Debug(" Creating scratch volume")
scratchVolume, err := createScratchVolume(virConn, config.ClusterID, pool)
if err != nil {
return err
}
logrus.Debug(" Creating bootstrap domain")
err = createBootstrapDomain(virConn, config, pool, liveVolume, scratchVolume)
if err != nil {
return err
}
return nil
}
func destroyBootstrap(config baremetalConfig) error {
logrus.Debug("libvirt: Destroying bootstrap")
uri, err := url.Parse(config.LibvirtURI)
if err != nil {
return err
}
virConn, err := libvirt.ConnectToURI(uri)
if err != nil {
return err
}
name := fmt.Sprintf("%s-bootstrap", config.ClusterID)
dom, err := virConn.DomainLookupByName(name)
if err != nil {
return err
}
logrus.Debug(" Destroying domain")
err = virConn.DomainDestroy(dom)
if err != nil {
return err
}
logrus.Debug(" Undefining domain")
if err := virConn.DomainUndefineFlags(dom, libvirt.DomainUndefineNvram|libvirt.DomainUndefineSnapshotsMetadata|libvirt.DomainUndefineManagedSave|libvirt.DomainUndefineCheckpointsMetadata); err != nil {
var libvirtErr *libvirt.Error
if !errors.As(err, &libvirtErr) {
return fmt.Errorf("failed to cast to libvirt.Error: %w", err)
}
if libvirtErr.Code == uint32(libvirt.ErrNoSupport) || libvirtErr.Code == uint32(libvirt.ErrInvalidArg) {
logrus.Printf("libvirt does not support undefine flags: will try again without flags")
if err := virConn.DomainUndefine(dom); err != nil {
return fmt.Errorf("couldn't undefine libvirt domain: %w", err)
}
} else {
return fmt.Errorf("couldn't undefine libvirt domain with flags: %w", err)
}
}
pool, err := virConn.StoragePoolLookupByName(name)
if err != nil {
return err
}
vol, err := virConn.StorageVolLookupByName(pool, fmt.Sprintf("%s-live-provisioner", config.ClusterID))
if err != nil {
return err
}
logrus.Debug(" Deleting live volume")
err = virConn.StorageVolDelete(vol, libvirt.StorageVolDeleteNormal)
if err != nil {
return err
}
vol, err = virConn.StorageVolLookupByName(pool, fmt.Sprintf("%s-scratch", config.ClusterID))
if err != nil {
return err
}
logrus.Debug(" Deleting scratch volume")
err = virConn.StorageVolDelete(vol, libvirt.StorageVolDeleteNormal)
if err != nil {
return err
}
logrus.Debug(" Destroying pool")
err = virConn.StoragePoolDestroy(pool)
if err != nil {
return err
}
logrus.Debug(" Deleting pool")
err = virConn.StoragePoolDelete(pool, libvirt.StoragePoolDeleteNormal)
if err != nil {
return err
}
return nil
}