cmd/hyperv: Use Default Switch if present

The Windows 10 Fall Creators Update added a new 'Default
Switch' (which is a NAT switch). Use it if present and the
user has not specified a switch.

Also, handle External switches with spaces in them.

Signed-off-by: Rolf Neugebauer <rolf.neugebauer@docker.com>
This commit is contained in:
Rolf Neugebauer 2018-01-24 16:52:17 +00:00
parent e42a06c30b
commit 83a7e29730

View File

@ -31,7 +31,7 @@ func runHyperV(args []string) {
var disks Disks var disks Disks
flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]") flags.Var(&disks, "disk", "Disk config. [file=]path[,size=1G]")
switchName := flags.String("switch", "", "Which Hyper-V switch to attache the VM to. If left empty, the first external switch found is used.") switchName := flags.String("switch", "", "Which Hyper-V switch to attache the VM to. If left empty, either 'Default Switch' or the first external switch found is used.")
if err := flags.Parse(args); err != nil { if err := flags.Parse(args); err != nil {
log.Fatal("Unable to parse args") log.Fatal("Unable to parse args")
@ -235,14 +235,20 @@ func hypervChecks() {
// or find the first external switch. // or find the first external switch.
func hypervGetSwitch(name string) (string, error) { func hypervGetSwitch(name string) (string, error) {
if name != "" { if name != "" {
_, _, err := poshCmd("Get-VMSwitch", name) if _, _, err := poshCmd("Get-VMSwitch", name); err != nil {
if err != nil {
return "", fmt.Errorf("Could not find switch %s: %v", name, err) return "", fmt.Errorf("Could not find switch %s: %v", name, err)
} }
return name, nil return name, nil
} }
out, _, err := poshCmd("get-vmswitch | Format-Table -Property Name, SwitchType -HideTableHeaders") // The Windows 10 Fall Creators Update adds a new 'Default
// Switch'. Check if it is present and if so, use it.
name = "Default Switch"
if _, _, err := poshCmd("Get-VMSwitch", name); err == nil {
return name, nil
}
out, _, err := poshCmd("Get-VMSwitch | Format-Table -Property Name, SwitchType -HideTableHeaders")
if err != nil { if err != nil {
return "", fmt.Errorf("Could not get list of switches: %v", err) return "", fmt.Errorf("Could not get list of switches: %v", err)
} }
@ -251,12 +257,12 @@ func hypervGetSwitch(name string) (string, error) {
if len(s) == 0 { if len(s) == 0 {
continue continue
} }
t := strings.SplitN(s, " ", 2) t := strings.Split(s, " ")
if len(t) < 2 { if len(t) < 2 {
continue continue
} }
if strings.Contains(t[1], "External") { if strings.Contains(t[len(t)-1:][0], "External") {
return strings.Trim(t[0], " "), nil return strings.Join(t[:len(t)-1], " "), nil
} }
} }
return "", fmt.Errorf("Could not find an external switch") return "", fmt.Errorf("Could not find an external switch")