From 8b13258917f90004cd658852016acf3867d6dc15 Mon Sep 17 00:00:00 2001 From: Stijn Simons Date: Thu, 3 Dec 2026 12:56:56 +0100 Subject: [PATCH 1/2] Security group hotswapping on running instances --- .../security/SecurityGroupManager.java | 2 + .../security/SecurityGroupManagerImpl.java | 84 ++++++++- .../java/com/cloud/vm/UserVmManagerImpl.java | 13 +- .../SecurityGroupManagerImplTest.java | 160 +++++++++++++++--- ui/src/views/compute/InstanceTab.vue | 9 +- 5 files changed, 218 insertions(+), 50 deletions(-) diff --git a/engine/components-api/src/main/java/com/cloud/network/security/SecurityGroupManager.java b/engine/components-api/src/main/java/com/cloud/network/security/SecurityGroupManager.java index 6e2270ffb108..b737af12a855 100644 --- a/engine/components-api/src/main/java/com/cloud/network/security/SecurityGroupManager.java +++ b/engine/components-api/src/main/java/com/cloud/network/security/SecurityGroupManager.java @@ -39,6 +39,8 @@ public interface SecurityGroupManager { public boolean addInstanceToGroups(UserVm userVm, List groups); + public void replaceInstanceGroups(UserVm vm, List groups); + public void removeInstanceFromGroups(UserVm userVm); public void fullSync(long agentId, HashMap> newGroupStates); diff --git a/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java index df8cb79f8723..299fb1404322 100644 --- a/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/main/java/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -463,8 +463,7 @@ protected List getAffectedVmsForVmStart(VMInstanceVO vm) { // For each group, find the security rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group assign - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_ASSIGN, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), vm - .getClass().getName(), vm.getUuid()); + publishMembershipUsageEvent(vm, mapVO.getSecurityGroupId(), EventTypes.EVENT_SECURITY_GROUP_ASSIGN); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to @@ -479,8 +478,7 @@ protected List getAffectedVmsForVmStop(VMInstanceVO vm) { // For each group, find the security rules that allow the group for (SecurityGroupVMMapVO mapVO : groupsForVm) {// FIXME: use custom sql in the dao //Add usage events for security group remove - UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SECURITY_GROUP_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), mapVO.getSecurityGroupId(), vm - .getClass().getName(), vm.getUuid()); + publishMembershipUsageEvent(vm, mapVO.getSecurityGroupId(), EventTypes.EVENT_SECURITY_GROUP_REMOVE); List allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId()); // For each security rule that allows a group that the vm belongs to, find the group it belongs to @@ -489,6 +487,11 @@ protected List getAffectedVmsForVmStop(VMInstanceVO vm) { return affectedVms; } + void publishMembershipUsageEvent(VMInstanceVO vm, long groupId, String eventType) { + UsageEventUtils.publishUsageEvent(eventType, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), groupId, + vm.getClass().getName(), vm.getUuid()); + } + protected List getAffectedVmsForSecurityRules(List allowingRules) { Set distinctGroups = new HashSet(); List affectedVms = new ArrayList(); @@ -1138,6 +1141,79 @@ public Boolean doInTransaction(TransactionStatus status) { } + @Override + @DB + public void replaceInstanceGroups(UserVm vm, List groups) { + long vmId = vm.getId(); + if (_userVMDao.acquireInLockTable(vmId) == null) { + throw new ConcurrentModificationException(String.format("Failed to acquire lock on VM %s", vm.getUuid())); + } + + List affectedVms; + try { + TransactionCallback> replace = status -> replaceInstanceGroupsInTransaction(vm, groups); + affectedVms = Transaction.execute(replace); + } finally { + _userVMDao.releaseFromLockTable(vmId); + } + if (!affectedVms.isEmpty()) { + scheduleRulesetUpdateToHosts(affectedVms, true, null); + } + } + + List replaceInstanceGroupsInTransaction(UserVm vm, List groups) { + long vmId = vm.getId(); + VMInstanceVO lockedVm = _vmDao.lockRow(vmId, true); + if (lockedVm == null || (lockedVm.getState() != State.Running && lockedVm.getState() != State.Stopped)) { + throw new InvalidParameterValueException(String.format("VM %s must be running or stopped to update security groups", vm.getUuid())); + } + if (!isVmSecurityGroupEnabled(vmId)) { + throw new InvalidParameterValueException("Security groups are not supported on the VM's networks"); + } + + Set requestedGroups = new TreeSet<>(groups); + Set addedGroups = new TreeSet<>(requestedGroups); + List removedMappings = new ArrayList<>(); + for (SecurityGroupVMMapVO mapping : _securityGroupVMMapDao.listByInstanceId(vmId)) { + addedGroups.remove(mapping.getSecurityGroupId()); + if (!requestedGroups.contains(mapping.getSecurityGroupId())) { + removedMappings.add(mapping); + } + } + for (Long groupId : addedGroups) { + if (_securityGroupDao.lockRow(groupId, true) == null) { + throw new InvalidParameterValueException("Unable to find security group with ID " + groupId); + } + } + + Set changedGroups = new HashSet<>(addedGroups); + for (SecurityGroupVMMapVO mapping : removedMappings) { + if (!_securityGroupVMMapDao.expunge(mapping.getId())) { + throw new CloudRuntimeException("Failed to remove a security group membership for VM " + vm.getUuid()); + } + changedGroups.add(mapping.getSecurityGroupId()); + } + for (Long groupId : addedGroups) { + _securityGroupVMMapDao.persist(new SecurityGroupVMMapVO(groupId, vmId)); + } + + if (lockedVm.getState() == State.Stopped || changedGroups.isEmpty()) { + return Collections.emptyList(); + } + for (SecurityGroupVMMapVO mapping : removedMappings) { + publishMembershipUsageEvent(lockedVm, mapping.getSecurityGroupId(), EventTypes.EVENT_SECURITY_GROUP_REMOVE); + } + for (Long groupId : addedGroups) { + publishMembershipUsageEvent(lockedVm, groupId, EventTypes.EVENT_SECURITY_GROUP_ASSIGN); + } + Set affectedVms = new HashSet<>(); + affectedVms.add(vmId); + for (Long groupId : changedGroups) { + affectedVms.addAll(getAffectedVmsForSecurityRules(_securityGroupRuleDao.listByAllowedSecurityGroupId(groupId))); + } + return new ArrayList<>(affectedVms); + } + @Override @DB public void removeInstanceFromGroups(final UserVm vm) { diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index b2e20256cc53..707b358b9c6a 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -3487,22 +3487,11 @@ private void checkAndUpdateSecurityGroupForVM(List securityGroupIdList, Us _accountMgr.getActiveAccountById(vm.getAccountId()), zone, networkIds, securityGroupIdList) ) { - updateSecurityGroup(vm, securityGroupIdList); + _securityGroupMgr.replaceInstanceGroups(vm, securityGroupIdList); } } } - private void updateSecurityGroup(UserVmVO vm, List securityGroupIdList) { - if (vm.getState() == State.Stopped) { - // Remove instance from security groups - _securityGroupMgr.removeInstanceFromGroups(vm); - // Add instance in provided groups - _securityGroupMgr.addInstanceToGroups(vm, securityGroupIdList); - } else { - throw new InvalidParameterValueException(String.format("VM %s must be stopped prior to update security groups", vm.getUuid())); - } - } - protected void updateUserData(UserVm vm) throws ResourceUnavailableException, InsufficientCapacityException { boolean result = updateUserDataInternal(vm); if (result) { diff --git a/server/src/test/java/com/cloud/network/security/SecurityGroupManagerImplTest.java b/server/src/test/java/com/cloud/network/security/SecurityGroupManagerImplTest.java index d5803a7efe65..5c6d59d817b7 100644 --- a/server/src/test/java/com/cloud/network/security/SecurityGroupManagerImplTest.java +++ b/server/src/test/java/com/cloud/network/security/SecurityGroupManagerImplTest.java @@ -4,9 +4,9 @@ // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at +// with the License. You may obtain a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an @@ -14,35 +14,141 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. - package com.cloud.network.security; -import com.cloud.network.security.SecurityGroupManagerImpl.CidrComparator; -import junit.framework.TestCase; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; -import javax.inject.Inject; -import java.util.Set; -import java.util.TreeSet; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.security.SecurityGroupManagerImpl.CidrComparator; +import com.cloud.network.security.dao.SecurityGroupDao; +import com.cloud.network.security.dao.SecurityGroupRuleDao; +import com.cloud.network.security.dao.SecurityGroupVMMapDao; +import com.cloud.uservm.UserVm; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine.State; +import com.cloud.vm.dao.VMInstanceDao; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class SecurityGroupManagerImplTest { + private Set cidrs; + + @Mock + SecurityGroupRuleDao _securityGroupRuleDao; + @Mock + SecurityGroupVMMapDao _securityGroupVMMapDao; + @Mock + VMInstanceDao _vmDao; + @Mock + SecurityGroupDao _securityGroupDao; + + @Spy + @InjectMocks + SecurityGroupManagerImpl manager = new SecurityGroupManagerImpl(); + + @Test + public void runningMembershipReplacementRefreshesPeersOfBothGroups() { + UserVm vm = mockMembershipVm(State.Running); + when(_securityGroupVMMapDao.expunge(5L)).thenReturn(true); + when(_securityGroupDao.lockRow(20L, true)).thenReturn(Mockito.mock(SecurityGroupVO.class)); + stubReferencingGroup(10L, 30L, 2L); + stubReferencingGroup(20L, 40L, 3L); + + Assert.assertEquals(Set.of(1L, 2L, 3L), + new HashSet<>(manager.replaceInstanceGroupsInTransaction(vm, List.of(20L, 20L)))); + Mockito.verify(_securityGroupVMMapDao).expunge(5L); + Mockito.verify(_securityGroupVMMapDao).persist(Mockito.argThat( + mapping -> mapping.getSecurityGroupId() == 20L && mapping.getInstanceId() == 1L)); + } + + @Test + public void stoppedMembershipCanBeClearedWithoutSchedulingRules() { + UserVm vm = mockMembershipVm(State.Stopped); + when(_securityGroupVMMapDao.expunge(5L)).thenReturn(true); + + Assert.assertTrue(manager.replaceInstanceGroupsInTransaction(vm, List.of()).isEmpty()); + Mockito.verify(_securityGroupVMMapDao).expunge(5L); + Mockito.verifyNoInteractions(_securityGroupRuleDao); + } -/** - * @author daan - * - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = "classpath:/SecurityGroupManagerTestContext.xml") -public class SecurityGroupManagerImplTest extends TestCase { - @Inject - SecurityGroupManagerImpl2 _sgMgr = null; - Set cidrs; + @Test + public void missingTargetGroupLeavesMembershipUntouched() { + UserVm vm = mockMembershipVm(State.Running); + + Assert.assertThrows(InvalidParameterValueException.class, + () -> manager.replaceInstanceGroupsInTransaction(vm, List.of(20L))); + Mockito.verify(_securityGroupVMMapDao, Mockito.never()).expunge(Mockito.anyLong()); + Mockito.verify(_securityGroupVMMapDao, Mockito.never()).persist(Mockito.any()); + } + + @Test + public void unchangedMembershipRequiresNoWritesOrRulesetRefresh() { + UserVm vm = mockMembershipVm(State.Running); + + Assert.assertTrue(manager.replaceInstanceGroupsInTransaction(vm, List.of(10L, 10L)).isEmpty()); + Mockito.verify(_securityGroupVMMapDao, Mockito.never()).expunge(Mockito.anyLong()); + Mockito.verify(_securityGroupVMMapDao, Mockito.never()).persist(Mockito.any()); + Mockito.verifyNoInteractions(_securityGroupRuleDao); + } + + @Test + public void transitionalVmRejectsMembershipUpdate() { + UserVm vm = mockMembershipVm(State.Starting); + + Assert.assertThrows(InvalidParameterValueException.class, + () -> manager.replaceInstanceGroupsInTransaction(vm, List.of(20L))); + Mockito.verifyNoInteractions(_securityGroupVMMapDao); + } + + @Test + public void unsupportedVmNetworkRejectsMembershipUpdate() { + UserVm vm = mockMembershipVm(State.Running); + Mockito.doReturn(false).when(manager).isVmSecurityGroupEnabled(1L); + + Assert.assertThrows(InvalidParameterValueException.class, + () -> manager.replaceInstanceGroupsInTransaction(vm, List.of(20L))); + Mockito.verifyNoInteractions(_securityGroupVMMapDao); + } + + private UserVm mockMembershipVm(State state) { + UserVm vm = Mockito.mock(UserVm.class); + when(vm.getId()).thenReturn(1L); + VMInstanceVO lockedVm = Mockito.mock(VMInstanceVO.class); + when(lockedVm.getState()).thenReturn(state); + when(_vmDao.lockRow(1L, true)).thenReturn(lockedVm); + Mockito.doReturn(true).when(manager).isVmSecurityGroupEnabled(1L); + Mockito.doNothing().when(manager).publishMembershipUsageEvent(Mockito.eq(lockedVm), Mockito.anyLong(), Mockito.anyString()); + SecurityGroupVMMapVO mapping = Mockito.mock(SecurityGroupVMMapVO.class); + when(mapping.getId()).thenReturn(5L); + when(mapping.getSecurityGroupId()).thenReturn(10L); + when(_securityGroupVMMapDao.listByInstanceId(1L)).thenReturn(List.of(mapping)); + return vm; + } + + private void stubReferencingGroup(long referencedGroupId, long ruleGroupId, long peerVmId) { + SecurityGroupRuleVO rule = Mockito.mock(SecurityGroupRuleVO.class); + when(rule.getSecurityGroupId()).thenReturn(ruleGroupId); + when(_securityGroupRuleDao.listByAllowedSecurityGroupId(referencedGroupId)).thenReturn(List.of(rule)); + when(_securityGroupVMMapDao.listVmIdsBySecurityGroup(ruleGroupId)).thenReturn(List.of(peerVmId)); + } @Before - public void setup() throws Exception { - cidrs = new TreeSet(new CidrComparator()); + public void setup() { + cidrs = new TreeSet<>(new CidrComparator()); } @Test(expected = NumberFormatException.class) @@ -61,18 +167,18 @@ public void faultyCidrCompareTest() { public void sameCidrCompareTest() { cidrs.add("1.2.3.4/5"); cidrs.add("1.2.3.4/5"); - assertEquals("only one element expected", 1, cidrs.size()); + Assert.assertEquals("only one element expected", 1, cidrs.size()); CidrComparator cmp = new CidrComparator(); - assertEquals("should be 0", 0, cmp.compare("1.2.3.4/5", "1.2.3.4/5")); + Assert.assertEquals("should be 0", 0, cmp.compare("1.2.3.4/5", "1.2.3.4/5")); } @Test public void CidrCompareTest() { cidrs.add("1.2.3.4/5"); cidrs.add("1.2.3.4/6"); - assertEquals("two element expected", 2, cidrs.size()); + Assert.assertEquals("two element expected", 2, cidrs.size()); CidrComparator cmp = new CidrComparator(); - assertEquals("should be 1", 1, cmp.compare("1.2.3.4/5", "1.2.3.4/6")); - assertEquals("should be -2", -2, cmp.compare("1.2.3.4/5", "1.2.3.4/3")); + Assert.assertEquals("should be 1", 1, cmp.compare("1.2.3.4/5", "1.2.3.4/6")); + Assert.assertEquals("should be -2", -2, cmp.compare("1.2.3.4/5", "1.2.3.4/3")); } } diff --git a/ui/src/views/compute/InstanceTab.vue b/ui/src/views/compute/InstanceTab.vue index c4c53dc91993..8b9e415d2300 100644 --- a/ui/src/views/compute/InstanceTab.vue +++ b/ui/src/views/compute/InstanceTab.vue @@ -307,13 +307,8 @@ export default { }, showUpdateSGModal () { this.loadingSG = true - if (this.vm.securitygroup && this.vm.securitygroup?.length > 0) { - this.securitygroupids = [] - for (const sg of this.vm.securitygroup) { - this.securitygroupids.push(sg.id) - } - this.dataPreFill = { securitygroupids: this.securitygroupids } - } + this.securitygroupids = (this.vm.securitygroup || []).map(group => group.id) + this.dataPreFill = { securitygroupids: this.securitygroupids } this.showUpdateSecurityGroupsModal = true this.loadingSG = false }, From e5945157bf402287e0a026174ddbb05e1dbbd92d Mon Sep 17 00:00:00 2001 From: Stijn Simons Date: Thu, 3 Dec 2026 12:57:09 +0100 Subject: [PATCH 2/2] Smoke test hotswapping of security groups --- .../smoke/test_security_group_membership.py | 203 ++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 test/integration/smoke/test_security_group_membership.py diff --git a/test/integration/smoke/test_security_group_membership.py b/test/integration/smoke/test_security_group_membership.py new file mode 100644 index 000000000000..6deb2c53414b --- /dev/null +++ b/test/integration/smoke/test_security_group_membership.py @@ -0,0 +1,203 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Security group membership updates with real KVM packet filtering.""" + +import time +import unittest +import uuid + +from nose.plugins.attrib import attr + +from marvin.cloudstackAPI import ( + authorizeSecurityGroupEgress, + authorizeSecurityGroupIngress, +) +from marvin.cloudstackException import CloudstackAPIException +from marvin.cloudstackTestCase import cloudstackTestCase +from marvin.codes import SUCCESS +from marvin.lib.base import Account, SecurityGroup, ServiceOffering, VirtualMachine +from marvin.lib.common import get_domain, get_template, get_zone + + +@attr(hypervisor="kvm", tags=["basic", "advancedsg", "sg"], + required_hardware="true") +class TestSecurityGroupMembership(cloudstackTestCase): + @classmethod + def setUpClass(cls): + cls.testClient = cls.getClsTestClient() + cls.apiclient = cls.testClient.getApiClient() + cls.zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) + if not cls.zone.securitygroupsenabled: + raise unittest.SkipTest("A security group enabled zone is required") + cls.testdata = cls.testClient.getParsedTestDataConfig() + cls.domain = get_domain(cls.apiclient) + cls.template = get_template( + cls.apiclient, cls.zone.id, hypervisor="KVM", + template_id=cls.testdata["small"].get("template")) + if not getattr(cls.template, "isready", False): + raise unittest.SkipTest("A ready Linux KVM template is required") + cls.offering = ServiceOffering.create( + cls.apiclient, cls.testdata["service_offering"]) + cls._cleanup = [cls.offering] + + @classmethod + def tearDownClass(cls): + cls.cleanup_resources(cls.apiclient, reversed(cls._cleanup)) + + def setUp(self): + self.cleanup = [] + self.account = Account.create( + self.apiclient, self.testdata["account"], domainid=self.domain.id) + self.cleanup.append(self.account) + + def tearDown(self): + self.cleanup_resources(self.apiclient, reversed(self.cleanup)) + + def _group(self, name): + return SecurityGroup.create( + self.apiclient, {"name": name}, account=self.account.name, + domainid=self.account.domainid) + + def _rule(self, group, egress=False, allowed_group=None, protocol="icmp"): + command = (authorizeSecurityGroupEgress.authorizeSecurityGroupEgressCmd() + if egress else + authorizeSecurityGroupIngress.authorizeSecurityGroupIngressCmd()) + command.securitygroupid = group.id + command.protocol = protocol + if protocol == "icmp": + command.icmptype = -1 + command.icmpcode = -1 + else: + command.startport = 1 if egress else 22 + command.endport = 65535 if egress else 22 + if allowed_group: + command.usersecuritygrouplist = [{ + "account": self.account.name, "group": allowed_group.name}] + else: + command.cidrlist = "0.0.0.0/0" + if egress: + self.apiclient.authorizeSecurityGroupEgress(command) + else: + self.apiclient.authorizeSecurityGroupIngress(command) + + def _management_group(self): + group = self._group("membership-ssh") + self._rule(group, protocol="tcp") + self._rule(group, egress=True, protocol="tcp") + return group + + def _deploy(self, groups): + vm = VirtualMachine.create( + self.apiclient, self.testdata["small"], + templateid=self.template.id, zoneid=self.zone.id, + serviceofferingid=self.offering.id, + accountid=self.account.name, domainid=self.account.domainid, + securitygroupids=[group.id for group in groups], hypervisor="KVM") + self.cleanup.append(vm) + vm.ssh_ip = vm.nic[0].ipaddress + return vm + + def _assert_membership(self, vm, groups, state="Running"): + listed = VirtualMachine.list(self.apiclient, id=vm.id)[0] + actual = [group.id for group in (getattr(listed, "securitygroup", None) or [])] + expected = [group.id for group in groups] + self.assertEqual(set(expected), set(actual)) + self.assertEqual(len(expected), len(actual), "Duplicate memberships returned") + self.assertEqual(state, listed.state) + + def _boot_id(self, vm): + output = vm.get_ssh_client().execute("cat /proc/sys/kernel/random/boot_id") + self.assertEqual(1, len(output), "Could not read guest boot ID") + return str(uuid.UUID(output[0])) + + def _wait_ping(self, source, destination, allowed): + ssh = source.get_ssh_client() + address = destination.nic[0].ipaddress + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + result = ssh.runCommand("ping -c 2 -W 2 %s" % address) + self.assertIsNotNone(result["stdout"], "Ping command did not execute") + self.assertFalse(result["stderr"], "Ping command error: %s" % result["stderr"]) + if (result["status"] == SUCCESS) == allowed: + return + time.sleep(1) + self.fail("ICMP from %s to %s did not become %s" % ( + source.id, destination.id, "allowed" if allowed else "denied")) + + def test_running_replacement_refreshes_instance_and_referencing_peers(self): + """Swap membership without rebooting; refresh ingress and egress peers.""" + management = self._management_group() + old, new, peer_group, control_group = [ + self._group(name) for name in ["old", "new", "peer", "control"]] + for group in [old, new, control_group]: + self._rule(group, egress=True) + self._rule(old) + self._rule(new, allowed_group=peer_group) + self._rule(peer_group, allowed_group=old) + self._rule(peer_group, egress=True, allowed_group=new) + + source = self._deploy([management, old]) + peer = self._deploy([management, peer_group]) + control = self._deploy([management, control_group, new]) + boots = {vm.id: self._boot_id(vm) for vm in [source, peer, control]} + self._wait_ping(control, source, True) + self._wait_ping(source, peer, True) + self._wait_ping(peer, source, False) + + source.update(self.apiclient, securitygroupids=[management.id, new.id]) + self._assert_membership(source, [management, new]) + self._wait_ping(control, source, False) + self._wait_ping(source, peer, False) + self._wait_ping(peer, source, True) + + source.update(self.apiclient, + securitygroupids=[management.id, new.id, new.id]) + self._assert_membership(source, [management, new]) + source.update(self.apiclient, securitygroupids=[management.id, new.id]) + self._assert_membership(source, [management, new]) + with self.assertRaises(CloudstackAPIException): + source.update(self.apiclient, securitygroupids=[str(uuid.uuid4())]) + self._assert_membership(source, [management, new]) + + # Marvin omits empty lists, so send the same empty string as the UI. + source.update(self.apiclient, securitygroupids="") + self._assert_membership(source, []) + self._wait_ping(peer, source, False) + source.update(self.apiclient, securitygroupids=[management.id, new.id]) + source.get_ssh_client(ipaddress=source.nic[0].ipaddress, reconnect=True) + self._wait_ping(peer, source, True) + for vm in [source, peer, control]: + self.assertEqual(boots[vm.id], self._boot_id(vm), + "Membership update rebooted a guest") + + def test_stopped_membership_replacement_and_clear_survive_start(self): + """Preserve stopped-VM updates and apply the final membership on start.""" + management = self._management_group() + old, new = self._group("old"), self._group("new") + vm = self._deploy([management, old]) + self._boot_id(vm) + vm.stop(self.apiclient) + vm.update(self.apiclient, securitygroupids=[management.id, new.id]) + self._assert_membership(vm, [management, new], state="Stopped") + vm.update(self.apiclient, securitygroupids="") + self._assert_membership(vm, [], state="Stopped") + vm.update(self.apiclient, securitygroupids=[management.id, new.id]) + vm.start(self.apiclient) + self._assert_membership(vm, [management, new]) + vm.get_ssh_client(ipaddress=vm.nic[0].ipaddress, reconnect=True) + self._boot_id(vm)