diff --git a/api/src/main/java/com/cloud/vm/VmDetailConstants.java b/api/src/main/java/com/cloud/vm/VmDetailConstants.java index 521633a0c597..13b6d28e6ed3 100644 --- a/api/src/main/java/com/cloud/vm/VmDetailConstants.java +++ b/api/src/main/java/com/cloud/vm/VmDetailConstants.java @@ -70,6 +70,10 @@ public interface VmDetailConstants { String CPU_SPEED = "cpuSpeed"; String MEMORY = "memory"; + // VM deployment with custom root disk offering params + String MIN_IOPS = "minIops"; + String MAX_IOPS = "maxIops"; + // Misc details for internal usage (not to be set/changed by user or admin) String CPU_OVER_COMMIT_RATIO = "cpuOvercommitRatio"; String MEMORY_OVER_COMMIT_RATIO = "memoryOvercommitRatio"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index fa55b424eaf3..31e72cb2ee7a 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -53,7 +53,8 @@ public class UpdateStoragePoolCmd extends BaseCmd { @Parameter(name = ApiConstants.TAGS, type = CommandType.LIST, collectionType = CommandType.STRING, description = "Comma-separated list of tags for the storage pool") private List tags; - @Parameter(name = ApiConstants.CAPACITY_IOPS, type = CommandType.LONG, required = false, description = "IOPS CloudStack can provision from this storage pool", validations={ApiArgValidator.PositiveNumber}) + @Parameter(name = ApiConstants.CAPACITY_IOPS, type = CommandType.LONG, required = false, description = "IOPS CloudStack can provision from this storage pool", + validations = {ApiArgValidator.PositiveNumber}) private Long capacityIops; @Parameter(name = ApiConstants.CAPACITY_BYTES, type = CommandType.LONG, required = false, description = "Bytes CloudStack can provision from this storage pool",validations={ApiArgValidator.PositiveNumber}) diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java index f8f744285c04..60f4f308503d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java @@ -15,14 +15,14 @@ // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.api.command.user.volume; -import org.apache.cloudstack.api.BaseAsyncCmd; - import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiArgValidator; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.ServerApiException; @@ -60,7 +60,7 @@ public class ResizeVolumeCmd extends BaseAsyncCmd implements UserCmd { @Parameter(name = ApiConstants.MAX_IOPS, type = CommandType.LONG, required = false, description = "New maximum number of IOPS") private Long maxIops; - @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, required = false, description = "New volume size in GB") + @Parameter(name = ApiConstants.SIZE, type = CommandType.LONG, required = false, description = "New volume size in GB",validations = {ApiArgValidator.PositiveNumber}) private Long size; @Parameter(name = ApiConstants.SHRINK_OK, type = CommandType.BOOLEAN, required = false, description = "Verify OK to Shrink") diff --git a/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java index cd5cac7228eb..3cc884ef7705 100755 --- a/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java @@ -19,6 +19,7 @@ import static com.cloud.configuration.ConfigurationManagerImpl.EXPOSE_ERRORS_TO_USER; import static com.cloud.configuration.ConfigurationManagerImpl.MIGRATE_VM_ACROSS_CLUSTERS; +import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.lang.reflect.Field; import java.net.URI; @@ -320,6 +321,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac public static final String VM_WORK_JOB_HANDLER = VirtualMachineManagerImpl.class.getSimpleName(); private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert"; + private static final String ONTAP_SVM_NAME_DETAIL = "svmName"; + private static final String ONTAP_SVM_UUID_DETAIL = "svmUUID"; + private static final String ONTAP_STORAGE_IP_DETAIL = "storageIP"; + private static final String ONTAP_PROTOCOL_DETAIL = "protocol"; @Inject private UserVmManager _userVmMgr; @@ -3567,15 +3572,63 @@ protected void executeManagedStorageChecksWhenTargetStoragePoolProvided(StorageP if (currentPool.getId() == targetPool.getId()) { return; } + if (isSupportedOntapLiveStorageMigration(currentPool, targetPool)) { + return; + } Map details = _storagePoolDao.getDetails(currentPool.getId()); if (details != null && Boolean.parseBoolean(details.get(Storage.Capability.ALLOW_MIGRATE_OTHER_POOLS.toString()))) { return; } + if (DataStoreProvider.ONTAP_PLUGIN_NAME.equals(currentPool.getStorageProviderName()) + && DataStoreProvider.ONTAP_PLUGIN_NAME.equals(targetPool.getStorageProviderName())) { + Map targetDetails = _storagePoolDao.getDetails(targetPool.getId()); + throw new CloudRuntimeException(String.format("ONTAP migration requires matching storageIP, SVM, protocol, and pool type " + + "[source: storageIP=%s, svmUUID=%s, svmName=%s, protocol=%s, type=%s; destination: storageIP=%s, svmUUID=%s, svmName=%s, protocol=%s, type=%s].", + details != null ? details.get(ONTAP_STORAGE_IP_DETAIL) : null, + details != null ? details.get(ONTAP_SVM_UUID_DETAIL) : null, + details != null ? details.get(ONTAP_SVM_NAME_DETAIL) : null, details != null ? details.get(ONTAP_PROTOCOL_DETAIL) : null, + currentPool.getPoolType(), targetDetails != null ? targetDetails.get(ONTAP_STORAGE_IP_DETAIL) : null, + targetDetails != null ? targetDetails.get(ONTAP_SVM_UUID_DETAIL) : null, + targetDetails != null ? targetDetails.get(ONTAP_SVM_NAME_DETAIL) : null, + targetDetails != null ? targetDetails.get(ONTAP_PROTOCOL_DETAIL) : null, targetPool.getPoolType())); + } throw new CloudRuntimeException(String.format("Currently, a volume on managed storage can only be 'migrated' to itself " + "[volumeId=%s, currentStoragePoolId=%s, targetStoragePoolId=%s].", volume.getUuid(), currentPool.getUuid(), targetPool.getUuid())); } + protected boolean isSupportedOntapLiveStorageMigration(StoragePoolVO currentPool, StoragePoolVO targetPool) { + if (!DataStoreProvider.ONTAP_PLUGIN_NAME.equals(currentPool.getStorageProviderName()) + || !DataStoreProvider.ONTAP_PLUGIN_NAME.equals(targetPool.getStorageProviderName())) { + return false; + } + + Map currentDetails = _storagePoolDao.getDetails(currentPool.getId()); + Map targetDetails = _storagePoolDao.getDetails(targetPool.getId()); + if (currentDetails == null || targetDetails == null) { + return false; + } + + String currentSvmName = currentDetails.get(ONTAP_SVM_NAME_DETAIL); + String targetSvmName = targetDetails.get(ONTAP_SVM_NAME_DETAIL); + String currentSvmUuid = currentDetails.get(ONTAP_SVM_UUID_DETAIL); + String targetSvmUuid = targetDetails.get(ONTAP_SVM_UUID_DETAIL); + String currentStorageIp = currentDetails.get(ONTAP_STORAGE_IP_DETAIL); + String targetStorageIp = targetDetails.get(ONTAP_STORAGE_IP_DETAIL); + String currentProtocol = currentDetails.get(ONTAP_PROTOCOL_DETAIL); + String targetProtocol = targetDetails.get(ONTAP_PROTOCOL_DETAIL); + boolean isSameSvm = isNotBlank(currentSvmUuid) || isNotBlank(targetSvmUuid) + ? isNotBlank(currentSvmUuid) && currentSvmUuid.equals(targetSvmUuid) + : isNotBlank(currentSvmName) && currentSvmName.equals(targetSvmName); + return isNotBlank(currentStorageIp) + && currentStorageIp.equals(targetStorageIp) + && isSameSvm + && isNotBlank(currentProtocol) + && currentProtocol.equalsIgnoreCase(targetProtocol) + && currentPool.getPoolType() != null + && currentPool.getPoolType() == targetPool.getPoolType(); + } + /** * For each one of the volumes we will map it to a storage pool that is available via the target host. * An exception is thrown if we cannot find a storage pool that is accessible in the target host to migrate the volume to. diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java index 9f6d02cc1234..9a06e7285e4d 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/CloudOrchestrator.java @@ -61,14 +61,12 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.VmDetailConstants; import com.cloud.vm.VmDiskInfo; import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDetailsDao; import com.cloud.vm.dao.VMInstanceDao; -import static org.apache.cloudstack.api.ApiConstants.MAX_IOPS; -import static org.apache.cloudstack.api.ApiConstants.MIN_IOPS; - @Component public class CloudOrchestrator implements OrchestrationService { @@ -205,8 +203,8 @@ public VirtualMachineEntity createVirtualMachine(String id, String owner, String Map userVmDetails = _vmInstanceDetailsDao.listDetailsKeyPairs(vm.getId()); if (userVmDetails != null) { - String minIops = userVmDetails.get(MIN_IOPS); - String maxIops = userVmDetails.get(MAX_IOPS); + String minIops = userVmDetails.get(VmDetailConstants.MIN_IOPS); + String maxIops = userVmDetails.get(VmDetailConstants.MAX_IOPS); rootDiskOfferingInfo.setMinIops(minIops != null && minIops.trim().length() > 0 ? Long.parseLong(minIops) : null); rootDiskOfferingInfo.setMaxIops(maxIops != null && maxIops.trim().length() > 0 ? Long.parseLong(maxIops) : null); diff --git a/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java b/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java index fe51440bd81b..3292c6bd5c9e 100644 --- a/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java +++ b/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java @@ -567,6 +567,62 @@ public void allowVolumeMigrationsForPowerFlexStorage() { verify(storagePoolVoMock, Mockito.times(0)).getId(); } + @Test + public void allowVolumeMigrationBetweenOntapPoolsOnSameSvmAndProtocol() { + StoragePoolVO targetPool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(true).when(storagePoolVoMock).isManaged(); + Mockito.doReturn(Storage.StoragePoolType.OntapiSCSI).when(storagePoolVoMock).getPoolType(); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(storagePoolVoMock).getStorageProviderName(); + Mockito.doReturn(12L).when(targetPool).getId(); + Mockito.doReturn(Storage.StoragePoolType.OntapiSCSI).when(targetPool).getPoolType(); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(targetPool).getStorageProviderName(); + Mockito.doReturn(Map.of("storageIP", "10.0.0.1", "svmName", "svm1", "protocol", "ISCSI")) + .when(storagePoolDaoMock).getDetails(storagePoolVoMockId); + Mockito.doReturn(Map.of("storageIP", "10.0.0.1", "svmName", "svm1", "protocol", "ISCSI")) + .when(storagePoolDaoMock).getDetails(12L); + + virtualMachineManagerImpl.executeManagedStorageChecksWhenTargetStoragePoolProvided(storagePoolVoMock, volumeVoMock, targetPool); + } + + @Test + public void rejectVolumeMigrationBetweenOntapPoolsUsingDifferentProtocols() { + StoragePoolVO targetPool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(true).when(storagePoolVoMock).isManaged(); + Mockito.doReturn(Storage.StoragePoolType.OntapiSCSI).when(storagePoolVoMock).getPoolType(); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(storagePoolVoMock).getStorageProviderName(); + Mockito.doReturn(12L).when(targetPool).getId(); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(targetPool).getStorageProviderName(); + Mockito.doReturn(Map.of("storageIP", "10.0.0.1", "svmName", "svm1", "protocol", "ISCSI")) + .when(storagePoolDaoMock).getDetails(storagePoolVoMockId); + Mockito.doReturn(Map.of("storageIP", "10.0.0.1", "svmName", "svm1", "protocol", "NFS3")) + .when(storagePoolDaoMock).getDetails(12L); + + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, + () -> virtualMachineManagerImpl.executeManagedStorageChecksWhenTargetStoragePoolProvided(storagePoolVoMock, volumeVoMock, targetPool)); + assertTrue(exception.getMessage().contains("protocol=ISCSI")); + assertTrue(exception.getMessage().contains("protocol=NFS3")); + } + + @Test + public void rejectOntapPoolsWithSameSvmNameOnDifferentStorageSystems() { + StoragePoolVO targetPool = Mockito.mock(StoragePoolVO.class); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(storagePoolVoMock).getStorageProviderName(); + Mockito.doReturn(12L).when(targetPool).getId(); + Mockito.doReturn(org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider.ONTAP_PLUGIN_NAME) + .when(targetPool).getStorageProviderName(); + Mockito.doReturn(Map.of("storageIP", "10.0.0.1", "svmName", "svm1", "protocol", "NFS3")) + .when(storagePoolDaoMock).getDetails(storagePoolVoMockId); + Mockito.doReturn(Map.of("storageIP", "10.0.0.2", "svmName", "svm1", "protocol", "NFS3")) + .when(storagePoolDaoMock).getDetails(12L); + + assertFalse(virtualMachineManagerImpl.isSupportedOntapLiveStorageMigration(storagePoolVoMock, targetPool)); + } + @Test public void executeManagedStorageChecksWhenTargetStoragePoolProvidedTestCurrentStoragePoolEqualsTargetPool() { Mockito.doReturn(true).when(storagePoolVoMock).isManaged(); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java new file mode 100644 index 000000000000..fd7deac04548 --- /dev/null +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/CloudOrchestratorTest.java @@ -0,0 +1,111 @@ +// 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. +package org.apache.cloudstack.engine.orchestration; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.offering.DiskOfferingInfo; +import com.cloud.service.ServiceOfferingVO; +import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.dao.DiskOfferingDao; +import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.utils.component.ComponentContext; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.VmDetailConstants; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.dao.VMInstanceDetailsDao; +import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntityImpl; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class CloudOrchestratorTest { + + private static final long VM_ID = 1L; + private static final long SERVICE_OFFERING_ID = 2L; + private static final long ROOT_DISK_OFFERING_ID = 3L; + private static final String TEMPLATE_ID = "4"; + + @InjectMocks + private CloudOrchestrator cloudOrchestrator = new CloudOrchestrator(); + + @Mock + private VirtualMachineManager _itMgr; + @Mock + private VMTemplateDao _templateDao; + @Mock + private VMInstanceDao _vmDao; + @Mock + private VMInstanceDetailsDao _vmInstanceDetailsDao; + @Mock + private ServiceOfferingDao _serviceOfferingDao; + @Mock + private DiskOfferingDao _diskOfferingDao; + + @Test + public void createVirtualMachineSetsCustomIopsFromVmDetails() throws Exception { + VMInstanceVO vm = Mockito.mock(VMInstanceVO.class); + ServiceOfferingVO serviceOffering = Mockito.mock(ServiceOfferingVO.class); + DiskOfferingVO rootDiskOffering = Mockito.mock(DiskOfferingVO.class); + VMTemplateVO template = Mockito.mock(VMTemplateVO.class); + VirtualMachineEntityImpl vmEntity = Mockito.mock(VirtualMachineEntityImpl.class); + + Mockito.when(_vmDao.findByUuid("vm-uuid")).thenReturn(vm); + Mockito.when(vm.getId()).thenReturn(VM_ID); + Mockito.when(vm.getServiceOfferingId()).thenReturn(SERVICE_OFFERING_ID); + Mockito.when(vm.getInstanceName()).thenReturn("i-1-1-VM"); + Mockito.when(_serviceOfferingDao.findById(VM_ID, SERVICE_OFFERING_ID)).thenReturn(serviceOffering); + Mockito.when(_diskOfferingDao.findById(ROOT_DISK_OFFERING_ID)).thenReturn(rootDiskOffering); + Mockito.when(rootDiskOffering.isCustomizedIops()).thenReturn(true); + Mockito.when(_templateDao.findById(Long.valueOf(TEMPLATE_ID))).thenReturn(template); + + Map details = new HashMap<>(); + details.put(VmDetailConstants.MIN_IOPS, "100"); + details.put(VmDetailConstants.MAX_IOPS, "1000"); + Mockito.when(_vmInstanceDetailsDao.listDetailsKeyPairs(VM_ID)).thenReturn(details); + + try (MockedStatic componentContext = Mockito.mockStatic(ComponentContext.class)) { + componentContext.when(() -> ComponentContext.inject(VirtualMachineEntityImpl.class)).thenReturn(vmEntity); + + cloudOrchestrator.createVirtualMachine("vm-uuid", "owner", TEMPLATE_ID, "host", "display", HypervisorType.KVM.name(), + 1, 1000, 1024, null, Collections.emptyList(), Collections.emptyList(), Collections.emptyMap(), null, + null, null, null, null, ROOT_DISK_OFFERING_ID, null, null, null, null); + } + + ArgumentCaptor rootDiskOfferingInfo = ArgumentCaptor.forClass(DiskOfferingInfo.class); + Mockito.verify(_itMgr).allocate(Mockito.eq("i-1-1-VM"), Mockito.eq(template), Mockito.eq(serviceOffering), rootDiskOfferingInfo.capture(), + Mockito.anyList(), Mockito.anyList(), Mockito.any(LinkedHashMap.class), Mockito.isNull(), Mockito.eq(HypervisorType.KVM), + Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull()); + + Assert.assertEquals(Long.valueOf(100), rootDiskOfferingInfo.getValue().getMinIops()); + Assert.assertEquals(Long.valueOf(1000), rootDiskOfferingInfo.getValue().getMaxIops()); + } +} diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java index 4cd9a8e23bfc..16b8eb975ac4 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDao.java @@ -182,6 +182,13 @@ public interface VolumeDao extends GenericDao, StateDao implements Vol protected static final String SELECT_HYPERTYPE_FROM_CLUSTER_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?"; protected static final String SELECT_HYPERTYPE_FROM_ZONE_VOLUME = "SELECT s.hypervisor from volumes v, storage_pool s where v.pool_id = s.id and v.id = ?"; protected static final String SELECT_POOLSCOPE = "SELECT s.scope from storage_pool s, volumes v where s.id = v.pool_id and v.id = ?"; + // Looks for a VM whose Ready root disk is on this pool and whose attached Ready data disk is on another pool. + // LIMIT 1 stops after the first match so we do not load all volumes. + private static final String HAS_MULTI_PRIMARY_STORAGE_POOL_VM = + "SELECT 1 FROM volumes root INNER JOIN volumes data ON data.instance_id = root.instance_id " + + "WHERE root.pool_id = ? AND root.volume_type = 'ROOT' AND root.instance_id IS NOT NULL " + + "AND root.removed IS NULL AND root.state = 'Ready' " + + "AND data.volume_type = 'DATADISK' AND data.pool_id IS NOT NULL AND data.pool_id <> ? " + + "AND data.removed IS NULL AND data.state = 'Ready' LIMIT 1"; private static final String ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT_PART1 = "SELECT pool.id, SUM(IF(vol.state='Ready' AND vol.account_id = ?, 1, 0)) FROM `cloud`.`storage_pool` pool LEFT JOIN `cloud`.`volumes` vol ON pool.id = vol.pool_id WHERE pool.data_center_id = ? "; private static final String ORDER_POOLS_NUMBER_OF_VOLUMES_FOR_ACCOUNT_PART2 = " GROUP BY pool.id ORDER BY 2 ASC "; @@ -998,6 +1006,21 @@ public boolean existsWithKmsKey(long kmsKeyId) { return findOneBy(sc) != null; } + @Override + @DB + public boolean hasMultiPrimaryStoragePoolVm(long poolId) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(HAS_MULTI_PRIMARY_STORAGE_POOL_VM)) { + pstmt.setLong(1, poolId); + pstmt.setLong(2, poolId); + try (ResultSet rs = pstmt.executeQuery()) { + return rs.next(); + } + } catch (SQLException e) { + throw new CloudRuntimeException("DB Exception on: " + HAS_MULTI_PRIMARY_STORAGE_POOL_VM, e); + } + } + public VolumeVO findByExternalUuid(String externalUuid) { SearchCriteria sc = ExternalUuidSearch.create(); sc.setParameters("externalUuid", externalUuid); diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java index 17f84b780698..818f9c3a6ee8 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java @@ -48,6 +48,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreCapabilities; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; @@ -240,13 +241,22 @@ public StrategyPriority canHandle(DataObject srcData, DataObject destData) { if (srcData instanceof VolumeInfo && destData instanceof VolumeInfo) { VolumeInfo srcVolumeInfo = (VolumeInfo)srcData; + VolumeInfo destVolumeInfo = (VolumeInfo)destData; + + // OntapDataMotionStrategy also returns HIGHEST for these and a tie keeps the first strategy. + if (srcVolumeInfo.getState() == Volume.State.Migrating) { + StoragePoolVO srcPool = _storagePoolDao.findById(srcVolumeInfo.getDataStore().getId()); + StoragePoolVO destPool = _storagePoolDao.findById(destVolumeInfo.getDataStore().getId()); + if ((srcPool != null && DataStoreProvider.ONTAP_PLUGIN_NAME.equals(srcPool.getStorageProviderName())) + || (destPool != null && DataStoreProvider.ONTAP_PLUGIN_NAME.equals(destPool.getStorageProviderName()))) { + return StrategyPriority.CANT_HANDLE; + } + } if (isVolumeOnManagedStorage(srcVolumeInfo)) { return StrategyPriority.HIGHEST; } - VolumeInfo destVolumeInfo = (VolumeInfo)destData; - if (isVolumeOnManagedStorage(destVolumeInfo)) { return StrategyPriority.HIGHEST; } @@ -327,6 +337,20 @@ public final StrategyPriority canHandle(Map volumeMap, Ho * Handles migrating volumes on managed Storage. */ protected StrategyPriority internalCanHandle(Map volumeMap, Host srcHost, Host destHost) { + // OntapDataMotionStrategy also returns HIGHEST for these and a tie keeps the first strategy. + for (VolumeInfo volumeInfo : volumeMap.keySet()) { + StoragePoolVO storagePoolVO = _storagePoolDao.findById(volumeInfo.getPoolId()); + if (storagePoolVO != null && DataStoreProvider.ONTAP_PLUGIN_NAME.equals(storagePoolVO.getStorageProviderName())) { + return StrategyPriority.CANT_HANDLE; + } + } + for (DataStore dataStore : volumeMap.values()) { + StoragePoolVO storagePoolVO = _storagePoolDao.findById(dataStore.getId()); + if (storagePoolVO != null && DataStoreProvider.ONTAP_PLUGIN_NAME.equals(storagePoolVO.getStorageProviderName())) { + return StrategyPriority.CANT_HANDLE; + } + } + Set volumeInfoSet = volumeMap.keySet(); for (VolumeInfo volumeInfo : volumeInfoSet) { diff --git a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java index fc51eeba7b6e..2680b7c25faf 100644 --- a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java +++ b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java @@ -30,6 +30,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; @@ -133,6 +134,46 @@ public void internalCanHandleTestNoStoragePoolsIsManaged() { configureAndTestInternalCanHandle(false, false, StrategyPriority.CANT_HANDLE); } + @Test + public void canHandleDeclinesMigratingVolumeOnOntapPrimary() { + PrimaryDataStore srcStore = mock(PrimaryDataStoreImpl.class); + PrimaryDataStore destStore = mock(PrimaryDataStoreImpl.class); + VolumeObject srcVolume = mock(VolumeObject.class); + VolumeObject destVolume = mock(VolumeObject.class); + doReturn(Volume.State.Migrating).when(srcVolume).getState(); + doReturn(srcStore).when(srcVolume).getDataStore(); + doReturn(destStore).when(destVolume).getDataStore(); + doReturn(1L).when(srcStore).getId(); + doReturn(2L).when(destStore).getId(); + StoragePoolVO srcPool = Mockito.spy(new StoragePoolVO()); + StoragePoolVO destPool = Mockito.spy(new StoragePoolVO()); + lenient().doReturn(true).when(srcPool).isManaged(); + doReturn(DataStoreProvider.ONTAP_PLUGIN_NAME).when(destPool).getStorageProviderName(); + doReturn(srcPool).when(primaryDataStoreDao).findById(1L); + doReturn(destPool).when(primaryDataStoreDao).findById(2L); + + Assert.assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(srcVolume, destVolume)); + } + + @Test + public void internalCanHandleDeclinesMapWithOntapPool() { + VolumeObject volumeInfo = Mockito.spy(new VolumeObject()); + Mockito.doReturn(0L).when(volumeInfo).getPoolId(); + DataStore ds = Mockito.spy(new PrimaryDataStoreImpl()); + Mockito.doReturn(1L).when(ds).getId(); + Map volumeMap = new HashMap<>(); + volumeMap.put(volumeInfo, ds); + StoragePoolVO srcPool = Mockito.spy(new StoragePoolVO()); + lenient().doReturn(true).when(srcPool).isManaged(); + StoragePoolVO destPool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn(DataStoreProvider.ONTAP_PLUGIN_NAME).when(destPool).getStorageProviderName(); + Mockito.doReturn(srcPool).when(primaryDataStoreDao).findById(0L); + Mockito.doReturn(destPool).when(primaryDataStoreDao).findById(1L); + + Assert.assertEquals(StrategyPriority.CANT_HANDLE, + strategy.internalCanHandle(volumeMap, new HostVO("srcHostUuid"), new HostVO("destHostUuid"))); + } + private void configureAndTestInternalCanHandle(boolean sPool0IsManaged, boolean sPool1IsManaged, StrategyPriority expectedStrategyPriority) { VolumeObject volumeInfo = Mockito.spy(new VolumeObject()); Mockito.doReturn(0l).when(volumeInfo).getPoolId(); @@ -555,6 +596,7 @@ public void testInternalCanHandle_ClvmSourceManagedDestination() { Mockito.doReturn(0L).when(volumeInfo).getPoolId(); DataStore ds = Mockito.spy(new PrimaryDataStoreImpl()); + Mockito.lenient().doReturn(1L).when(ds).getId(); Map volumeMap = new HashMap<>(); volumeMap.put(volumeInfo, ds); @@ -580,6 +622,7 @@ public void testInternalCanHandle_ClvmNgSourceManagedDestination() { Mockito.doReturn(0L).when(volumeInfo).getPoolId(); DataStore ds = Mockito.spy(new PrimaryDataStoreImpl()); + Mockito.lenient().doReturn(1L).when(ds).getId(); Map volumeMap = new HashMap<>(); volumeMap.put(volumeInfo, ds); @@ -605,6 +648,7 @@ public void testInternalCanHandle_ClvmToClvmNg() { Mockito.doReturn(0L).when(volumeInfo).getPoolId(); DataStore ds = Mockito.spy(new PrimaryDataStoreImpl()); + Mockito.lenient().doReturn(1L).when(ds).getId(); Map volumeMap = new HashMap<>(); volumeMap.put(volumeInfo, ds); @@ -633,6 +677,7 @@ public void testInternalCanHandle_ClvmNgToClvm() { Mockito.doReturn(0L).when(volumeInfo).getPoolId(); DataStore ds = Mockito.spy(new PrimaryDataStoreImpl()); + Mockito.lenient().doReturn(1L).when(ds).getId(); Map volumeMap = new HashMap<>(); volumeMap.put(volumeInfo, ds); diff --git a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 05bbf13c9745..06dcb125ada5 100644 --- a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -1007,7 +1007,6 @@ private TemplateInfo createManagedTemplateVolume(TemplateInfo srcTemplateInfo, P } else { errMesg = callback.result.getResult(); } - templateOnPrimary.processEvent(Event.OperationFailed); throw new CloudRuntimeException(String.format("Unable to create template %s on primary storage %s: %s", templateOnPrimary.getImage(), destPrimaryDataStore, errMesg)); } @@ -1015,8 +1014,12 @@ private TemplateInfo createManagedTemplateVolume(TemplateInfo srcTemplateInfo, P } catch (Throwable e) { logger.debug("Failed to create template volume on storage", e); - templateOnPrimary.processEvent(Event.OperationFailed); - throw new CloudRuntimeException(e.getMessage()); + try { + templateOnPrimary.processEvent(Event.OperationFailed); + } catch (Exception stateEx) { + logger.warn("Unable to mark template {} as failed on primary storage {}: {}", templateOnPrimary.getImage(), destPrimaryDataStore, stateEx.getMessage()); + } + throw new CloudRuntimeException(e.getMessage(), e); } finally { _tmpltPoolDao.releaseFromLockTable(templatePoolRefId); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java index b9a85806c8ea..198c3f568599 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java @@ -37,6 +37,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -3428,8 +3429,13 @@ public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { destFormat, destVolumePath, destPrimaryStore.getId(), destPrimaryStore.getUuid(), destPrimaryStore.getName(), destPrimaryStore.getPoolType())); + Map srcDetails = ObjectUtils.defaultIfNull( + ObjectUtils.firstNonNull(srcPrimaryStore.getDetails(), cmd.getOptions()), Collections.emptyMap()); + Map destDetails = ObjectUtils.defaultIfNull( + ObjectUtils.firstNonNull(destPrimaryStore.getDetails(), cmd.getOptions2()), Collections.emptyMap()); + if (srcPrimaryStore.isManaged()) { - if (!storagePoolMgr.connectPhysicalDisk(srcPrimaryStore.getPoolType(), srcPrimaryStore.getUuid(), srcVolumePath, srcPrimaryStore.getDetails())) { + if (!storagePoolMgr.connectPhysicalDisk(srcPrimaryStore.getPoolType(), srcPrimaryStore.getUuid(), srcVolumePath, srcDetails)) { logger.warn(String.format("Failed to connect src volume %s, in storage pool %s", srcVol, srcPrimaryStore)); } } @@ -3445,12 +3451,25 @@ public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { volume.setVmName(srcVol.getVmName()); KVMPhysicalDisk newVolume; String destVolumeName; - destPool = storagePoolMgr.getStoragePool(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid()); + try { + destPool = storagePoolMgr.getStoragePool(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid()); + } catch (CloudRuntimeException e) { + if (destPrimaryStore.isManaged() && e.getMessage().contains("not found")) { + destPool = storagePoolMgr.createStoragePool(destPrimaryStore.getUuid(), destPrimaryStore.getHost(), + destPrimaryStore.getPort(), destPrimaryStore.getPath(), null, destPrimaryStore.getPoolType(), + destDetails); + } else { + throw e; + } + } if (destPrimaryStore.isManaged()) { - if (!storagePoolMgr.connectPhysicalDisk(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid(), destVolumePath, destPrimaryStore.getDetails())) { + if (!storagePoolMgr.connectPhysicalDisk(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid(), destVolumePath, destDetails)) { logger.warn("Failed to connect dest volume {}, in storage pool {}", destVol, destPrimaryStore); } - destVolumeName = derivePath(destPrimaryStore, destData, destPrimaryStore.getDetails()); + } + if (destPrimaryStore.isManaged()) { + destVolumeName = StringUtils.defaultIfBlank( + derivePath(destPrimaryStore, destData, destDetails), destVolumePath); } else { PhysicalDiskFormat destPoolDefaultFormat = destPool.getDefaultFormat(); destFormat = getFormat(destPoolDefaultFormat); diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java index a85fc31224e0..1a03e19cc8f0 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java @@ -29,10 +29,14 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef; import com.cloud.storage.Storage; +import com.cloud.storage.Volume; import com.cloud.storage.template.TemplateConstants; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; +import org.apache.cloudstack.storage.command.CopyCmdAnswer; +import org.apache.cloudstack.storage.command.CopyCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.qemu.QemuImageOptions; @@ -49,6 +53,7 @@ import org.libvirt.Domain; import org.libvirt.LibvirtException; import org.mockito.InjectMocks; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; @@ -162,6 +167,237 @@ public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationEnoughSpace() } } + @Test + public void copyManagedVolumeWithoutTargetReturnsCopiedDiskPath() { + CopyCommand command = Mockito.mock(CopyCommand.class); + VolumeObjectTO sourceVolume = Mockito.mock(VolumeObjectTO.class); + VolumeObjectTO destinationVolume = Mockito.mock(VolumeObjectTO.class); + PrimaryDataStoreTO sourceStore = Mockito.mock(PrimaryDataStoreTO.class); + PrimaryDataStoreTO destinationStore = Mockito.mock(PrimaryDataStoreTO.class); + KVMStoragePool destinationPool = Mockito.mock(KVMStoragePool.class); + KVMPhysicalDisk sourceDisk = Mockito.mock(KVMPhysicalDisk.class); + KVMPhysicalDisk copiedDisk = Mockito.mock(KVMPhysicalDisk.class); + Map destinationDetails = Map.of(); + + Mockito.when(command.getSrcTO()).thenReturn(sourceVolume); + Mockito.when(command.getDestTO()).thenReturn(destinationVolume); + Mockito.when(command.getWaitInMillSeconds()).thenReturn(60); + Mockito.when(sourceVolume.getDataStore()).thenReturn(sourceStore); + Mockito.when(destinationVolume.getDataStore()).thenReturn(destinationStore); + Mockito.when(sourceVolume.getPath()).thenReturn("source-path"); + Mockito.when(destinationVolume.getPath()).thenReturn("destination-path"); + Mockito.when(sourceVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(destinationVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(sourceVolume.getVolumeType()).thenReturn(Volume.Type.DATADISK); + Mockito.when(sourceStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(destinationStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(sourceStore.getUuid()).thenReturn("source-pool"); + Mockito.when(destinationStore.getUuid()).thenReturn("destination-pool"); + Mockito.when(destinationStore.getHost()).thenReturn("destination-host"); + Mockito.when(destinationStore.getPort()).thenReturn(2049); + Mockito.when(destinationStore.getPath()).thenReturn("/destination-export"); + Mockito.when(sourceStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.getDetails()).thenReturn(destinationDetails); + Mockito.when(storagePoolManager.getStoragePool( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool")).thenThrow(new CloudRuntimeException("not found")); + Mockito.when(storagePoolManager.createStoragePool( + "destination-pool", "destination-host", 2049, "/destination-export", null, + Storage.StoragePoolType.NetworkFilesystem, destinationDetails)).thenReturn(destinationPool); + Mockito.when(storagePoolManager.getPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path")).thenReturn(sourceDisk); + Mockito.when(storagePoolManager.copyPhysicalDisk( + Mockito.eq(sourceDisk), Mockito.eq("destination-path"), + Mockito.eq(destinationPool), Mockito.eq(60))).thenReturn(copiedDisk); + Mockito.when(copiedDisk.getFormat()).thenReturn(QemuImg.PhysicalDiskFormat.QCOW2); + + CopyCmdAnswer answer = (CopyCmdAnswer)storageProcessor.copyVolumeFromPrimaryToPrimary(command); + + InOrder destinationPoolSetup = Mockito.inOrder(storagePoolManager); + destinationPoolSetup.verify(storagePoolManager).getStoragePool( + Storage.StoragePoolType.NetworkFilesystem, "destination-pool"); + destinationPoolSetup.verify(storagePoolManager).createStoragePool( + "destination-pool", "destination-host", 2049, "/destination-export", null, + Storage.StoragePoolType.NetworkFilesystem, destinationDetails); + destinationPoolSetup.verify(storagePoolManager).connectPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool", "destination-path", destinationStore.getDetails()); + Assert.assertTrue(answer.getResult()); + Assert.assertEquals("destination-path", answer.getNewData().getPath()); + } + + @Test + public void copyVolumeFromPrimaryToPrimaryUsesCommandOptionsWhenStoreDetailsAreNull() { + CopyCommand command = Mockito.mock(CopyCommand.class); + VolumeObjectTO sourceVolume = Mockito.mock(VolumeObjectTO.class); + VolumeObjectTO destinationVolume = Mockito.mock(VolumeObjectTO.class); + PrimaryDataStoreTO sourceStore = Mockito.mock(PrimaryDataStoreTO.class); + PrimaryDataStoreTO destinationStore = Mockito.mock(PrimaryDataStoreTO.class); + KVMStoragePool destinationPool = Mockito.mock(KVMStoragePool.class); + KVMPhysicalDisk sourceDisk = Mockito.mock(KVMPhysicalDisk.class); + KVMPhysicalDisk copiedDisk = Mockito.mock(KVMPhysicalDisk.class); + Map sourceDetails = Map.of("iqn", "/iqn.source/7"); + Map destinationDetails = Map.of(); + + Mockito.when(command.getSrcTO()).thenReturn(sourceVolume); + Mockito.when(command.getDestTO()).thenReturn(destinationVolume); + Mockito.when(command.getWaitInMillSeconds()).thenReturn(60); + Mockito.when(command.getOptions()).thenReturn(sourceDetails); + Mockito.when(sourceVolume.getDataStore()).thenReturn(sourceStore); + Mockito.when(destinationVolume.getDataStore()).thenReturn(destinationStore); + Mockito.when(sourceVolume.getPath()).thenReturn("source-path"); + Mockito.when(destinationVolume.getPath()).thenReturn("destination-path"); + Mockito.when(sourceVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(destinationVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(sourceVolume.getVolumeType()).thenReturn(Volume.Type.DATADISK); + Mockito.when(sourceStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(destinationStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(sourceStore.getUuid()).thenReturn("source-pool"); + Mockito.when(destinationStore.getUuid()).thenReturn("destination-pool"); + Mockito.when(sourceStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.isManaged()).thenReturn(true); + Mockito.when(sourceStore.getDetails()).thenReturn(null); + Mockito.when(destinationStore.getDetails()).thenReturn(destinationDetails); + Mockito.when(storagePoolManager.getStoragePool( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool")).thenReturn(destinationPool); + Mockito.when(storagePoolManager.getPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path")).thenReturn(sourceDisk); + Mockito.when(storagePoolManager.copyPhysicalDisk( + Mockito.eq(sourceDisk), Mockito.eq("destination-path"), + Mockito.eq(destinationPool), Mockito.eq(60))).thenReturn(copiedDisk); + Mockito.when(copiedDisk.getFormat()).thenReturn(QemuImg.PhysicalDiskFormat.QCOW2); + + CopyCmdAnswer answer = (CopyCmdAnswer)storageProcessor.copyVolumeFromPrimaryToPrimary(command); + + Mockito.verify(storagePoolManager).connectPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path", sourceDetails); + Assert.assertTrue(answer.getResult()); + Assert.assertEquals("destination-path", answer.getNewData().getPath()); + } + + @Test + public void copyVolumeFromPrimaryToPrimaryUsesCommandOptions2WhenStoreDetailsAreNull() { + CopyCommand command = Mockito.mock(CopyCommand.class); + VolumeObjectTO sourceVolume = Mockito.mock(VolumeObjectTO.class); + VolumeObjectTO destinationVolume = Mockito.mock(VolumeObjectTO.class); + PrimaryDataStoreTO sourceStore = Mockito.mock(PrimaryDataStoreTO.class); + PrimaryDataStoreTO destinationStore = Mockito.mock(PrimaryDataStoreTO.class); + KVMStoragePool destinationPool = Mockito.mock(KVMStoragePool.class); + KVMPhysicalDisk sourceDisk = Mockito.mock(KVMPhysicalDisk.class); + KVMPhysicalDisk copiedDisk = Mockito.mock(KVMPhysicalDisk.class); + Map destinationDetails = Map.of("managedStoreTarget", "destination-iqn-path"); + + Mockito.when(command.getSrcTO()).thenReturn(sourceVolume); + Mockito.when(command.getDestTO()).thenReturn(destinationVolume); + Mockito.when(command.getWaitInMillSeconds()).thenReturn(60); + Mockito.when(command.getOptions2()).thenReturn(destinationDetails); + Mockito.when(sourceVolume.getDataStore()).thenReturn(sourceStore); + Mockito.when(destinationVolume.getDataStore()).thenReturn(destinationStore); + Mockito.when(sourceVolume.getPath()).thenReturn("source-path"); + Mockito.when(destinationVolume.getPath()).thenReturn("destination-path"); + Mockito.when(sourceVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(destinationVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(sourceVolume.getVolumeType()).thenReturn(Volume.Type.DATADISK); + Mockito.when(sourceStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(destinationStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(sourceStore.getUuid()).thenReturn("source-pool"); + Mockito.when(destinationStore.getUuid()).thenReturn("destination-pool"); + Mockito.when(destinationStore.getHost()).thenReturn("destination-host"); + Mockito.when(destinationStore.getPort()).thenReturn(2049); + Mockito.when(destinationStore.getPath()).thenReturn("/destination-export"); + Mockito.when(sourceStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.getDetails()).thenReturn(null); + Mockito.when(storagePoolManager.getStoragePool( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool")).thenThrow(new CloudRuntimeException("not found")); + Mockito.when(storagePoolManager.createStoragePool( + "destination-pool", "destination-host", 2049, "/destination-export", null, + Storage.StoragePoolType.NetworkFilesystem, destinationDetails)).thenReturn(destinationPool); + Mockito.when(storagePoolManager.getPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path")).thenReturn(sourceDisk); + Mockito.when(storagePoolManager.copyPhysicalDisk( + Mockito.eq(sourceDisk), Mockito.eq("destination-iqn-path"), + Mockito.eq(destinationPool), Mockito.eq(60))).thenReturn(copiedDisk); + Mockito.when(copiedDisk.getFormat()).thenReturn(QemuImg.PhysicalDiskFormat.QCOW2); + + CopyCmdAnswer answer = (CopyCmdAnswer)storageProcessor.copyVolumeFromPrimaryToPrimary(command); + + Mockito.verify(storagePoolManager).createStoragePool( + "destination-pool", "destination-host", 2049, "/destination-export", null, + Storage.StoragePoolType.NetworkFilesystem, destinationDetails); + Mockito.verify(storagePoolManager).connectPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool", "destination-path", destinationDetails); + Assert.assertTrue(answer.getResult()); + Assert.assertEquals("destination-iqn-path", answer.getNewData().getPath()); + } + + @Test + public void copyVolumeFromPrimaryToPrimaryPrefersStoreDetailsOverCommandOptions() { + CopyCommand command = Mockito.mock(CopyCommand.class); + VolumeObjectTO sourceVolume = Mockito.mock(VolumeObjectTO.class); + VolumeObjectTO destinationVolume = Mockito.mock(VolumeObjectTO.class); + PrimaryDataStoreTO sourceStore = Mockito.mock(PrimaryDataStoreTO.class); + PrimaryDataStoreTO destinationStore = Mockito.mock(PrimaryDataStoreTO.class); + KVMStoragePool destinationPool = Mockito.mock(KVMStoragePool.class); + KVMPhysicalDisk sourceDisk = Mockito.mock(KVMPhysicalDisk.class); + KVMPhysicalDisk copiedDisk = Mockito.mock(KVMPhysicalDisk.class); + Map sourceStoreDetails = Map.of("iqn", "/iqn.store/1"); + Map destinationStoreDetails = Map.of("nfsMountOpts", "vers=3"); + + Mockito.when(command.getSrcTO()).thenReturn(sourceVolume); + Mockito.when(command.getDestTO()).thenReturn(destinationVolume); + Mockito.when(command.getWaitInMillSeconds()).thenReturn(60); + Mockito.when(command.getOptions()).thenReturn(Map.of("iqn", "/iqn.command/9")); + Mockito.when(command.getOptions2()).thenReturn(Map.of("managedStoreTarget", "command-target")); + Mockito.when(sourceVolume.getDataStore()).thenReturn(sourceStore); + Mockito.when(destinationVolume.getDataStore()).thenReturn(destinationStore); + Mockito.when(sourceVolume.getPath()).thenReturn("source-path"); + Mockito.when(destinationVolume.getPath()).thenReturn("destination-path"); + Mockito.when(sourceVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(destinationVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + Mockito.when(sourceVolume.getVolumeType()).thenReturn(Volume.Type.DATADISK); + Mockito.when(sourceStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(destinationStore.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + Mockito.when(sourceStore.getUuid()).thenReturn("source-pool"); + Mockito.when(destinationStore.getUuid()).thenReturn("destination-pool"); + Mockito.when(sourceStore.isManaged()).thenReturn(true); + Mockito.when(destinationStore.isManaged()).thenReturn(true); + Mockito.when(sourceStore.getDetails()).thenReturn(sourceStoreDetails); + Mockito.when(destinationStore.getDetails()).thenReturn(destinationStoreDetails); + Mockito.when(storagePoolManager.getStoragePool( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool")).thenReturn(destinationPool); + Mockito.when(storagePoolManager.getPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path")).thenReturn(sourceDisk); + Mockito.when(storagePoolManager.copyPhysicalDisk( + Mockito.eq(sourceDisk), Mockito.eq("destination-path"), + Mockito.eq(destinationPool), Mockito.eq(60))).thenReturn(copiedDisk); + Mockito.when(copiedDisk.getFormat()).thenReturn(QemuImg.PhysicalDiskFormat.QCOW2); + + CopyCmdAnswer answer = (CopyCmdAnswer)storageProcessor.copyVolumeFromPrimaryToPrimary(command); + + Mockito.verify(storagePoolManager).connectPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "source-pool", "source-path", sourceStoreDetails); + Mockito.verify(storagePoolManager).connectPhysicalDisk( + Storage.StoragePoolType.NetworkFilesystem, + "destination-pool", "destination-path", destinationStoreDetails); + Mockito.verify(storagePoolManager, Mockito.never()).createStoragePool( + Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), + Mockito.nullable(String.class), Mockito.any(Storage.StoragePoolType.class), Mockito.any()); + Assert.assertTrue(answer.getResult()); + Assert.assertEquals("destination-path", answer.getNewData().getPath()); + } + @Test public void testIsEnoughSpaceForDownloadTemplateOnTemporaryLocationNotExistingLocation() { try (MockedStatic