From 811831c0591a11079bad59f78c3909a55b0bae1f Mon Sep 17 00:00:00 2001 From: James Peru Date: Mon, 23 Nov 2026 18:59:47 +0300 Subject: [PATCH 1/2] server: serialize the device ID allocation of the NICs of an instance --- .../orchestration/NetworkOrchestrator.java | 59 ++++++++++++++----- 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index e6bbeb7d660d..2193a117d498 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -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; @@ -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, @@ -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 From d29c4c6afe6e357929c040cf01a23f42993d26dc Mon Sep 17 00:00:00 2001 From: James Peru Date: Tue, 24 Nov 2026 21:29:29 +0300 Subject: [PATCH 2/2] Add unit tests for the NIC allocation under the instance lock --- .../NetworkOrchestratorTest.java | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java index feca11feac5d..fa8d5a7bc605 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java @@ -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; @@ -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; @@ -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; @@ -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; @@ -1280,4 +1285,107 @@ public void ensureRouterForAssociationDoesNothingForNetworkNotSetupOrImplemented verify(testOrchestrator, never()).implementNetworkElementsAndResources(any(), any(), any(), any()); } + + private GlobalLock prepareNicAllocationLock(MockedStatic 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 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 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 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(null, 2)).when(testOrchestrator).allocateNic(requested, network, false, 2, vmProfile); + + try (MockedStatic 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(); + } + } }