File: preflight_checks_linux.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (717 lines) | stat: -rw-r--r-- 22,420 bytes parent folder | download
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
package preflight

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"regexp"
	"strings"
	"text/template"

	"github.com/Masterminds/semver/v3"
	"github.com/crc-org/crc/v2/pkg/crc/cache"
	"github.com/crc-org/crc/v2/pkg/crc/constants"
	"github.com/crc-org/crc/v2/pkg/crc/daemonclient"
	"github.com/crc-org/crc/v2/pkg/crc/logging"
	"github.com/crc-org/crc/v2/pkg/crc/machine/libvirt"
	"github.com/crc-org/crc/v2/pkg/crc/systemd"
	"github.com/crc-org/crc/v2/pkg/crc/systemd/states"
	crcos "github.com/crc-org/crc/v2/pkg/os"
	"github.com/crc-org/crc/v2/pkg/os/linux"
	"libvirt.org/go/libvirtxml"
)

const (
	// This is defined in https://github.com/crc-org/machine-driver-libvirt/blob/master/go.mod#L5
	minSupportedLibvirtVersion = "8.0.0"
)

func checkRunningInsideWSL2() error {
	version, err := os.ReadFile("/proc/version")
	if err != nil {
		return err
	}

	if strings.Contains(string(version), "Microsoft") {
		logging.Debugf("Running inside WSL2 environment")
		return fmt.Errorf("CRC is unsupported using WSL2")
	}

	return nil
}

func checkVirtualizationEnabled() error {
	logging.Debug("Checking if the vmx/svm flags are present in /proc/cpuinfo")
	// Check if the cpu flags vmx or svm is present
	flags, err := getCPUFlags()
	if err != nil {
		return err
	}

	re := regexp.MustCompile(`(vmx|svm)`)

	cputype := re.FindString(flags)
	if cputype == "" {
		return fmt.Errorf("Virtualization is not available for your CPU")
	}
	logging.Debug("CPU virtualization flags are good")
	return nil
}

func fixVirtualizationEnabled() error {
	return fmt.Errorf("You need to enable virtualization in BIOS")
}

func checkKvmEnabled() error {
	logging.Debug("Checking if /dev/kvm exists")
	// Check if /dev/kvm exists
	if _, err := os.Stat("/dev/kvm"); os.IsNotExist(err) {
		return fmt.Errorf("kvm kernel module is not loaded")
	}
	logging.Debug("/dev/kvm was found")
	return nil
}

func fixKvmEnabled() error {
	logging.Debug("Trying to load kvm module")
	flags, err := getCPUFlags()
	if err != nil {
		return err
	}

	switch {
	case strings.Contains(flags, "vmx"):
		stdOut, stdErr, err := crcos.RunPrivileged("Loading kvm_intel kernel module", "modprobe", "kvm_intel")
		if err != nil {
			return fmt.Errorf("Failed to load kvm intel module: %s %v: %s", stdOut, err, stdErr)
		}
	case strings.Contains(flags, "svm"):
		stdOut, stdErr, err := crcos.RunPrivileged("Loading kvm_amd kernel module", "modprobe", "kvm_amd")
		if err != nil {
			return fmt.Errorf("Failed to load kvm amd module: %s %v: %s", stdOut, err, stdErr)
		}
	default:
		logging.Debug("Unable to detect processor details")
	}

	logging.Debug("kvm module loaded")
	return nil
}

func getLibvirtCapabilities() (*libvirtxml.Caps, error) {
	stdOut, _, err := crcos.RunWithDefaultLocale("virsh", "--readonly", "--connect", "qemu:///system", "capabilities")
	if err != nil {
		stdOut, _, err = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///session", "capabilities")
		if err != nil {
			return nil, fmt.Errorf("Failed to run 'virsh capabilities': %v", err)
		}
	}
	caps := &libvirtxml.Caps{}
	err = caps.Unmarshal(stdOut)
	if err != nil {
		return nil, fmt.Errorf("Error parsing 'virsh capabilities': %v", err)
	}

	return caps, nil
}

