From e964395bd45c390e648f7c9cd567943c45276d69 Mon Sep 17 00:00:00 2001 From: Rohit Yadav Date: Fri, 25 Aug 2023 11:36:03 +0530 Subject: [PATCH 1/6] vmware: improve solidfire storage plugin integration and fix cases (#3) (#7761) This fixes the following cases in which Solidfire storage integration caused issues when using Solidfire datadisks with VMware: 1. Take Volume Snapshot of Solidfire data disk 2. Delete an active Instance with Solidfire data disk attached 3. Attach used existing Solidfire data disk to a running/stopped VM 4. Stop and Start an instance with Solidfire data disks attached 5. Expand disk by resizing Solidfire data disk by providing size 6. Expand disk by changing disk offering for the Solidfire data disk Additional changes: - Use VMFS6 as managed datastore type if the host supports - Refactor detection and splitting of managed storage ds name in storage processor - Restrict storage rescanning for managed datastore when resizing Signed-off-by: Rohit Yadav --- .../orchestration/VolumeOrchestrator.java | 4 +-- .../manager/VmwareStorageManagerImpl.java | 30 ++++++++++++------- .../vmware/resource/VmwareResource.java | 5 ++++ .../resource/VmwareStorageProcessor.java | 12 ++++++-- .../manager/VmwareStorageManagerImplTest.java | 11 +++++++ .../SolidFirePrimaryDataStoreDriver.java | 30 +++++++++++++++++-- .../vmware/mo/HostDatastoreSystemMO.java | 17 ++++++----- .../hypervisor/vmware/util/VmwareHelper.java | 1 + 8 files changed, 86 insertions(+), 24 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 52bcf5033af..c3908795f7c 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1906,8 +1906,8 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati throw new StorageAccessException(String.format("Unable to grant access to volume [%s] on host [%s].", volToString, host)); } } else { - // This might impact other managed storages, grant access for PowerFlex storage pool only - if (pool.getPoolType() == Storage.StoragePoolType.PowerFlex) { + // This might impact other managed storages, grant access for PowerFlex and Iscsi/Solidfire storage pool only + if (pool.getPoolType() == Storage.StoragePoolType.PowerFlex || pool.getPoolType() == Storage.StoragePoolType.Iscsi) { try { volService.grantAccess(volFactory.getVolume(vol.getId()), host, (DataStore)pool); } catch (Exception e) { diff --git a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java index 5b94858b403..d7a736e80e4 100644 --- a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java +++ b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java @@ -1107,12 +1107,25 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { return "snapshots/" + accountId + "/" + volumeId; } + protected boolean isManagedStorageDatastorePath(final String datastorePath) { + // ex. [-iqn.2010-01.com.solidfire:3p53.data-9999.97-0] i-2-9999-VM + return datastorePath != null && datastorePath.startsWith("[-iqn."); + } + + protected String getManagedDatastoreName(final String datastorePath) { + // ex. [-iqn.2010-01.com.solidfire:3p53.data-9999.97-0] + return datastorePath == null ? datastorePath : datastorePath.split(" ")[0]; + } + private long getVMSnapshotChainSize(VmwareContext context, VmwareHypervisorHost hyperHost, String fileName, ManagedObjectReference morDs, String exceptFileName, String vmName) throws Exception { long size = 0; DatastoreMO dsMo = new DatastoreMO(context, morDs); HostDatastoreBrowserMO browserMo = dsMo.getHostDatastoreBrowserMO(); String datastorePath = (new DatastoreFile(dsMo.getName(), vmName)).getPath(); + if (isManagedStorageDatastorePath(datastorePath)) { + datastorePath = getManagedDatastoreName(datastorePath); + } HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec(); FileQueryFlags fqf = new FileQueryFlags(); fqf.setFileSize(true); @@ -1241,11 +1254,9 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { String vmdkName = null; // if this is managed storage - if (fullPath.startsWith("[-iqn.")) { // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] -iqn.2010-01.com.company:3y8w.vol-10.64-0-000001.vmdk - baseName = fullPath.split(" ")[0]; // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] - - // remove '[' and ']' - baseName = baseName.substring(1, baseName.length() - 1); + if (isManagedStorageDatastorePath(fullPath)) { + baseName = getManagedDatastoreName(fullPath); + baseName = baseName.substring(1, baseName.length() - 1); // remove '[' and ']' vmdkName = fullPath; // for managed storage, vmdkName == fullPath } else { @@ -1288,12 +1299,9 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } } else { Map mapNewDisk = getNewDiskMap(vmMo); - // if this is managed storage - if (path.startsWith("[-iqn.")) { // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] -iqn.2010-01.com.company:3y8w.vol-10.64-0-000001.vmdk - path = path.split(" ")[0]; // ex. [-iqn.2010-01.com.company:3y8w.vol-10.64-0] - - // remove '[' and ']' - baseName = path.substring(1, path.length() - 1); + if (isManagedStorageDatastorePath(path)) { + path = getManagedDatastoreName(path); + baseName = path.substring(1, path.length() - 1); // remove '[' and ']' } else { baseName = VmwareHelper.trimSnapshotDeltaPostfix(path); } diff --git a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 01d6f6816e0..e76b34954c6 100644 --- a/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -940,6 +940,11 @@ public class VmwareResource extends ServerResourceBase implements StoragePoolRes ManagedObjectReference morDS = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, VmwareResource.getDatastoreName(iScsiName)); DatastoreMO dsMo = new DatastoreMO(hyperHost.getContext(), morDS); + if (path.startsWith("[-iqn.")) { + // Rescan 1:1 LUN that VMware may not know the LUN was recently resized + _storageProcessor.rescanAllHosts(context, lstHosts, true, true); + } + _storageProcessor.expandDatastore(hostDatastoreSystem, dsMo); } diff --git a/plugins/hypervisors/vmware/src/main/java/com/cloud/storage/resource/VmwareStorageProcessor.java b/plugins/hypervisors/vmware/src/main/java/com/cloud/storage/resource/VmwareStorageProcessor.java index 7b4d5f118b4..ba9d16f8186 100644 --- a/plugins/hypervisors/vmware/src/main/java/com/cloud/storage/resource/VmwareStorageProcessor.java +++ b/plugins/hypervisors/vmware/src/main/java/com/cloud/storage/resource/VmwareStorageProcessor.java @@ -2825,7 +2825,15 @@ public class VmwareStorageProcessor implements StorageProcessor { morDs = firstHostDatastoreSystemMO.findDatastoreByName(datastoreName); if (morDs == null) { - morDs = firstHostDatastoreSystemMO.createVmfsDatastore(datastoreName, hostScsiDisk); + final String hostVersion = firstHostMO.getProductVersion(); + if (hostVersion.compareTo(VmwareHelper.MIN_VERSION_VMFS6) >= 0) { + morDs = firstHostDatastoreSystemMO.createVmfs6Datastore(datastoreName, hostScsiDisk); + } else { + morDs = firstHostDatastoreSystemMO.createVmfs5Datastore(datastoreName, hostScsiDisk); + } + } else { + // in case of iSCSI/solidfire 1:1 VMFS datastore could be inaccessible + mountVmfsDatastore(new DatastoreMO(context, morDs), lstHosts); } if (morDs != null) { @@ -3364,7 +3372,7 @@ public class VmwareStorageProcessor implements StorageProcessor { } } - private void rescanAllHosts(VmwareContext context, List> lstHostPairs, boolean rescanHba, boolean rescanVmfs) throws Exception { + public void rescanAllHosts(VmwareContext context, List> lstHostPairs, boolean rescanHba, boolean rescanVmfs) throws Exception { List hosts = new ArrayList<>(lstHostPairs.size()); for (Pair hostPair : lstHostPairs) { diff --git a/plugins/hypervisors/vmware/src/test/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImplTest.java b/plugins/hypervisors/vmware/src/test/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImplTest.java index 1d207e37bca..c72f23c628e 100644 --- a/plugins/hypervisors/vmware/src/test/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImplTest.java +++ b/plugins/hypervisors/vmware/src/test/java/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImplTest.java @@ -116,4 +116,15 @@ public class VmwareStorageManagerImplTest { public void testSetVolumeToPathAndSizeDatastoreClusterDifferentChildStore() { testCommon(Storage.StoragePoolType.PreSetup, Storage.StoragePoolType.DatastoreCluster, true); } + + @Test + public void testIsManagedStorageDatastorePath() { + Assert.assertTrue("Test if [-iqn... is a managed storage", storageManager.isManagedStorageDatastorePath("[-iqn.2010-01.com.solidfire:3p53.data-9999.97-0] i-2-9999-VM.vmdk")); + Assert.assertFalse("Test if [SomeDS] is not a managed storage", storageManager.isManagedStorageDatastorePath("[SomeDS] i-2-9999-VM/disk.vmdk")); + } + + @Test + public void testGetManagedDatastoreName() { + Assert.assertEquals("[-iqn.2010-01.com.solidfire:3p53.data-9999.97-0]", storageManager.getManagedDatastoreName("[-iqn.2010-01.com.solidfire:3p53.data-9999.97-0] i-2-9999-VM.vmdk")); + } } diff --git a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java index 702bdc3669a..4478dc98ca4 100644 --- a/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java +++ b/plugins/storage/volume/solidfire/src/main/java/org/apache/cloudstack/storage/datastore/driver/SolidFirePrimaryDataStoreDriver.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.storage.datastore.driver; import java.text.NumberFormat; +import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -85,6 +86,8 @@ import com.cloud.user.dao.AccountDao; import com.cloud.utils.Pair; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.VirtualMachine; import com.google.common.base.Preconditions; public class SolidFirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { @@ -111,6 +114,7 @@ public class SolidFirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { @Inject private PrimaryDataStoreDao storagePoolDao; @Inject private StoragePoolDetailsDao storagePoolDetailsDao; @Inject private VMTemplatePoolDao vmTemplatePoolDao; + @Inject private VMInstanceDao vmDao; @Inject private VolumeDao volumeDao; @Inject private VolumeDetailsDao volumeDetailsDao; @Inject private VolumeDataFactory volumeFactory; @@ -187,13 +191,33 @@ public class SolidFirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { } } + private boolean isRevokeAccessNotNeeded(DataObject dataObject) { + // Workaround: don't unplug iscsi lun when volume is attached to a VM + // This is regression workaround from upper layers which are calling + // a releaseVmResources() method that calls the revoke on an attached disk + if (dataObject.getType() == DataObjectType.VOLUME) { + Volume volume = volumeDao.findById(dataObject.getId()); + if (volume.getInstanceId() != null) { + VirtualMachine vm = vmDao.findById(volume.getInstanceId()); + if (vm != null && !Arrays.asList(VirtualMachine.State.Destroyed, VirtualMachine.State.Expunging, VirtualMachine.State.Error).contains(vm.getState())) { + return true; + } + } + } + return false; + } + @Override - public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore) - { + public void revokeAccess(DataObject dataObject, Host host, DataStore dataStore) { if (dataObject == null || host == null || dataStore == null) { return; } + if (isRevokeAccessNotNeeded(dataObject)) { + LOGGER.debug("Skipping revoke access for Solidfire data object type:" + dataObject.getType() + " id:" + dataObject.getId()); + return; + } + long sfVolumeId = getSolidFireVolumeId(dataObject, false); long clusterId = host.getClusterId(); long storagePoolId = dataStore.getId(); @@ -210,6 +234,8 @@ public class SolidFirePrimaryDataStoreDriver implements PrimaryDataStoreDriver { throw new CloudRuntimeException(errMsg); } + LOGGER.debug("Revoking access for Solidfire data object type:" + dataObject.getType() + " id:" + dataObject.getId()); + try { SolidFireUtil.SolidFireConnection sfConnection = SolidFireUtil.getSolidFireConnection(storagePoolId, storagePoolDetailsDao); diff --git a/vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java b/vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java index 30798e31e19..c2fe3f4e54c 100644 --- a/vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java +++ b/vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/HostDatastoreSystemMO.java @@ -199,18 +199,21 @@ public class HostDatastoreSystemMO extends BaseMO { return _context.getService().queryAvailableDisksForVmfs(_mor, null); } - public ManagedObjectReference createVmfsDatastore(String datastoreName, HostScsiDisk hostScsiDisk) throws Exception { - // just grab the first instance of VmfsDatastoreOption - VmfsDatastoreOption vmfsDatastoreOption = _context.getService().queryVmfsDatastoreCreateOptions(_mor, hostScsiDisk.getDevicePath(), 5).get(0); - + public ManagedObjectReference createVmfsDatastore(String datastoreName, HostScsiDisk hostScsiDisk, Integer vmfsVersion) throws Exception { + VmfsDatastoreOption vmfsDatastoreOption = _context.getService().queryVmfsDatastoreCreateOptions(_mor, hostScsiDisk.getDevicePath(), vmfsVersion).get(0); VmfsDatastoreCreateSpec vmfsDatastoreCreateSpec = (VmfsDatastoreCreateSpec)vmfsDatastoreOption.getSpec(); - - // set the name of the datastore to be created vmfsDatastoreCreateSpec.getVmfs().setVolumeName(datastoreName); - return _context.getService().createVmfsDatastore(_mor, vmfsDatastoreCreateSpec); } + public ManagedObjectReference createVmfs5Datastore(String datastoreName, HostScsiDisk hostScsiDisk) throws Exception { + return createVmfsDatastore(datastoreName, hostScsiDisk, 5); + } + + public ManagedObjectReference createVmfs6Datastore(String datastoreName, HostScsiDisk hostScsiDisk) throws Exception { + return createVmfsDatastore(datastoreName, hostScsiDisk, 6); + } + public boolean deleteDatastore(String name) throws Exception { ManagedObjectReference morDatastore = findDatastore(name); if (morDatastore != null) { diff --git a/vmware-base/src/main/java/com/cloud/hypervisor/vmware/util/VmwareHelper.java b/vmware-base/src/main/java/com/cloud/hypervisor/vmware/util/VmwareHelper.java index 4a81beeff98..841d914af32 100644 --- a/vmware-base/src/main/java/com/cloud/hypervisor/vmware/util/VmwareHelper.java +++ b/vmware-base/src/main/java/com/cloud/hypervisor/vmware/util/VmwareHelper.java @@ -98,6 +98,7 @@ public class VmwareHelper { public static final int MAX_SUPPORTED_DEVICES_SCSI_CONTROLLER = MAX_ALLOWED_DEVICES_SCSI_CONTROLLER - 1; // One device node is unavailable for hard disks or SCSI devices public static final int MAX_USABLE_SCSI_CONTROLLERS = 2; public static final String MIN_VERSION_UEFI_LEGACY = "5.5"; + public static final String MIN_VERSION_VMFS6 = "6.5"; public static boolean isReservedScsiDeviceNumber(int deviceNumber) { // The SCSI controller is assigned to virtual device node (z:7), so that device node is unavailable for hard disks or SCSI devices. From f5a1f4130d554c648d030c14cdd7ad212976e9cf Mon Sep 17 00:00:00 2001 From: Wei Zhou Date: Fri, 25 Aug 2023 11:35:31 +0200 Subject: [PATCH 2/6] server: fix global setting system.vm.public.ip.reservation.mode.strictness is not really dynamic (#7909) If the original value is `false`, and search build is configured without the condition. Now change the value to `true`, it will not get effective due to missing condition. --- .../main/java/com/cloud/network/IpAddressManagerImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java index 60e7c5d12bf..bb5371ed271 100644 --- a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java +++ b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java @@ -496,9 +496,8 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage AssignIpAddressSearch.and("dc", AssignIpAddressSearch.entity().getDataCenterId(), Op.EQ); AssignIpAddressSearch.and("allocated", AssignIpAddressSearch.entity().getAllocatedTime(), Op.NULL); AssignIpAddressSearch.and("vlanId", AssignIpAddressSearch.entity().getVlanId(), Op.IN); - if (SystemVmPublicIpReservationModeStrictness.value()) { - AssignIpAddressSearch.and("forSystemVms", AssignIpAddressSearch.entity().isForSystemVms(), Op.EQ); - } + AssignIpAddressSearch.and("forSystemVms", AssignIpAddressSearch.entity().isForSystemVms(), Op.EQ); + SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); vlanSearch.and("type", vlanSearch.entity().getVlanType(), Op.EQ); vlanSearch.and("networkId", vlanSearch.entity().getNetworkId(), Op.EQ); From 8dc5fdd067d555e3fdb04704627bca043b766174 Mon Sep 17 00:00:00 2001 From: Wei Zhou Date: Fri, 25 Aug 2023 11:36:39 +0200 Subject: [PATCH 3/6] server: fix cannot get systemvm ips in dedicated ranges (#7144) This fixes #6698 --- .../java/com/cloud/api/ApiResponseHelper.java | 2 +- .../ConfigurationManagerImpl.java | 8 +- .../cloud/network/IpAddressManagerImpl.java | 275 +++++++++--------- .../integration/smoke/test_public_ip_range.py | 3 +- ui/public/locales/en.json | 1 + .../views/infra/network/IpRangesTabPublic.vue | 6 +- 6 files changed, 151 insertions(+), 144 deletions(-) diff --git a/server/src/main/java/com/cloud/api/ApiResponseHelper.java b/server/src/main/java/com/cloud/api/ApiResponseHelper.java index 05aee6b6ccb..17c465d40ce 100644 --- a/server/src/main/java/com/cloud/api/ApiResponseHelper.java +++ b/server/src/main/java/com/cloud/api/ApiResponseHelper.java @@ -901,7 +901,7 @@ public class ApiResponseHelper implements ResponseGenerator { Long networkId = vlan.getNetworkId(); if (networkId != null) { Network network = _ntwkModel.getNetwork(networkId); - if (network != null) { + if (network != null && TrafficType.Guest.equals(network.getTrafficType())) { Long accountId = network.getAccountId(); populateAccount(vlanResponse, accountId); populateDomain(vlanResponse, ApiDBUtils.findAccountById(accountId).getDomainId()); diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index 737cdc769f6..455a964b8d7 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -5397,10 +5397,11 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati // Check if any of the Public IP addresses is allocated to another // account - boolean forSystemVms = false; final List ips = _publicIpAddressDao.listByVlanId(vlanDbId); for (final IPAddressVO ip : ips) { - forSystemVms = ip.isForSystemVms(); + if (ip.isForSystemVms()) { + throw new InvalidParameterValueException(ip.getAddress() + " Public IP address in range is dedicated to system vms "); + } final Long allocatedToAccountId = ip.getAllocatedToAccountId(); if (allocatedToAccountId != null) { if (vlanOwner != null && allocatedToAccountId != vlanOwner.getId()) { @@ -5425,7 +5426,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid()); } - } else if (domain != null && !forSystemVms) { + } else if (domain != null) { // Create an DomainVlanMapVO entry DomainVlanMapVO domainVlanMapVO = new DomainVlanMapVO(domain.getId(), vlan.getId()); _domainVlanMapDao.persist(domainVlanMapVO); @@ -7250,7 +7251,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Override public Domain getVlanDomain(long vlanId) { Vlan vlan = _vlanDao.findById(vlanId); - Long domainId = null; // if vlan is Virtual Domain specific, get vlan information from the // accountVlanMap; otherwise get account information diff --git a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java index bb5371ed271..9882ed50353 100644 --- a/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java +++ b/server/src/main/java/com/cloud/network/IpAddressManagerImpl.java @@ -334,19 +334,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage @DB private IPAddressVO assignAndAllocateIpAddressEntry(final Account owner, final VlanType vlanUse, final Long guestNetworkId, final boolean sourceNat, final boolean allocate, final boolean isSystem, - final Long vpcId, final Boolean displayIp, final boolean fetchFromDedicatedRange, + final Long vpcId, final Boolean displayIp, final List addressVOS) throws CloudRuntimeException { return Transaction.execute((TransactionCallbackWithException) status -> { IPAddressVO finalAddress = null; - if (!fetchFromDedicatedRange && VlanType.VirtualNetwork.equals(vlanUse)) { - // Check that the maximum number of public IPs for the given accountId will not be exceeded - try { - _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip); - } catch (ResourceAllocationException ex) { - s_logger.warn("Failed to allocate resource of type " + ex.getResourceType() + " for account " + owner); - throw new AccountLimitException("Maximum number of public IP addresses for account: " + owner.getAccountName() + " has been exceeded."); - } - } for (IPAddressVO possibleAddr : addressVOS) { if (possibleAddr.getState() != State.Free) { @@ -826,6 +817,10 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage throws InsufficientAddressCapacityException { List addrs = listAvailablePublicIps(dcId, podId, vlanDbIds, owner, vlanUse, guestNetworkId, sourceNat, assign, allocate, requestedIp, requestedGateway, isSystem, vpcId, displayIp, forSystemVms, true); IPAddressVO addr = addrs.get(0); + if (assign) { + addr = assignAndAllocateIpAddressEntry(owner, vlanUse, guestNetworkId, sourceNat, allocate, + isSystem,vpcId, displayIp, addrs); + } if (vlanUse == VlanType.VirtualNetwork) { _firewallMgr.addSystemFirewallRules(addr, owner); } @@ -837,128 +832,99 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage public List listAvailablePublicIps(final long dcId, final Long podId, final List vlanDbIds, final Account owner, final VlanType vlanUse, final Long guestNetworkId, final boolean sourceNat, final boolean assign, final boolean allocate, final String requestedIp, final String requestedGateway, final boolean isSystem, final Long vpcId, final Boolean displayIp, final boolean forSystemVms, final boolean lockOneRow) throws InsufficientAddressCapacityException { - return Transaction.execute(new TransactionCallbackWithException, InsufficientAddressCapacityException>() { - @Override - public List doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException { - StringBuilder errorMessage = new StringBuilder("Unable to get ip address in "); - boolean fetchFromDedicatedRange = false; - List dedicatedVlanDbIds = new ArrayList(); - List nonDedicatedVlanDbIds = new ArrayList(); - DataCenter zone = _entityMgr.findById(DataCenter.class, dcId); - SearchCriteria sc = null; - if (podId != null) { - sc = AssignIpAddressFromPodVlanSearch.create(); - sc.setJoinParameters("podVlanMapSB", "podId", podId); - errorMessage.append(" pod id=" + podId); - } else { - sc = AssignIpAddressSearch.create(); - errorMessage.append(" zone id=" + dcId); - } + StringBuilder errorMessage = new StringBuilder("Unable to get ip address in "); + boolean fetchFromDedicatedRange = false; + List dedicatedVlanDbIds = new ArrayList(); + List nonDedicatedVlanDbIds = new ArrayList(); + DataCenter zone = _entityMgr.findById(DataCenter.class, dcId); - // If owner has dedicated Public IP ranges, fetch IP from the dedicated range - // Otherwise fetch IP from the system pool - Network network = _networksDao.findById(guestNetworkId); - //Checking if network is null in the case of system VM's. At the time of allocation of IP address to systemVm, no network is present. - if(network == null || !(network.getGuestType() == GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) { - List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(owner.getId()); - for (AccountVlanMapVO map : maps) { - if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId())) - dedicatedVlanDbIds.add(map.getVlanDbId()); - } - } - List domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId()); - for (DomainVlanMapVO map : domainMaps) { + SearchCriteria sc = null; + if (podId != null) { + sc = AssignIpAddressFromPodVlanSearch.create(); + sc.setJoinParameters("podVlanMapSB", "podId", podId); + errorMessage.append(" pod id=" + podId); + } else { + sc = AssignIpAddressSearch.create(); + errorMessage.append(" zone id=" + dcId); + } + + sc.setParameters("dc", dcId); + + // for direct network take ip addresses only from the vlans belonging to the network + if (vlanUse == VlanType.DirectAttached) { + sc.setJoinParameters("vlan", "networkId", guestNetworkId); + errorMessage.append(", network id=" + guestNetworkId); + } + if (requestedGateway != null) { + sc.setJoinParameters("vlan", "vlanGateway", requestedGateway); + errorMessage.append(", requested gateway=" + requestedGateway); + } + sc.setJoinParameters("vlan", "type", vlanUse); + + Network network = _networksDao.findById(guestNetworkId); + String routerIpAddress = null; + if (network != null) { + NetworkDetailVO routerIpDetail = _networkDetailsDao.findDetail(network.getId(), ApiConstants.ROUTER_IP); + routerIpAddress = routerIpDetail != null ? routerIpDetail.getValue() : null; + } + if (requestedIp != null) { + sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp); + errorMessage.append(": requested ip " + requestedIp + " is not available"); + } else if (routerIpAddress != null) { + sc.addAnd("address", Op.NEQ, routerIpAddress); + } + + boolean ascOrder = ! forSystemVms; + Filter filter = new Filter(IPAddressVO.class, "forSystemVms", ascOrder, 0l, 1l); + + filter.addOrderBy(IPAddressVO.class,"vlanId", true); + + List addrs = new ArrayList<>(); + + if (forSystemVms) { + // Get Public IPs for system vms in dedicated ranges + sc.setParameters("forSystemVms", true); + if (lockOneRow) { + addrs = _ipAddressDao.lockRows(sc, filter, true); + } else { + addrs = new ArrayList<>(_ipAddressDao.search(sc, null)); + } + } + if ((!lockOneRow || (lockOneRow && CollectionUtils.isEmpty(addrs))) && + !(forSystemVms && SystemVmPublicIpReservationModeStrictness.value())) { + sc.setParameters("forSystemVms", false); + // If owner has dedicated Public IP ranges, fetch IP from the dedicated range + // Otherwise fetch IP from the system pool + // Checking if network is null in the case of system VM's. At the time of allocation of IP address to systemVm, no network is present. + if (network == null || !(network.getGuestType() == GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) { + List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(owner.getId()); + for (AccountVlanMapVO map : maps) { if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId())) dedicatedVlanDbIds.add(map.getVlanDbId()); } - List nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId); - for (VlanVO nonDedicatedVlan : nonDedicatedVlans) { - if (vlanDbIds == null || vlanDbIds.contains(nonDedicatedVlan.getId())) - nonDedicatedVlanDbIds.add(nonDedicatedVlan.getId()); - } - - if (vlanUse == VlanType.VirtualNetwork) { - if (!dedicatedVlanDbIds.isEmpty()) { - fetchFromDedicatedRange = true; - sc.setParameters("vlanId", dedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray())); - } else if (!nonDedicatedVlanDbIds.isEmpty()) { - sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); - } else { - if (podId != null) { - InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId); - ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid()); - throw ex; - } - s_logger.warn(errorMessage.toString()); - InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId); - ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid()); - throw ex; - } - } - - sc.setParameters("dc", dcId); - - // for direct network take ip addresses only from the vlans belonging to the network - if (vlanUse == VlanType.DirectAttached) { - sc.setJoinParameters("vlan", "networkId", guestNetworkId); - errorMessage.append(", network id=" + guestNetworkId); - } - if (requestedGateway != null) { - sc.setJoinParameters("vlan", "vlanGateway", requestedGateway); - errorMessage.append(", requested gateway=" + requestedGateway); - } - sc.setJoinParameters("vlan", "type", vlanUse); - String routerIpAddress = null; - if (network != null) { - NetworkDetailVO routerIpDetail = _networkDetailsDao.findDetail(network.getId(), ApiConstants.ROUTER_IP); - routerIpAddress = routerIpDetail != null ? routerIpDetail.getValue() : null; - } - if (requestedIp != null) { - sc.addAnd("address", SearchCriteria.Op.EQ, requestedIp); - errorMessage.append(": requested ip " + requestedIp + " is not available"); - } else if (routerIpAddress != null) { - sc.addAnd("address", Op.NEQ, routerIpAddress); - } - - boolean ascOrder = ! forSystemVms; - Filter filter = new Filter(IPAddressVO.class, "forSystemVms", ascOrder, 0l, 1l); - if (SystemVmPublicIpReservationModeStrictness.value()) { - sc.setParameters("forSystemVms", forSystemVms); - } - - filter.addOrderBy(IPAddressVO.class,"vlanId", true); - - List addrs; - - if (lockOneRow) { - addrs = _ipAddressDao.lockRows(sc, filter, true); + } + List domainMaps = _domainVlanMapDao.listDomainVlanMapsByDomain(owner.getDomainId()); + for (DomainVlanMapVO map : domainMaps) { + if (vlanDbIds == null || vlanDbIds.contains(map.getVlanDbId())) + dedicatedVlanDbIds.add(map.getVlanDbId()); + } + List nonDedicatedVlans = _vlanDao.listZoneWideNonDedicatedVlans(dcId); + for (VlanVO nonDedicatedVlan : nonDedicatedVlans) { + if (vlanDbIds == null || vlanDbIds.contains(nonDedicatedVlan.getId())) + nonDedicatedVlanDbIds.add(nonDedicatedVlan.getId()); + } + if (vlanUse == VlanType.VirtualNetwork) { + if (!dedicatedVlanDbIds.isEmpty()) { + fetchFromDedicatedRange = true; + sc.setParameters("vlanId", dedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(dedicatedVlanDbIds.toArray())); + } else if (!nonDedicatedVlanDbIds.isEmpty()) { + sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); } else { - addrs = new ArrayList<>(_ipAddressDao.search(sc, null)); - } - - // If all the dedicated IPs of the owner are in use fetch an IP from the system pool - if ((!lockOneRow || (lockOneRow && addrs.size() == 0)) && fetchFromDedicatedRange && vlanUse == VlanType.VirtualNetwork) { - // Verify if account is allowed to acquire IPs from the system - boolean useSystemIps = UseSystemPublicIps.valueIn(owner.getId()); - if (useSystemIps && !nonDedicatedVlanDbIds.isEmpty()) { - fetchFromDedicatedRange = false; - sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); - errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); - if (lockOneRow) { - addrs = _ipAddressDao.lockRows(sc, filter, true); - } else { - addrs.addAll(_ipAddressDao.search(sc, null)); - } - } - } - - if (lockOneRow && addrs.size() == 0) { if (podId != null) { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId); - // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid()); throw ex; } @@ -967,17 +933,58 @@ public class IpAddressManagerImpl extends ManagerBase implements IpAddressManage ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid()); throw ex; } - - if (lockOneRow) { - assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size(); - } - if (assign) { - assignAndAllocateIpAddressEntry(owner, vlanUse, guestNetworkId, sourceNat, allocate, - isSystem,vpcId, displayIp, fetchFromDedicatedRange, addrs); - } - return addrs; } - }); + if (lockOneRow) { + addrs = _ipAddressDao.lockRows(sc, filter, true); + } else { + addrs = new ArrayList<>(_ipAddressDao.search(sc, null)); + } + + // If all the dedicated IPs of the owner are in use fetch an IP from the system pool + if ((!lockOneRow || (lockOneRow && addrs.size() == 0)) && fetchFromDedicatedRange && vlanUse == VlanType.VirtualNetwork) { + // Verify if account is allowed to acquire IPs from the system + boolean useSystemIps = UseSystemPublicIps.valueIn(owner.getId()); + if (useSystemIps && !nonDedicatedVlanDbIds.isEmpty()) { + fetchFromDedicatedRange = false; + sc.setParameters("vlanId", nonDedicatedVlanDbIds.toArray()); + errorMessage.append(", vlanId id=" + Arrays.toString(nonDedicatedVlanDbIds.toArray())); + if (lockOneRow) { + addrs = _ipAddressDao.lockRows(sc, filter, true); + } else { + addrs.addAll(_ipAddressDao.search(sc, null)); + } + } + } + } + + if (lockOneRow && addrs.size() == 0) { + if (podId != null) { + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", Pod.class, podId); + // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. + ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid()); + throw ex; + } + s_logger.warn(errorMessage.toString()); + InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException("Insufficient address capacity", DataCenter.class, dcId); + ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid()); + throw ex; + } + + if (lockOneRow) { + assert (addrs.size() == 1) : "Return size is incorrect: " + addrs.size(); + } + + if (assign && !fetchFromDedicatedRange && VlanType.VirtualNetwork.equals(vlanUse)) { + // Check that the maximum number of public IPs for the given accountId will not be exceeded + try { + _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip); + } catch (ResourceAllocationException ex) { + s_logger.warn("Failed to allocate resource of type " + ex.getResourceType() + " for account " + owner); + throw new AccountLimitException("Maximum number of public IP addresses for account: " + owner.getAccountName() + " has been exceeded."); + } + } + + return addrs; } @DB diff --git a/test/integration/smoke/test_public_ip_range.py b/test/integration/smoke/test_public_ip_range.py index 69baf5f2fc2..19edc4c164f 100644 --- a/test/integration/smoke/test_public_ip_range.py +++ b/test/integration/smoke/test_public_ip_range.py @@ -128,9 +128,8 @@ class TestDedicatePublicIPRange(cloudstackTestCase): id=self.public_ip_range.vlan.id ) public_ip_response = list_public_ip_range_response[0] - self.assertEqual( + self.assertIsNone( public_ip_response.account, - "system", "Check account name is system account in listVlanIpRanges" ) return diff --git a/ui/public/locales/en.json b/ui/public/locales/en.json index 1469170ae01..528ea521c53 100644 --- a/ui/public/locales/en.json +++ b/ui/public/locales/en.json @@ -1901,6 +1901,7 @@ "label.suspend.project": "Suspend project", "label.switch.type": "Switch type", "label.sync.storage": "Sync storage pool", +"label.system.ip.pool": "System Pool", "label.system.offering": "System offering", "label.system.offerings": "System offerings", "label.system.service.offering": "System service offering", diff --git a/ui/src/views/infra/network/IpRangesTabPublic.vue b/ui/src/views/infra/network/IpRangesTabPublic.vue index 247a8faf0d4..d7f743fda13 100644 --- a/ui/src/views/infra/network/IpRangesTabPublic.vue +++ b/ui/src/views/infra/network/IpRangesTabPublic.vue @@ -47,21 +47,21 @@ {{ record.endip || record.endipv6 }}