Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public interface SecurityGroupManager {

public boolean addInstanceToGroups(UserVm userVm, List<Long> groups);

public void replaceInstanceGroups(UserVm vm, List<Long> groups);

public void removeInstanceFromGroups(UserVm userVm);

public void fullSync(long agentId, HashMap<String, Pair<Long, Long>> newGroupStates);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,8 +463,7 @@ protected List<Long> 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<SecurityGroupRuleVO> allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId());
// For each security rule that allows a group that the vm belongs to, find the group it belongs to
Expand All @@ -479,8 +478,7 @@ protected List<Long> 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<SecurityGroupRuleVO> allowingRules = _securityGroupRuleDao.listByAllowedSecurityGroupId(mapVO.getSecurityGroupId());
// For each security rule that allows a group that the vm belongs to, find the group it belongs to
Expand All @@ -489,6 +487,11 @@ protected List<Long> 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<Long> getAffectedVmsForSecurityRules(List<SecurityGroupRuleVO> allowingRules) {
Set<Long> distinctGroups = new HashSet<Long>();
List<Long> affectedVms = new ArrayList<Long>();
Expand Down Expand Up @@ -1138,6 +1141,79 @@ public Boolean doInTransaction(TransactionStatus status) {

}

@Override
@DB
public void replaceInstanceGroups(UserVm vm, List<Long> 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<Long> affectedVms;
try {
TransactionCallback<List<Long>> replace = status -> replaceInstanceGroupsInTransaction(vm, groups);
affectedVms = Transaction.execute(replace);
} finally {
_userVMDao.releaseFromLockTable(vmId);
}
if (!affectedVms.isEmpty()) {
scheduleRulesetUpdateToHosts(affectedVms, true, null);
}
}

List<Long> replaceInstanceGroupsInTransaction(UserVm vm, List<Long> 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<Long> requestedGroups = new TreeSet<>(groups);
Set<Long> addedGroups = new TreeSet<>(requestedGroups);
List<SecurityGroupVMMapVO> 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<Long> 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<Long> 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) {
Expand Down
13 changes: 1 addition & 12 deletions server/src/main/java/com/cloud/vm/UserVmManagerImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3487,22 +3487,11 @@ private void checkAndUpdateSecurityGroupForVM(List<Long> securityGroupIdList, Us
_accountMgr.getActiveAccountById(vm.getAccountId()),
zone, networkIds, securityGroupIdList)
) {
updateSecurityGroup(vm, securityGroupIdList);
_securityGroupMgr.replaceInstanceGroups(vm, securityGroupIdList);
}
}
}

private void updateSecurityGroup(UserVmVO vm, List<Long> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,151 @@
// 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
// "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.

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<String> 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<String> 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<String>(new CidrComparator());
public void setup() {
cidrs = new TreeSet<>(new CidrComparator());
}

@Test(expected = NumberFormatException.class)
Expand All @@ -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"));
}
}
Loading