func checkLibvirtInstalled() error {
	logging.Debug("Checking if 'virsh' is available")
	path, err := exec.LookPath("virsh")
	if err != nil {
		return fmt.Errorf("Libvirt cli virsh was not found in path")
	}
	logging.Debug("'virsh' was found in ", path)

	logging.Debug("Checking 'virsh capabilities' for libvirtd/qemu availability")
	caps, err := getLibvirtCapabilities()
	if err != nil {
		return err
	}

	foundHvm := false
	for _, guest := range caps.Guests {
		if guest.OSType == "hvm" && guest.Arch.Name == caps.Host.CPU.Arch {
			logging.Debugf("Found %s hypervisor with 'hvm' capabilities", caps.Host.CPU.Arch)
			foundHvm = true
			break
		}
	}
	if !foundHvm {
		return fmt.Errorf("Could not find a %s hypervisor with 'hvm' capabilities", caps.Host.CPU.Arch)
	}

	return nil
}

func fixLibvirtInstalled(distro *linux.OsRelease) func() error {
	return func() error {
		logging.Debug("Trying to install libvirt")
		stdOut, stdErr, err := crcos.RunPrivileged("Installing virtualization packages", "/bin/sh", "-c", installLibvirtCommand(distro))
		if err != nil {
			return fmt.Errorf("Could not install required packages: %s %v: %s", stdOut, err, stdErr)
		}
		logging.Debug("libvirt was successfully installed")
		return nil
	}
}

func installLibvirtCommand(distro *linux.OsRelease) string {
	dnfCommand := "dnf install -y libvirt libvirt-daemon-kvm qemu-kvm"
	switch {
	case distroIsLike(distro, linux.Ubuntu):
		return "apt-get update && apt-get install -y libvirt-daemon libvirt-daemon-system libvirt-clients"
	case distroIsLike(distro, linux.Fedora):
		return dnfCommand
	default:
		logging.Warnf("unsupported distribution %s, trying to install libvirt with dnf", distro)
		return dnfCommand
	}
}

func checkLibvirtVersion() error {
	logging.Debugf("Checking if libvirt version is >=%s", minSupportedLibvirtVersion)
	stdOut, _, err := crcos.RunWithDefaultLocale("virsh", "-v")
	if err != nil {
		return fmt.Errorf("Failed to run virsh")
	}
	installedLibvirtVersion, err := semver.NewVersion(strings.TrimSpace(stdOut))
	if err != nil {
		return fmt.Errorf("Unable to parse installed libvirt version %v", err)
	}
	supportedLibvirtVersion, err := semver.NewVersion(minSupportedLibvirtVersion)
	if err != nil {
		return fmt.Errorf("Unable to parse %s libvirt version %v", minSupportedLibvirtVersion, err)
	}

	if installedLibvirtVersion.LessThan(supportedLibvirtVersion) {
		return fmt.Errorf("libvirt version %s is installed, but %s or higher is required", installedLibvirtVersion.String(), minSupportedLibvirtVersion)
	}

	return nil
}

func checkUserPartOfLibvirtGroup() error {
	logging.Debug("Checking if current user is part of the libvirt group")

	currentUser, err := user.Current()
	if err != nil {
		logging.Debugf("user.Current() failed: %v", err)
		return fmt.Errorf("Failed to get current user id")
	}
	gids, err := currentUser.GroupIds()
	if err != nil {
		logging.Debugf("currentUser.GroupIds() failed: %v", err)
		return fmt.Errorf("Failed to get the groups user '%s' belongs to", currentUser.Username)
	}
	for _, gid := range gids {
		group, err := user.LookupGroupId(gid)
		if err != nil {
			logging.Debugf("Failed to lookup group id %s: %v", gid, err)
			continue
		}
		if group.Name == "libvirt" {
			logging.Debug("Current user is already in the libvirt group")
			return nil
		}
	}

	return fmt.Errorf("%s is not part of the libvirt group", currentUser.Username)
}

