Repository: vmware/govmomi
Pull request #2798 (2022-03-27 08:04:00)

vcsim: Fix device connectivity when vm is powered off
## Description

When vm power state is not powered on, its devices should not be connected.

Closes: #2797

## Type of change

Please mark options that are relevant:

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to
  not work as expected)
- [ ] This change requires a documentation update
- [ ] Build related change

## How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide
instructions so we can reproduce. If applicable, please also list any relevant
details for your test configuration.

- unit tests in the commit

## Checklist:

- [x] My code follows the CONTRIBUTION [guidelines](./../CONTRIBUTING.md) of
  this project
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged


Patch:
diff --git a/simulator/virtual_machine.go b/simulator/virtual_machine.go
index 3483f8ba..64b54dbe 100644
--- a/simulator/virtual_machine.go
+++ b/simulator/virtual_machine.go
@@ -1283,6 +1283,13 @@ func (vm *VirtualMachine) configureDevice(ctx *Context, devices object.VirtualDe
 		}
 	}
 
+	// device can be connected only if vm is powered on
+	if vm.Runtime.PowerState != types.VirtualMachinePowerStatePoweredOn {
+		if d.Connectable != nil {
+			d.Connectable.Connected = false
+		}
+	}
+
 	return nil
 }
 
@@ -1539,10 +1546,27 @@ func (c *powerVMTask) Run(task *Task) (types.AnyType, types.BaseMethodFault) {
 		)
 	}
 
+	// copy devices to prevent data race
+	devices := c.VirtualMachine.cloneDevice()
+	for _, d := range devices {
+		conn := d.GetVirtualDevice().Connectable
+		if conn == nil {
+			continue
+		}
+
+		if c.state == types.VirtualMachinePowerStatePoweredOn {
+			// apply startConnected to current connection
+			conn.Connected = conn.StartConnected
+		} else {
+			conn.Connected = false
+		}
+	}
+
 	c.ctx.Map.Update(c.VirtualMachine, []types.PropertyChange{
 		{Name: "runtime.powerState", Val: c.state},
 		{Name: "summary.runtime.powerState", Val: c.state},
 		{Name: "summary.runtime.bootTime", Val: boot},
+		{Name: "config.hardware.device", Val: devices},
 	})
 
 	return nil, nil


Test patch:
diff --git a/simulator/virtual_machine_test.go b/simulator/virtual_machine_test.go
index c42d569f..7f180cbd 100644
--- a/simulator/virtual_machine_test.go
+++ b/simulator/virtual_machine_test.go
@@ -390,6 +390,104 @@ func TestReconfigVmDevice(t *testing.T) {
 	}
 }
 
+func TestConnectVmDevice(t *testing.T) {
+	ctx := context.Background()
+
+	m := ESX()
+	defer m.Remove()
+	err := m.Create()
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	s := m.Service.NewServer()
+	defer s.Close()
+
+	c, err := govmomi.NewClient(ctx, s.URL, true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	vmm := Map.Any("VirtualMachine").(*VirtualMachine)
+	vm := object.NewVirtualMachine(c.Client, vmm.Reference())
+
+	l := object.VirtualDeviceList{} // used only for Connect/Disconnect function
+
+	tests := []struct {
+		description            string
+		changePower            func(context.Context) (*object.Task, error)
+		changeConnectivity     func(types.BaseVirtualDevice) error
+		expectedConnected      bool
+		expectedStartConnected bool
+	}{
+		{"disconnect when vm is on", nil, l.Disconnect, false, false},
+		{"connect when vm is on", nil, l.Connect, true, true},
+		{"power off vm", vm.PowerOff, nil, false, true},
+		{"disconnect when vm is off", nil, l.Disconnect, false, false},
+		{"connect when vm is off", nil, l.Connect, false, true},
+		{"power on vm when StartConnected is true", vm.PowerOn, nil, true, true},
+		{"power off vm and disconnect again", vm.PowerOff, l.Disconnect, false, false},
+		{"power on vm when StartConnected is false", vm.PowerOn, nil, false, false},
+	}
+
+	for _, testCase := range tests {
+		testCase := testCase // assign to local var since loop var is reused
+
+		t.Run(testCase.description, func(t *testing.T) {
+			if testCase.changePower != nil {
+				task, err := testCase.changePower(ctx)
+				if err != nil {
+					t.Fatal(err)
+				}
+
+				err = task.Wait(ctx)
+				if err != nil {
+					t.Fatal(err)
+				}
+			}
+
+			if testCase.changeConnectivity != nil {
+				list, err := vm.Device(ctx)
+				if err != nil {
+					t.Fatal(err)
+				}
+				device := list.FindByKey(esx.EthernetCard.Key)
+				if device == nil {
+					t.Fatal("cloud not find EthernetCard")
+				}
+
+				err = testCase.changeConnectivity(device)
+				if err != nil {
+					t.Fatal(err)
+				}
+				err = vm.EditDevice(ctx, device)
+				if err != nil {
+					t.Fatal(err)
+				}
+			}
+
+			updatedList, err := vm.Device(ctx)
+			if err != nil {
+				t.Fatal(err)
+			}
+			updatedDevice := updatedList.FindByKey(esx.EthernetCard.Key)
+			if updatedDevice == nil {
+				t.Fatal("cloud not find EthernetCard")
+			}
+			conn := updatedDevice.GetVirtualDevice().Connectable
+
+			if conn.Connected != testCase.expectedConnected {
+				t.Errorf("unexpected Connected property. expected: %t, actual: %t",
+					testCase.expectedConnected, conn.Connected)
+			}
+			if conn.StartConnected != testCase.expectedStartConnected {
+				t.Errorf("unexpected StartConnected property. expected: %t, actual: %t",
+					testCase.expectedStartConnected, conn.StartConnected)
+			}
+		})
+	}
+}
+
 func TestVAppConfigAdd(t *testing.T) {
 	ctx := context.Background()