File: vswitch_windows.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 (47 lines) | stat: -rw-r--r-- 1,216 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
package network

import (
	"fmt"
	"strings"

	"github.com/crc-org/crc/v2/pkg/os/windows/powershell"
)

const hypervDefaultVirtualSwitchID = "c08cb7b8-9b3c-408e-8e30-5e16a3aeb444"

func SelectSwitchByNameOrDefault(name string) (bool, string) {
	// if named exists
	if ExistsSwitchByName(name) {
		return true, name
	}

	// else use Default
	return GetDefaultSwitchName()
}

func ExistsSwitchByName(name string) bool {
	getSwitchByNameCmd := fmt.Sprintf("Get-VMSwitch %s | ForEach-Object { $_.Name }", name)
	stdOut, stdErr, _ := powershell.Execute(getSwitchByNameCmd)

	// If stdErr contains the command then execution failed
	if strings.Contains(stdErr, "Get-VMSwitch") {
		return false
	}

	if strings.Contains(stdOut, name) {
		return true
	}
	return false
}

func GetDefaultSwitchName() (bool, string) {
	getDefaultSwitchNameCmd := fmt.Sprintf("[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-VMSwitch -Id %s | ForEach-Object { $_.Name }", hypervDefaultVirtualSwitchID)
	stdOut, stdErr, _ := powershell.Execute(getDefaultSwitchNameCmd)

	// If stdErr contains the command then execution failed
	if strings.Contains(stdErr, "Get-VMSwitch") {
		return false, ""
	}

	return true, strings.TrimSpace(stdOut)
}