func fixUserPartOfLibvirtGroup() error {
	logging.Debug("Adding current user to the libvirt group")
	currentUser, err := user.Current()
	if err != nil {
		logging.Debugf("user.Current() failed: %v", err)
		return fmt.Errorf("Failed to get current user id")
	}
	_, _, err = crcos.RunPrivileged("Adding user to the libvirt group", "usermod", "-a", "-G", "libvirt", currentUser.Username)
	if err != nil {
		return fmt.Errorf("Failed to add user to libvirt group")
	}
	logging.Debug("Current user is in the libvirt group")

	return err
}

func checkCurrentGroups(distro *linux.OsRelease) func() error {
	return func() error {
		if !distroIsLike(distro, linux.Ubuntu) {
			return nil
		}

		// After adding the user to the libvirt group, they need to relogin for the new group to be used by the currrent shell
		gids, err := os.Getgroups()
		if err != nil {
			return err
		}
		for _, gid := range gids {
			group, err := user.LookupGroupId(fmt.Sprintf("%d", gid))
			if err != nil {
				logging.Debugf("Failed to lookup group id %d: %v", gid, err)
				continue
			}
			if group.Name == "libvirt" {
				logging.Debug("libvirt group is active for the current user/process")
				return nil
			}
		}
		return fmt.Errorf("User in the currently active process is not part of the libvirt group")
	}
}

func systemdUnitRunning(sd *systemd.Commander, unitName string) bool {
	status, err := sd.Status(unitName)
	if err != nil {
		logging.Debugf("Could not get %s  status: %v", unitName, err)
		return false
	}
	switch status {
	case states.Running:
		logging.Debugf("%s is running", unitName)
		return true
	case states.Listening:
		logging.Debugf("%s is listening", unitName)
		return true
	default:
		logging.Debugf("%s is neither running nor listening", unitName)
		return false
	}
}

const (
	vsockUnitName     = "crc-vsock.socket"
	vsockUnitTemplate = `[Unit]
Description=CRC vsock socket

[Socket]
ListenStream=vsock::%d
Service=crc-daemon.service

[Install]
WantedBy=default.target
`

	httpUnitName = "crc-http.socket"
	httpUnit     = `[Unit]
Description=CRC HTTP socket

[Socket]
ListenStream=%h/.crc/crc-http.sock
Service=crc-daemon.service

[Install]
WantedBy=default.target
`

	daemonUnitName     = "crc-daemon.service"
	daemonUnitTemplate = `
[Unit]
Description=CRC daemon
Requires=crc-http.socket
Requires=crc-vsock.socket

[Service]
# This allows systemd to know when startup is not complete (for example, because of a preflight failure)
# daemon.SdNotify(false, daemon.SdNotifyReady) must be called before the startup is successful
Type=notify
ExecStart=%s daemon
`
)

var vsockUnit = fmt.Sprintf(vsockUnitTemplate, constants.DaemonVsockPort)

func checkSystemdUnit(unitName string, unitContent string, shouldBeRunning bool) error {
	sd := systemd.NewHostSystemdCommander().User()

	logging.Debugf("Checking if %s is running", unitName)
	running := systemdUnitRunning(sd, unitName)
	if !running && shouldBeRunning {
		return unitShouldBeRunningErr(unitName)
	} else if running && !shouldBeRunning {
		return unitShouldNotBeRunningErr(unitName)
	}

	logging.Debugf("Checking if %s has the expected content", unitName)
	unitPath := systemd.UserUnitPath(unitName)
	return crcos.FileContentMatches(unitPath, []byte(unitContent))
}

func daemonUnitContent() string {
	return fmt.Sprintf(daemonUnitTemplate, constants.CrcSymlinkPath)
}

func checkDaemonSystemdSockets() error {
	logging.Debug("Checking crc daemon systemd socket units")

	if err := checkSystemdUnit(httpUnitName, httpUnit, true); err != nil {
		return err
	}

	return checkSystemdUnit(vsockUnitName, vsockUnit, true)
}

func checkDaemonSystemdService() error {
	logging.Debug("Checking crc daemon systemd service")

	// the daemon should not be running at the end of setup, as it must be restarted on upgrades
	shouldNotBeRunningErr := checkSystemdUnit(daemonUnitName, daemonUnitContent(), false)
	if shouldNotBeRunningErr == nil {
		return nil
	}
	if !errors.Is(shouldNotBeRunningErr, unitShouldNotBeRunningErr(daemonUnitName)) {
		return shouldNotBeRunningErr
	}
	// daemon is running, check its version
	version, err := daemonclient.GetVersionFromDaemonAPI()
	if err != nil {
		return shouldNotBeRunningErr
	}
	return daemonclient.CheckVersionMismatch(version)
}

