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 @@ -284,6 +284,8 @@
* NetworkManagerImpl implements NetworkManager.
*/
public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestrationService, Listener, Configurable {
protected static final int NIC_ALLOCATION_LOCK_TIMEOUT_SECONDS = 600;


@Inject
EntityManager _entityMgr;
Expand Down Expand Up @@ -4847,6 +4849,46 @@ protected NicProfile getNicProfileForVm(final Network network, final NicProfile
return nic;
}

/**
* Picks the free device ID of the instance and allocates the NIC with it while holding a lock on the instance.
* Several networks can be added to the same instance at the same time (for instance, VPC tiers implemented in
* parallel are all plugged into the same VPC virtual router); without the lock, they could all read the same
* free device ID and the instance would end with several NICs sharing a device ID.
*/
protected NicProfile allocateNicForVmWithFreeDeviceId(final Network network, final NicProfile requested, final VirtualMachineProfile vmProfile)
throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException {
final VirtualMachine vm = vmProfile.getVirtualMachine();
final GlobalLock lock = GlobalLock.getInternLock("vm.nic.allocation." + vm.getId());
try {
if (!lock.lock(NIC_ALLOCATION_LOCK_TIMEOUT_SECONDS)) {
throw new ConcurrentOperationException(String.format("Unable to acquire the lock to allocate a NIC for Instance %s in Network %s", vm, network));
}
try {
final int deviceId = _nicDao.getFreeDeviceId(vm.getId());

boolean isDefaultNic = getNicProfileDefaultNic(requested);

NicProfile nic = allocateNic(requested, network, isDefaultNic, deviceId, vmProfile).first();

if (nic == null) {
throw new CloudRuntimeException("Failed to allocate nic for Instance " + vm + " in network " + network);
}

//Update vm_network_map table
if (vmProfile.getType() == VirtualMachine.Type.User) {
final VMNetworkMapVO vno = new VMNetworkMapVO(vm.getId(), network.getId());
_vmNetworkMapDao.persist(vno);
}
logger.debug("NIC is allocated successfully for Instance {} in Network {} with device ID {}", vm, network, deviceId);
return nic;
} finally {
lock.unlock();
}
} finally {
lock.releaseRef();
}
}

@Override
public NicProfile createNicForVm(final Network network, final NicProfile requested, final ReservationContext context, final VirtualMachineProfile vmProfile, final boolean prepare)
throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException,
Expand All @@ -4860,22 +4902,7 @@ public NicProfile createNicForVm(final Network network, final NicProfile request

//1) allocate nic (if needed) Always allocate if it is a user vm
if (nic == null || vmProfile.getType() == VirtualMachine.Type.User) {
final int deviceId = _nicDao.getFreeDeviceId(vm.getId());

boolean isDefaultNic = getNicProfileDefaultNic(requested);

nic = allocateNic(requested, network, isDefaultNic, deviceId, vmProfile).first();

if (nic == null) {
throw new CloudRuntimeException("Failed to allocate nic for Instance " + vm + " in network " + network);
}

//Update vm_network_map table
if (vmProfile.getType() == VirtualMachine.Type.User) {
final VMNetworkMapVO vno = new VMNetworkMapVO(vm.getId(), network.getId());
_vmNetworkMapDao.persist(vno);
}
logger.debug("NIC is allocated successfully for Instance {} in Network {}", vm, network);
nic = allocateNicForVmWithFreeDeviceId(network, requested, vmProfile);
}

//2) prepare nic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientVirtualNetworkCapacityException;
import com.cloud.network.IpAddressManager;
import com.cloud.utils.Pair;
import com.cloud.utils.db.GlobalLock;
import org.apache.cloudstack.extension.Extension;
import org.apache.cloudstack.extension.ExtensionHelper;
import org.apache.cloudstack.framework.extensions.network.NetworkExtensionElement;
Expand All @@ -52,6 +54,7 @@
import org.junit.runners.JUnit4;
import org.springframework.test.util.ReflectionTestUtils;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
import org.mockito.MockedStatic;
import org.mockito.Mockito;

Expand Down Expand Up @@ -99,6 +102,7 @@
import com.cloud.vm.Nic;
import com.cloud.vm.NicProfile;
import com.cloud.vm.NicVO;
import org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
Expand All @@ -111,6 +115,7 @@
import com.cloud.vm.dao.NicNetworkMapDao;
import com.cloud.vm.dao.NicNetworkMapVO;
import com.cloud.vm.dao.NicSecondaryIpDao;
import org.apache.cloudstack.engine.cloud.entity.api.db.dao.VMNetworkMapDao;
import com.cloud.vm.dao.UserVmDao;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
Expand Down Expand Up @@ -1280,4 +1285,107 @@ public void ensureRouterForAssociationDoesNothingForNetworkNotSetupOrImplemented

verify(testOrchestrator, never()).implementNetworkElementsAndResources(any(), any(), any(), any());
}

private GlobalLock prepareNicAllocationLock(MockedStatic<GlobalLock> globalLockMocked, long vmId, boolean acquired) {
GlobalLock lock = mock(GlobalLock.class);
globalLockMocked.when(() -> GlobalLock.getInternLock("vm.nic.allocation." + vmId)).thenReturn(lock);
when(lock.lock(NetworkOrchestrator.NIC_ALLOCATION_LOCK_TIMEOUT_SECONDS)).thenReturn(acquired);
return lock;
}

private VirtualMachineProfile prepareVmProfileForNicAllocation(long vmId, Type type) {
VirtualMachine vm = mock(VirtualMachine.class);
when(vm.getId()).thenReturn(vmId);
VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class);
when(vmProfile.getVirtualMachine()).thenReturn(vm);
when(vmProfile.getType()).thenReturn(type);
return vmProfile;
}