func fixSystemdUnit(unitName string, unitContent string, shouldBeRunning bool) error {
	logging.Debugf("Setting up %s", unitName)

	sd := systemd.NewHostSystemdCommander().User()

	if err := os.MkdirAll(systemd.UserUnitsDir(), 0750); err != nil {
		return err
	}
	unitPath := systemd.UserUnitPath(unitName)
	if crcos.FileContentMatches(unitPath, []byte(unitContent)) != nil {
		logging.Debugf("Creating %s", unitPath)
		if err := os.WriteFile(unitPath, []byte(unitContent), 0600); err != nil {
			return err
		}
		_ = sd.DaemonReload()
	}

	running := systemdUnitRunning(sd, unitName)
	if !running && shouldBeRunning {
		logging.Debugf("Starting %s", unitName)
		if err := sd.Enable(unitName); err != nil {
			return err
		}
		return sd.Start(unitName)
	} else if running && !shouldBeRunning {
		logging.Debugf("Stopping %s", unitName)
		return sd.Stop(unitName)
	}

	return nil
}

func fixDaemonSystemdSockets() error {
	logging.Debugf("Setting up crc daemon systemd socket units")
	if err := fixSystemdUnit(httpUnitName, httpUnit, true); err != nil {
		return err
	}

	return fixSystemdUnit(vsockUnitName, vsockUnit, true)
}

func fixDaemonSystemdService() error {
	logging.Debugf("Setting up crc daemon systemd unit")
	return fixSystemdUnit(daemonUnitName, daemonUnitContent(), false)
}

func removeDaemonSystemdSockets() error {
	logging.Debugf("Removing crc daemon systemd socket units")

	sd := systemd.NewHostSystemdCommander().User()

	_ = sd.Stop(httpUnitName)
	os.Remove(systemd.UserUnitPath(httpUnitName))

	_ = sd.Stop(vsockUnitName)
	os.Remove(systemd.UserUnitPath(vsockUnitName))

	return nil
}

func removeDaemonSystemdService() error {
	logging.Debugf("Removing crc daemon systemd service")

	sd := systemd.NewHostSystemdCommander().User()

	_ = sd.Stop(daemonUnitName)
	os.Remove(systemd.UserUnitPath(daemonUnitName))

	return nil
}

func warnNoDaemonAutostart() error {
	// only purpose of this check is to trigger a warning for RHEL7/CentOS7 users
	logging.Warnf("systemd --user is not available, crc daemon won't be autostarted and must be run manually before using CRC")
	return nil
}

func checkLibvirtServiceRunning() error {
	logging.Debug("Checking if libvirtd service is running")
	sd := systemd.NewHostSystemdCommander()

	libvirtSystemdUnits := []string{"virtqemud.socket", "libvirtd.socket", "virtqemud.service", "libvirtd.service"}
	for _, unit := range libvirtSystemdUnits {
		if systemdUnitRunning(sd, unit) {
			return nil
		}
	}

	logging.Warnf("No active (running) libvirtd systemd unit could be found - make sure one of libvirt systemd units is enabled so that it's autostarted at boot time.")
	return fmt.Errorf("found no active libvirtd systemd unit")
}

func fixLibvirtServiceRunning() error {
	logging.Debug("Starting libvirtd.service")
	sd := systemd.NewHostSystemdCommander()
	/* split libvirt daemon is a bit tricky to startup properly as we'd
	* need to start multiple components by hand, so we just start the
	* monolithic daemon
	 */
	err := sd.Start("libvirtd")
	if err != nil {
		return fmt.Errorf("Failed to start libvirt service")
	}
	logging.Debug("libvirtd.service is running")
	return nil
}

func checkMachineDriverLibvirtInstalled() error {
	machineDriverLibvirt := cache.NewMachineDriverLibvirtCache()

	logging.Debugf("Checking if %s is installed", machineDriverLibvirt.GetExecutableName())

	if !machineDriverLibvirt.IsCached() {
		return fmt.Errorf("%s executable is not cached", machineDriverLibvirt.GetExecutableName())
	}
	if err := machineDriverLibvirt.CheckVersion(); err != nil {
		return err
	}
	logging.Debugf("%s is already installed", machineDriverLibvirt.GetExecutableName())
	return nil
}

func fixMachineDriverLibvirtInstalled() error {
	machineDriverLibvirt := cache.NewMachineDriverLibvirtCache()

	logging.Debugf("Installing %s", machineDriverLibvirt.GetExecutableName())

	if err := machineDriverLibvirt.EnsureIsCached(); err != nil {
		return fmt.Errorf("Unable to download %s: %v", machineDriverLibvirt.GetExecutableName(), err)
	}
	logging.Debugf("%s is installed in %s", machineDriverLibvirt.GetExecutableName(), filepath.Dir(machineDriverLibvirt.GetExecutablePath()))
	return nil
}

func checkLibvirtCrcNetworkAvailable() error {
	logging.Debug("Checking if libvirt 'crc' network exists")
	_, _, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-info", "crc")
	if err != nil {
		return fmt.Errorf("Libvirt network crc not found")
	}

	return checkLibvirtCrcNetworkDefinition()
}

func getLibvirtNetworkXML() (string, error) {
	config := libvirt.NetworkConfig{
		NetworkName: libvirt.DefaultNetwork,
		MAC:         libvirt.MACAddress,
		IP:          libvirt.IPAddress,
	}
	t, err := template.New("netxml").Parse(libvirt.NetworkTemplate)
	if err != nil {
		return "", err
	}
	var netXMLDef strings.Builder
	err = t.Execute(&netXMLDef, config)
	if err != nil {
		return "", err
	}

	return netXMLDef.String(), nil
}

func fixLibvirtCrcNetworkAvailable() error {
	logging.Debug("Creating libvirt 'crc' network")

	netXMLDef, err := getLibvirtNetworkXML()
	if err != nil {
		logging.Debugf("getLibvirtNetworkXML() failed: %v", err)
		return fmt.Errorf("Failed to read libvirt 'crc' network definition")
	}

	// For time being we are going to override the crc network according what we have in our binary template.
	// We also don't care about the error or output from those commands atm.
	// #nosec G204
	_, _, _ = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-destroy", libvirt.DefaultNetwork)
	// #nosec G204
	_, _, _ = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-undefine", libvirt.DefaultNetwork)
	// Create the network according to our defined template
	cmd := exec.Command("virsh", "--connect", "qemu:///system", "net-define", "/dev/stdin")
	cmd.Stdin = strings.NewReader(netXMLDef)
	buf := new(bytes.Buffer)
	cmd.Stderr = buf
	err = cmd.Run()
	if err != nil {
		logging.Debugf("%v : %s", err, buf.String())
		return fmt.Errorf("Failed to create libvirt 'crc' network: %v - %s", err, buf.String())
	}
	logging.Debug("libvirt 'crc' network created")
	return nil
}

func removeLibvirtCrcNetwork() error {
	logging.Debug("Removing libvirt 'crc' network")
	_, _, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-info", libvirt.DefaultNetwork)
	if err != nil {
		// Ignore if no crc network exists for libvirt
		// User may have manually deleted the `crc` network from libvirt
		return nil
	}
	_, stderr, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-destroy", libvirt.DefaultNetwork)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		return fmt.Errorf("Failed to destroy libvirt 'crc' network")
	}

	_, stderr, err = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-undefine", libvirt.DefaultNetwork)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		return fmt.Errorf("Failed to undefine libvirt 'crc' network")
	}
	logging.Debug("libvirt 'crc' network removed")
	return nil
}