@Test
public void allocateNicForVmWithFreeDeviceIdTestPicksTheDeviceIdAndAllocatesTheNicWhileHoldingTheLock() throws Exception {
long vmId = 5L;
int freeDeviceId = 3;
Network network = mock(Network.class);
NicProfile requested = mock(NicProfile.class);
NicProfile allocated = mock(NicProfile.class);
VirtualMachineProfile vmProfile = prepareVmProfileForNicAllocation(vmId, Type.DomainRouter);
testOrchestrator._vmNetworkMapDao = mock(VMNetworkMapDao.class);
when(testOrchestrator._nicDao.getFreeDeviceId(vmId)).thenReturn(freeDeviceId);
Mockito.doReturn(new Pair<>(allocated, freeDeviceId)).when(testOrchestrator).allocateNic(requested, network, false, freeDeviceId, vmProfile);

try (MockedStatic<GlobalLock> globalLockMocked = Mockito.mockStatic(GlobalLock.class)) {
GlobalLock lock = prepareNicAllocationLock(globalLockMocked, vmId, true);

NicProfile result = testOrchestrator.allocateNicForVmWithFreeDeviceId(network, requested, vmProfile);

Assert.assertSame(allocated, result);
InOrder inOrder = Mockito.inOrder(lock, testOrchestrator._nicDao, testOrchestrator);
inOrder.verify(lock).lock(NetworkOrchestrator.NIC_ALLOCATION_LOCK_TIMEOUT_SECONDS);
inOrder.verify(testOrchestrator._nicDao).getFreeDeviceId(vmId);
inOrder.verify(testOrchestrator).allocateNic(requested, network, false, freeDeviceId, vmProfile);
inOrder.verify(lock).unlock();
inOrder.verify(lock).releaseRef();
verify(testOrchestrator._vmNetworkMapDao, never()).persist(any());
}
}

@Test
public void allocateNicForVmWithFreeDeviceIdTestPersistsTheVmNetworkMapForUserVm() throws Exception {
long vmId = 6L;
Network network = mock(Network.class);
NicProfile requested = mock(NicProfile.class);
VirtualMachineProfile vmProfile = prepareVmProfileForNicAllocation(vmId, Type.User);
testOrchestrator._vmNetworkMapDao = mock(VMNetworkMapDao.class);
when(testOrchestrator._nicDao.getFreeDeviceId(vmId)).thenReturn(1);
Mockito.doReturn(new Pair<>(mock(NicProfile.class), 1)).when(testOrchestrator).allocateNic(requested, network, false, 1, vmProfile);

try (MockedStatic<GlobalLock> globalLockMocked = Mockito.mockStatic(GlobalLock.class)) {
GlobalLock lock = prepareNicAllocationLock(globalLockMocked, vmId, true);

testOrchestrator.allocateNicForVmWithFreeDeviceId(network, requested, vmProfile);

verify(testOrchestrator._vmNetworkMapDao).persist(any(VMNetworkMapVO.class));
verify(lock).unlock();
verify(lock).releaseRef();
}
}

@Test
public void allocateNicForVmWithFreeDeviceIdTestDoesNotAllocateWhenTheLockIsNotAcquired() throws Exception {
long vmId = 7L;
Network network = mock(Network.class);
NicProfile requested = mock(NicProfile.class);
VirtualMachineProfile vmProfile = prepareVmProfileForNicAllocation(vmId, Type.DomainRouter);

try (MockedStatic<GlobalLock> globalLockMocked = Mockito.mockStatic(GlobalLock.class)) {
GlobalLock lock = prepareNicAllocationLock(globalLockMocked, vmId, false);

Assert.assertThrows(ConcurrentOperationException.class, () -> testOrchestrator.allocateNicForVmWithFreeDeviceId(network, requested, vmProfile));

verify(testOrchestrator._nicDao, never()).getFreeDeviceId(anyLong());
verify(testOrchestrator, never()).allocateNic(any(), any(), any(), Mockito.anyInt(), any());
verify(lock, never()).unlock();
verify(lock).releaseRef();
}
}

@Test
public void allocateNicForVmWithFreeDeviceIdTestReleasesTheLockWhenTheAllocationFails() throws Exception {
long vmId = 8L;
Network network = mock(Network.class);
NicProfile requested = mock(NicProfile.class);
VirtualMachineProfile vmProfile = prepareVmProfileForNicAllocation(vmId, Type.DomainRouter);
when(testOrchestrator._nicDao.getFreeDeviceId(vmId)).thenReturn(2);
Mockito.doReturn(new Pair<NicProfile, Integer>(null, 2)).when(testOrchestrator).allocateNic(requested, network, false, 2, vmProfile);

try (MockedStatic<GlobalLock> globalLockMocked = Mockito.mockStatic(GlobalLock.class)) {
GlobalLock lock = prepareNicAllocationLock(globalLockMocked, vmId, true);

Assert.assertThrows(CloudRuntimeException.class, () -> testOrchestrator.allocateNicForVmWithFreeDeviceId(network, requested, vmProfile));

verify(lock).unlock();
verify(lock).releaseRef();
}
}
}
Loading