func removeCrcVM() error {
	stdout, _, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "domstate", constants.DefaultName)
	if err != nil {
		//  User may have run `crc delete` before `crc cleanup`
		//  in that case there is no crc vm so return early.
		return nil
	}
	if strings.TrimSpace(stdout) == "running" {
		_, stderr, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "destroy", constants.DefaultName)
		if err != nil {
			logging.Debugf("%v : %s", err, stderr)
			return fmt.Errorf("Failed to destroy 'crc' VM")
		}
	}
	_, stderr, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "undefine", constants.DefaultName)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		return fmt.Errorf("Failed to undefine 'crc' VM")
	}
	logging.Debug("'crc' VM is removed")
	return nil
}

func removeLibvirtStoragePool() error {
	_, stderr, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "pool-info", constants.DefaultName)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		// Pool does not exist
		return nil
	}
	_, stderr, err = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "pool-destroy", constants.DefaultName)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		// ignore error, we want to try to delete the pool regardless of success or not
	}
	_, stderr, err = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "pool-undefine", constants.DefaultName)
	if err != nil {
		logging.Debugf("%v : %s", err, stderr)
		return fmt.Errorf("Failed to undefine 'crc' libvirt storage pool")
	}
	logging.Debug("'crc' libvirt storage has been removed")
	return nil
}

func trimSpacesFromXML(str string) string {
	strs := strings.Split(str, "\n")
	var builder strings.Builder
	for _, s := range strs {
		builder.WriteString(strings.TrimSpace(s))
	}

	return builder.String()
}

func checkLibvirtCrcNetworkDefinition() error {
	logging.Debug("Checking if libvirt 'crc' definition is up to date")
	stdOut, _, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-dumpxml", "--inactive", "crc")
	if err != nil {
		return fmt.Errorf("Failed to get 'crc' network XML: %s", err)
	}
	stdOut = trimSpacesFromXML(stdOut)

	netXMLDef, err := getLibvirtNetworkXML()
	if err != nil {
		return fmt.Errorf("Failed to generate 'crc' network XML from template: %s", err)
	}
	netXMLDef = trimSpacesFromXML(netXMLDef)

	if stdOut != netXMLDef {
		logging.Debugf("libvirt 'crc' network definition does not have the expected value")
		logging.Debugf("expected: %s", netXMLDef)
		logging.Debugf("current: %s", stdOut)
		return fmt.Errorf("libvirt 'crc' network definition is incorrect")
	}
	logging.Debugf("libvirt 'crc' network has the expected value")
	return nil
}

func checkLibvirtCrcNetworkActive() error {
	logging.Debug("Checking if libvirt 'crc' network is active")
	stdOut, _, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-info", "crc")
	if err != nil {
		return fmt.Errorf("Failed to query 'crc' network information")
	}
	outputSlice := strings.Split(stdOut, "\n")

	for _, stdOut = range outputSlice {
		stdOut = strings.TrimSpace(stdOut)
		if strings.HasPrefix(stdOut, "Active") && strings.Contains(stdOut, "yes") {
			logging.Debug("libvirt 'crc' network is already active")
			return nil
		}
	}
	return fmt.Errorf("Libvirt crc network is not active")
}

func fixLibvirtCrcNetworkActive() error {
	logging.Debug("Starting libvirt 'crc' network")
	stdOut, stdErr, err := crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-start", "crc")
	if err != nil {
		return fmt.Errorf("Failed to start libvirt 'crc' network %s %v: %s", stdOut, err, stdErr)
	}
	stdOut, stdErr, err = crcos.RunWithDefaultLocale("virsh", "--connect", "qemu:///system", "net-autostart", "crc")
	if err != nil {
		return fmt.Errorf("Failed to autostart libvirt 'crc' network %s %v: %s", stdOut, err, stdErr)
	}
	logging.Debug("libvirt 'crc' network started")
	return nil
}

func getCPUFlags() (string, error) {
	// Check if the cpu flags vmx or svm is present
	out, err := os.ReadFile("/proc/cpuinfo")
	if err != nil {
		logging.Debugf("Failed to read /proc/cpuinfo: %v", err)
		return "", fmt.Errorf("Failed to read /proc/cpuinfo")
	}
	re := regexp.MustCompile(`flags.*:.*`)

	flags := re.FindString(string(out))
	if flags == "" {
		return "", fmt.Errorf("Could not find cpu flags from /proc/cpuinfo")
	}
	return flags, nil
}