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 2b9b41b6e8ac..9cda6c7017da 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 @@ -520,6 +520,66 @@ public Pair findPod(VirtualMachineTemplate template, ServiceOffering return null; } + /** The snapshot (and where it is) that a volume is created from. */ + protected static class SnapshotForVolume { + final SnapshotInfo snapInfo; + final DataStoreRole dataStoreRole; + final boolean kvmSnapshotOnlyInPrimaryStorage; + + SnapshotForVolume(SnapshotInfo snapInfo, DataStoreRole dataStoreRole, boolean kvmSnapshotOnlyInPrimaryStorage) { + this.snapInfo = snapInfo; + this.dataStoreRole = dataStoreRole; + this.kvmSnapshotOnlyInPrimaryStorage = kvmSnapshotOnlyInPrimaryStorage; + } + } + + /** + * Picks the copy of the snapshot to create the volume from. Unless the primary storage creates volumes from its own + * snapshots (StorPool and Linstor through CAN_CREATE_TEMPLATE_FROM_SNAPSHOT, PowerFlex through + * {@link SnapshotHelper#isSnapshotOnStorageCreatingVolumesFromIt}), a KVM snapshot kept only on primary storage is first + * copied to secondary storage. + */ + protected SnapshotForVolume prepareSnapshotForVolumeCreation(Snapshot snapshot, SnapshotForVolume current, boolean storageSupportSnapshotToTemplateEnabled, long zoneId) { + if (storageSupportSnapshotToTemplateEnabled) { + return current; + } + if (snapshotHelper.isSnapshotOnStorageCreatingVolumesFromIt(current.snapInfo)) { + // The primary storage creates the volume from its own snapshot, there is no temporary copy on secondary storage + logger.debug("Creating volume from snapshot [{}] on primary storage, the storage creates the volume from it", current.snapInfo.getSnapshotVO()); + return new SnapshotForVolume(current.snapInfo, current.dataStoreRole, false); + } + SnapshotInfo snapInfo = current.snapInfo; + boolean kvmSnapshotOnlyInPrimaryStorage = current.kvmSnapshotOnlyInPrimaryStorage; + try { + DataStoreRole dataStoreRole = snapshotHelper.getDataStoreRole(snapshot); + snapInfo = snapshotFactory.getSnapshotWithRoleAndZone(snapshot.getId(), dataStoreRole, zoneId); + kvmSnapshotOnlyInPrimaryStorage = snapshotHelper.isKvmSnapshotOnlyInPrimaryStorage(snapshot, dataStoreRole); + logger.debug("Creating volume from snapshot, with dataStore role {} and on primary storage: {}", dataStoreRole, kvmSnapshotOnlyInPrimaryStorage); + snapInfo = snapshotHelper.backupSnapshotToSecondaryStorageIfNotExists(snapInfo, dataStoreRole, snapshot, kvmSnapshotOnlyInPrimaryStorage); + return new SnapshotForVolume(snapInfo, dataStoreRole, kvmSnapshotOnlyInPrimaryStorage); + } catch (CloudRuntimeException e) { + snapshotHelper.expungeTemporarySnapshot(kvmSnapshotOnlyInPrimaryStorage, snapInfo); + throw e; + } + } + + /** + * When the snapshot's pool creates volumes from its own snapshots (PowerFlex), only that pool can hold the new volume: + * adds every other pool of the zone to the pools to avoid. + * @return the required pool id, or null when any suitable pool can be used + */ + protected Long avoidPoolsOtherThanRequiredForSnapshot(Snapshot snapshot, long zoneId, Set poolsToAvoid) { + Long requiredPoolId = snapshotHelper.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(snapshot, zoneId); + if (requiredPoolId != null) { + for (StoragePoolVO otherPool : _storagePoolDao.listByDataCenterId(zoneId)) { + if (otherPool.getId() != requiredPoolId) { + poolsToAvoid.add(otherPool); + } + } + } + return requiredPoolId; + } + @DB @Override public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, UserVm vm) throws StorageUnavailableException { @@ -545,6 +605,11 @@ public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, Use String msg = String.format("There are no available storage pools to store the volume [%s] in. ", volumeToString); + Long requiredPoolId = avoidPoolsOtherThanRequiredForSnapshot(snapshot, volume.getDataCenterId(), poolsToAvoid); + if (requiredPoolId != null) { + msg += "A volume created from this snapshot must be on the snapshot's storage, which is not suitable for it. "; + } + if (vm != null) { Pod podofVM = _entityMgr.findById(Pod.class, vm.getPodIdToDeployIn()); if (podofVM != null) { @@ -618,19 +683,13 @@ public VolumeInfo createVolumeFromSnapshot(Volume volume, Snapshot snapshot, Use boolean kvmSnapshotOnlyInPrimaryStorage = snapshotHelper.isKvmSnapshotOnlyInPrimaryStorage(snapshot, dataStoreRole, zoneId); logger.debug("Creating volume from snapshot, with dataStore role {} and on primary storage: {}", dataStoreRole, kvmSnapshotOnlyInPrimaryStorage); - boolean storageSupportSnapshotToTemplateEnabled = snapshotHelper.isStorageSupportSnapshotToTemplate(snapInfo); // storageSupportSnapshotToTemplateEnabled is true only for StorPool now [TODO: Update to check storage supports snapshot to volume (DataStoreCapabilities.CAN_CREATE_VOLUME_FROM_SNAPSHOT) - may impact other storages, or StorPool storage type only] - try { - if (!storageSupportSnapshotToTemplateEnabled) { - dataStoreRole = snapshotHelper.getDataStoreRole(snapshot); - snapInfo = snapshotFactory.getSnapshotWithRoleAndZone(snapshot.getId(), dataStoreRole, zoneId); - kvmSnapshotOnlyInPrimaryStorage = snapshotHelper.isKvmSnapshotOnlyInPrimaryStorage(snapshot, dataStoreRole); - logger.debug("Creating volume from snapshot, with dataStore role {} and on primary storage: {}", dataStoreRole, kvmSnapshotOnlyInPrimaryStorage); - snapInfo = snapshotHelper.backupSnapshotToSecondaryStorageIfNotExists(snapInfo, dataStoreRole, snapshot, kvmSnapshotOnlyInPrimaryStorage); - } - } catch (CloudRuntimeException e) { - snapshotHelper.expungeTemporarySnapshot(kvmSnapshotOnlyInPrimaryStorage, snapInfo); - throw e; - } + // true for StorPool and Linstor; PowerFlex is handled in prepareSnapshotForVolumeCreation + boolean storageSupportSnapshotToTemplateEnabled = snapshotHelper.isStorageSupportSnapshotToTemplate(snapInfo); + SnapshotForVolume snapshotForVolume = prepareSnapshotForVolumeCreation(snapshot, new SnapshotForVolume(snapInfo, dataStoreRole, kvmSnapshotOnlyInPrimaryStorage), + storageSupportSnapshotToTemplateEnabled, zoneId); + snapInfo = snapshotForVolume.snapInfo; + dataStoreRole = snapshotForVolume.dataStoreRole; + kvmSnapshotOnlyInPrimaryStorage = snapshotForVolume.kvmSnapshotOnlyInPrimaryStorage; boolean kvmIncrementalSnapshot = SnapshotManager.kvmIncrementalSnapshot.valueIn(_hostDao.findClusterIdByVolumeInfo(snapInfo.getBaseVolume())); if (kvmIncrementalSnapshot && DataStoreRole.Image.equals(dataStoreRole)) { diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 04e80212e8cc..61082432eb52 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -20,6 +20,7 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; import java.util.List; import java.util.Set; import java.lang.reflect.Field; @@ -35,7 +36,9 @@ import com.cloud.storage.clvm.ClvmPoolManager; import com.cloud.storage.ScopeType; import com.cloud.storage.DataStoreRole; +import com.cloud.storage.Snapshot; import com.cloud.storage.Storage; +import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeVO; @@ -49,12 +52,15 @@ import com.cloud.vm.VirtualMachine; import com.cloud.utils.Pair; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; +import org.apache.cloudstack.snapshot.SnapshotHelper; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; @@ -113,6 +119,11 @@ public class VolumeOrchestratorTest { @Mock private ImageStoreDao imageStoreDaoMock; + @Mock + private SnapshotHelper snapshotHelperMock; + + @Mock + private SnapshotDataFactory snapshotDataFactoryMock; @Spy @InjectMocks @@ -970,4 +981,93 @@ private Field findField(Class clazz, String fieldName) { return null; } + @Test + public void avoidPoolsOtherThanRequiredForSnapshotAvoidsEveryOtherPoolOfTheZone() { + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshotHelperMock.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(snapshot, 1L)).thenReturn(7L); + StoragePoolVO required = Mockito.mock(StoragePoolVO.class); + Mockito.when(required.getId()).thenReturn(7L); + StoragePoolVO other1 = Mockito.mock(StoragePoolVO.class); + Mockito.when(other1.getId()).thenReturn(8L); + StoragePoolVO other2 = Mockito.mock(StoragePoolVO.class); + Mockito.when(other2.getId()).thenReturn(9L); + Mockito.when(storagePoolDao.listByDataCenterId(1L)).thenReturn(List.of(other1, required, other2)); + Set avoid = new HashSet<>(); + + Assert.assertEquals(Long.valueOf(7L), volumeOrchestrator.avoidPoolsOtherThanRequiredForSnapshot(snapshot, 1L, avoid)); + Assert.assertEquals(Set.of(other1, other2), avoid); + } + + @Test + public void avoidPoolsOtherThanRequiredForSnapshotNoRequiredPool() { + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshotHelperMock.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(snapshot, 1L)).thenReturn(null); + Set avoid = new HashSet<>(); + + Assert.assertNull(volumeOrchestrator.avoidPoolsOtherThanRequiredForSnapshot(snapshot, 1L, avoid)); + Assert.assertTrue(avoid.isEmpty()); + Mockito.verify(storagePoolDao, Mockito.never()).listByDataCenterId(Mockito.anyLong()); + } + + @Test + public void prepareSnapshotForVolumeCreationStorageSupportingSnapshotToTemplateUsesTheSnapshotAsIs() { + SnapshotInfo snapInfo = Mockito.mock(SnapshotInfo.class); + VolumeOrchestrator.SnapshotForVolume current = new VolumeOrchestrator.SnapshotForVolume(snapInfo, DataStoreRole.Primary, true); + + Assert.assertSame(current, volumeOrchestrator.prepareSnapshotForVolumeCreation(Mockito.mock(Snapshot.class), current, true, 1L)); + Mockito.verifyNoInteractions(snapshotHelperMock); + } + + @Test + public void prepareSnapshotForVolumeCreationPowerFlexSnapshotIsNotStagedOnSecondary() { + SnapshotInfo snapInfo = Mockito.mock(SnapshotInfo.class); + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshotHelperMock.isSnapshotOnStorageCreatingVolumesFromIt(snapInfo)).thenReturn(true); + + VolumeOrchestrator.SnapshotForVolume result = volumeOrchestrator.prepareSnapshotForVolumeCreation(snapshot, + new VolumeOrchestrator.SnapshotForVolume(snapInfo, DataStoreRole.Primary, true), false, 1L); + + Assert.assertSame(snapInfo, result.snapInfo); + Assert.assertEquals(DataStoreRole.Primary, result.dataStoreRole); + Assert.assertFalse("no temporary secondary copy to expunge or sync", result.kvmSnapshotOnlyInPrimaryStorage); + Mockito.verify(snapshotHelperMock, Mockito.never()).backupSnapshotToSecondaryStorageIfNotExists(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.verify(snapshotHelperMock, Mockito.never()).getDataStoreRole(Mockito.any()); + } + + @Test + public void prepareSnapshotForVolumeCreationOtherStorageIsStagedAsBefore() { + SnapshotInfo snapInfo = Mockito.mock(SnapshotInfo.class); + SnapshotInfo primaryInfo = Mockito.mock(SnapshotInfo.class); + SnapshotInfo secondaryInfo = Mockito.mock(SnapshotInfo.class); + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshot.getId()).thenReturn(42L); + Mockito.when(snapshotHelperMock.isSnapshotOnStorageCreatingVolumesFromIt(snapInfo)).thenReturn(false); + Mockito.when(snapshotHelperMock.getDataStoreRole(snapshot)).thenReturn(DataStoreRole.Primary); + Mockito.when(snapshotDataFactoryMock.getSnapshotWithRoleAndZone(42L, DataStoreRole.Primary, 1L)).thenReturn(primaryInfo); + Mockito.when(snapshotHelperMock.isKvmSnapshotOnlyInPrimaryStorage(snapshot, DataStoreRole.Primary)).thenReturn(true); + Mockito.when(snapshotHelperMock.backupSnapshotToSecondaryStorageIfNotExists(primaryInfo, DataStoreRole.Primary, snapshot, true)).thenReturn(secondaryInfo); + + VolumeOrchestrator.SnapshotForVolume result = volumeOrchestrator.prepareSnapshotForVolumeCreation(snapshot, + new VolumeOrchestrator.SnapshotForVolume(snapInfo, DataStoreRole.Primary, true), false, 1L); + + Assert.assertSame(secondaryInfo, result.snapInfo); + Assert.assertTrue(result.kvmSnapshotOnlyInPrimaryStorage); + } + + @Test + public void prepareSnapshotForVolumeCreationStagingFailureExpungesTheTemporaryCopy() { + SnapshotInfo snapInfo = Mockito.mock(SnapshotInfo.class); + SnapshotInfo primaryInfo = Mockito.mock(SnapshotInfo.class); + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshot.getId()).thenReturn(42L); + Mockito.when(snapshotHelperMock.getDataStoreRole(snapshot)).thenReturn(DataStoreRole.Primary); + Mockito.when(snapshotDataFactoryMock.getSnapshotWithRoleAndZone(42L, DataStoreRole.Primary, 1L)).thenReturn(primaryInfo); + Mockito.when(snapshotHelperMock.isKvmSnapshotOnlyInPrimaryStorage(snapshot, DataStoreRole.Primary)).thenReturn(true); + Mockito.when(snapshotHelperMock.backupSnapshotToSecondaryStorageIfNotExists(primaryInfo, DataStoreRole.Primary, snapshot, true)) + .thenThrow(new CloudRuntimeException("Could not find snapshot [42] in Image storage")); + + Assert.assertThrows(CloudRuntimeException.class, () -> volumeOrchestrator.prepareSnapshotForVolumeCreation(snapshot, + new VolumeOrchestrator.SnapshotForVolume(snapInfo, DataStoreRole.Primary, true), false, 1L)); + Mockito.verify(snapshotHelperMock).expungeTemporarySnapshot(true, primaryInfo); + } } diff --git a/plugins/storage/volume/scaleio/src/main/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriver.java b/plugins/storage/volume/scaleio/src/main/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriver.java index 14cb82a4c2b3..841f148e90c0 100644 --- a/plugins/storage/volume/scaleio/src/main/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriver.java +++ b/plugins/storage/volume/scaleio/src/main/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriver.java @@ -16,6 +16,8 @@ // under the License. package org.apache.cloudstack.storage.datastore.driver; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,12 +31,15 @@ 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.DataStoreCapabilities; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; 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.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; import org.apache.cloudstack.framework.async.AsyncCompletionCallback; @@ -59,6 +64,7 @@ import org.apache.cloudstack.storage.datastore.manager.ScaleIOSDCManager; import org.apache.cloudstack.storage.datastore.manager.ScaleIOSDCManagerImpl; import org.apache.cloudstack.storage.datastore.util.ScaleIOUtil; +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.storage.volume.VolumeObject; @@ -79,14 +85,21 @@ import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.alert.AlertManager; +import com.cloud.capacity.CapacityManager; import com.cloud.configuration.Config; +import com.cloud.dc.ClusterVO; +import com.cloud.dc.dao.ClusterDao; import com.cloud.exception.OperationTimedoutException; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.org.Grouping; +import com.cloud.resource.ResourceManager; import com.cloud.server.ManagementServerImpl; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ResizeVolumePayload; +import com.cloud.storage.ScopeType; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; @@ -105,6 +118,7 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.db.GlobalLock; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; @@ -115,6 +129,12 @@ public class ScaleIOPrimaryDataStoreDriver implements PrimaryDataStoreDriver { protected Logger logger = LogManager.getLogger(getClass()); + /** + * Volume detail set by StorageSystemDataMotionStrategy when a volume is to be created from a snapshot on the same + * storage system (see {@link DataStoreCapabilities#CAN_CREATE_VOLUME_FROM_SNAPSHOT}); its value is the snapshot id. + */ + static final String CLONE_OF_SNAPSHOT = "cloneOfSnapshot"; + @Inject EndPointSelector selector; @Inject @@ -147,6 +167,14 @@ public class ScaleIOPrimaryDataStoreDriver implements PrimaryDataStoreDriver { private VolumeService volumeService; @Inject private VolumeOrchestrationService volumeMgr; + @Inject + private DataStoreManager dataStoreMgr; + @Inject + private VolumeDataFactory volumeDataFactory; + @Inject + private ResourceManager resourceMgr; + @Inject + private ClusterDao clusterDao; private ScaleIOSDCManager sdcManager; public ScaleIOPrimaryDataStoreDriver() { @@ -511,6 +539,9 @@ public CreateObjectAnswer createVolume(VolumeInfo volumeInfo, long storagePoolId Preconditions.checkArgument(storagePoolId > 0, "storagePoolId should be > 0"); Preconditions.checkArgument(storagePool != null && storagePool.getHostAddress() != null, "storagePool and host address should not be null"); + final Long snapshotIdToCopy = getSnapshotIdToCreateVolumeFrom(volumeInfo); + final SnapshotDataStoreVO snapshotStoreToCopy = snapshotIdToCopy != null ? validateSnapshotToCreateVolumeFrom(snapshotIdToCopy, volumeInfo, storagePool) : null; + try { final ScaleIOGatewayClient client = getScaleIOClient(storagePool); final String scaleIOStoragePoolId = storagePool.getPath(); @@ -544,6 +575,10 @@ public CreateObjectAnswer createVolume(VolumeInfo volumeInfo, long storagePoolId storagePool.setUsedBytes(usedBytes > capacityBytes ? capacityBytes : usedBytes); storagePoolDao.update(storagePoolId, storagePool); + if (snapshotStoreToCopy != null) { + copySnapshotToNewVolume(snapshotIdToCopy, snapshotStoreToCopy, volume, storagePool, client); + } + CreateObjectAnswer answer = new CreateObjectAnswer(createdObject.getTO()); // if volume needs to be set up with encryption, do it now if it's not a root disk (which gets done during template copy) @@ -585,6 +620,365 @@ public CreateObjectAnswer createVolume(VolumeInfo volumeInfo, long storagePoolId } } + /** + * Returns the id of the snapshot whose data the new volume must contain, if the volume is being created from a + * volume snapshot (the "cloneOfSnapshot" contract of {@link DataStoreCapabilities#CAN_CREATE_VOLUME_FROM_SNAPSHOT}). + */ + protected Long getSnapshotIdToCreateVolumeFrom(VolumeInfo volumeInfo) { + VolumeDetailVO detail = volumeDetailsDao.findDetail(volumeInfo.getId(), CLONE_OF_SNAPSHOT); + if (detail == null || StringUtils.isBlank(detail.getValue())) { + return null; + } + return Long.parseLong(detail.getValue()); + } + + /** + * Checks, before anything is created on PowerFlex, that the volume can be created from the snapshot: the snapshot is on + * this pool, and neither the snapshot's volume nor the new volume is encrypted. + * @return the snapshot's primary storage reference + */ + protected SnapshotDataStoreVO validateSnapshotToCreateVolumeFrom(long snapshotId, VolumeInfo newVolume, StoragePoolVO storagePool) { + SnapshotDataStoreVO snapshotStore = snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(snapshotId, DataStoreRole.Primary); + if (snapshotStore == null || StringUtils.isBlank(snapshotStore.getInstallPath())) { + throw new CloudRuntimeException(String.format("Unable to find the PowerFlex snapshot [id: %d] on primary storage", snapshotId)); + } + if (snapshotStore.getDataStoreId() != storagePool.getId()) { + throw new CloudRuntimeException(String.format("The PowerFlex snapshot [id: %d] is on another storage pool than the new volume %s;" + + " creating a volume from a PowerFlex snapshot is supported on the same storage pool only", snapshotId, newVolume)); + } + if (anyVolumeRequiresEncryption(newVolume)) { + throw new CloudRuntimeException(String.format("Creating an encrypted volume from a PowerFlex volume snapshot is not supported, volume: %s", newVolume)); + } + SnapshotVO snapshot = snapshotDao.findById(snapshotId); + VolumeVO snapshotBaseVolume = snapshot != null ? volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId()) : null; + if (snapshotBaseVolume == null) { + throw new CloudRuntimeException(String.format("Unable to find the volume of the PowerFlex snapshot [id: %d] to check its encryption", snapshotId)); + } + if (snapshotBaseVolume.getPassphraseId() != null || snapshotBaseVolume.getKmsKeyId() != null) { + throw new CloudRuntimeException(String.format("Creating a volume from a snapshot of an encrypted PowerFlex volume is not supported, snapshot id: %d", snapshotId)); + } + return snapshotStore; + } + + /** + * Copies the data of a PowerFlex volume snapshot into a newly created PowerFlex volume, through a KVM host. + *

+ * A PowerFlex snapshot belongs to the volume tree (VTree) of its source volume, and so would a snapshot of it. A + * volume created from a snapshot must be independent of that VTree (its own lifecycle, migration and VTree + * limits), so the data is copied: both are mapped to the host's SDC and the agent copies the snapshot block device + * to the new volume's block device. The source is always passed as RAW: a PowerFlex snapshot is a raw block device, + * whatever format the volume record says. + *

+ * Copies from the same snapshot through the same SDC are serialized, so one copy does not unmap the snapshot while + * another copy is reading it; the snapshot is unmapped afterwards only if this copy mapped it. + * On any failure the new PowerFlex volume is removed and a {@link CloudRuntimeException} is thrown. + */ + protected void copySnapshotToNewVolume(long snapshotId, SnapshotDataStoreVO snapshotStore, VolumeVO newVolume, StoragePoolVO storagePool, ScaleIOGatewayClient client) { + String error; + try { + SnapshotCopy copy = new SnapshotCopy(); + copy.snapshot = snapshotDao.findById(snapshotId); + copy.snapshotStore = snapshotStore; + copy.newVolume = newVolume; + copy.storagePool = storagePool; + copy.client = client; + copy.dataStore = dataStoreMgr.getDataStore(storagePool.getId(), DataStoreRole.Primary); + copy.newVolumeInfo = volumeDataFactory.getVolume(newVolume.getId(), copy.dataStore); + copy.waitSeconds = NumbersUtil.parseInt(configDao.getValue(Config.CopyVolumeWait.key()), Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); + error = copySnapshot(copy); + } catch (Exception e) { + logger.debug("Copying the PowerFlex snapshot [id: {}] failed", snapshotId, e); + error = describe(e); + } + + if (error != null) { + deleteVolumeAfterFailedCopy(client, newVolume, storagePool.getId()); + throw new CloudRuntimeException(String.format("Failed to copy the PowerFlex snapshot [id: %d] to the volume %s: %s", snapshotId, newVolume, error)); + } + logger.info("Copied PowerFlex snapshot [id: {}] to the new volume {}", snapshotId, newVolume); + } + + /** What a copy from a snapshot to a new volume works on. */ + protected static class SnapshotCopy { + SnapshotVO snapshot; + SnapshotDataStoreVO snapshotStore; + VolumeVO newVolume; + VolumeInfo newVolumeInfo; + StoragePoolVO storagePool; + DataStore dataStore; + ScaleIOGatewayClient client; + int waitSeconds; + } + + /** At most this many hosts are tried for a copy (a host may have no usable SDC). */ + private static final int MAX_COPY_HOST_ATTEMPTS = 3; + /** How long to wait for another copy from the same snapshot on a host before trying the next host. */ + private static final int COPY_LOCK_WAIT_BEFORE_NEXT_HOST_SECONDS = 60; + + /** + * @return null when the copy succeeded, else the reason it failed (never blank) + */ + private String copySnapshot(SnapshotCopy copy) { + final List hosts = findHostsForCopy(copy.newVolumeInfo, copy.storagePool, copy.dataStore); + if (hosts.isEmpty()) { + return "no Up and Enabled KVM host available for the storage pool to copy the snapshot"; + } + final String snapshotVolumeId = ScaleIOUtil.getVolumePath(copy.snapshotStore.getInstallPath()); + String error = null; + for (int i = 0; i < hosts.size(); i++) { + final Host host = hosts.get(i); + // taken before the SDC is prepared, so another copy from this snapshot on this host can't release the SDC in between; + // wait briefly when another host can be tried, else as long as a copy may take + int lockWait = i < hosts.size() - 1 ? Math.min(COPY_LOCK_WAIT_BEFORE_NEXT_HOST_SECONDS, copy.waitSeconds) : copy.waitSeconds; + GlobalLock lock = acquireSnapshotCopyLock(snapshotVolumeId, host.getId(), lockWait); + if (lock == null) { + error = "timed out waiting for another copy from the same snapshot on the host " + host; + continue; + } + try { + String sdcId; + try { + sdcId = prepareSdcOnHost(host, copy.dataStore); + } catch (Exception e) { + logger.warn("Unable to prepare the SDC on host {} to copy the PowerFlex snapshot: {}", host, describe(e)); + logger.debug("Preparing the SDC on host {} failed", host, e); + sdcId = null; + } + if (StringUtils.isBlank(sdcId)) { + error = "no SDC connected on the host " + host; + unprepareSdcAfterFailedPrepare(host, copy.dataStore); + continue; + } + logger.info("Copying PowerFlex snapshot [path: {}] to the new volume {} [path: {}] on host {}", copy.snapshotStore.getInstallPath(), copy.newVolume, + copy.newVolume.getPath(), host); + CopyAttempt attempt = mapCopyAndUnmap(copy, host, sdcId); + if (attempt.error == null || attempt.copyStarted) { + return attempt.error; + } + // failed on this host before any data was copied (e.g. a mapping): another host may do + error = attempt.error; + } finally { + releaseSnapshotCopyLock(lock); + } + } + return error; + } + + /** + * Hosts to copy on, best first: a host the pool is attached to, then Up and Enabled KVM hosts in the pool's scope that + * can connect to it (storage access groups, enabled clusters not excluded from storage operations). With on-demand SDC + * connection a host's attachment to the pool is removed when nothing is mapped to its SDC, so the copy can't rely on it. + */ + protected List findHostsForCopy(VolumeInfo newVolumeInfo, StoragePoolVO storagePool, DataStore dataStore) { + List hosts = new ArrayList<>(); + EndPoint ep = selector.select(newVolumeInfo); + if (ep != null) { + HostVO attached = hostDao.findById(ep.getId()); + if (attached != null) { + hosts.add(attached); + } + } + List candidates = resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, storagePool.getDataCenterId(), Hypervisor.HypervisorType.KVM); + if (CollectionUtils.isNotEmpty(candidates)) { + List eligible = new ArrayList<>(); + for (HostVO h : candidates) { + if (!Hypervisor.HypervisorType.KVM.equals(h.getHypervisorType()) || h.getClusterId() == null) { + continue; + } + if (ScopeType.CLUSTER.equals(storagePool.getScope()) && !h.getClusterId().equals(storagePool.getClusterId())) { + continue; + } + if (hosts.stream().anyMatch(x -> x.getId() == h.getId()) || !isClusterUsableForStorageOperations(h.getClusterId())) { + continue; + } + eligible.add(h); + } + Collections.shuffle(eligible); + hosts.addAll(eligible); + } + return hosts.size() > MAX_COPY_HOST_ATTEMPTS ? new ArrayList<>(hosts.subList(0, MAX_COPY_HOST_ATTEMPTS)) : hosts; + } + + private boolean isClusterUsableForStorageOperations(long clusterId) { + ClusterVO cluster = clusterDao.findById(clusterId); + return cluster != null && Grouping.AllocationState.Enabled.equals(cluster.getAllocationState()) + && !Boolean.TRUE.equals(CapacityManager.StorageOperationsExcludeCluster.valueIn(clusterId)); + } + + protected EndPoint getEndPoint(Host host) { + return RemoteHostEndPoint.getHypervisorHostEndPoint(host); + } + + /** The outcome of a copy attempt on one host. */ + private static class CopyAttempt { + final String error; + final boolean copyStarted; + + CopyAttempt(String error, boolean copyStarted) { + this.error = error; + this.copyStarted = copyStarted; + } + } + + /** + * Maps the snapshot and the new volume to the SDC, copies the snapshot to the new volume and unmaps them. + * @return the attempt: no error when the copy succeeded, else the reason it failed (never blank) + */ + private CopyAttempt mapCopyAndUnmap(SnapshotCopy copy, Host host, String sdcId) { + final String snapshotPath = copy.snapshotStore.getInstallPath(); + final String snapshotVolumeId = ScaleIOUtil.getVolumePath(snapshotPath); + final String newVolumePath = copy.newVolume.getPath(); + boolean snapshotMappedHere = false; + boolean newVolumeMapped = false; + boolean copyStarted = false; + try { + // the snapshot may already be mapped to this SDC for another operation; leave such a mapping in place + if (!copy.client.isVolumeMappedToSdc(snapshotVolumeId, sdcId)) { + if (!copy.client.mapVolumeToSdc(snapshotVolumeId, sdcId)) { + return new CopyAttempt("failed to map the snapshot volume " + snapshotPath + " to the SDC " + sdcId, false); + } + snapshotMappedHere = true; + } + if (!copy.client.mapVolumeToSdc(ScaleIOUtil.getVolumePath(newVolumePath), sdcId)) { + return new CopyAttempt("failed to map the volume " + newVolumePath + " to the SDC " + sdcId, false); + } + newVolumeMapped = true; + + VolumeObjectTO srcTO = new VolumeObjectTO(); + srcTO.setPath(snapshotPath); + srcTO.setUuid(copy.snapshot != null ? copy.snapshot.getUuid() : null); + srcTO.setName(copy.snapshot != null ? copy.snapshot.getName() : snapshotPath); + srcTO.setSize(copy.snapshotStore.getSize() > 0 ? copy.snapshotStore.getSize() : copy.newVolume.getSize()); + // A PowerFlex snapshot is a raw block device, whatever format the volume record says + srcTO.setFormat(Storage.ImageFormat.RAW); + srcTO.setDataStore(getPrimaryDataStoreTOForManagedVolume(copy.storagePool, snapshotPath, srcTO.getName(), srcTO.getSize())); + + VolumeObjectTO destTO = (VolumeObjectTO) copy.newVolumeInfo.getTO(); + destTO.setPath(newVolumePath); + destTO.setFormat(Storage.ImageFormat.RAW); + destTO.setDataStore(getPrimaryDataStoreTOForManagedVolume(copy.storagePool, newVolumePath, copy.newVolume.getName(), copy.newVolume.getSize())); + + CopyCommand cmd = new CopyCommand(srcTO, destTO, copy.waitSeconds, VirtualMachineManager.ExecuteInSequence.value()); + copyStarted = true; + Answer answer = getEndPoint(host).sendMessage(cmd); + if (answer == null) { + return new CopyAttempt("no answer from the host " + host, true); + } + if (!answer.getResult()) { + return new CopyAttempt(StringUtils.defaultIfBlank(answer.getDetails(), "the copy failed on the host " + host), true); + } + return new CopyAttempt(null, true); + } catch (Exception e) { + return new CopyAttempt(describe(e), copyStarted); + } finally { + if (snapshotMappedHere) { + revokeVolumeAccess(snapshotPath, host, copy.dataStore); + } + if (newVolumeMapped) { + revokeVolumeAccess(newVolumePath, host, copy.dataStore); + } + if (!snapshotMappedHere && !newVolumeMapped) { + unprepareSdcIfUnused(host, copy.dataStore, sdcId, copy.client); + } + } + } + + /** After a prepare that did not connect the SDC: let the SDC manager release what it can (it only unprepares an SDC with nothing mapped). */ + protected void unprepareSdcAfterFailedPrepare(Host host, DataStore dataStore) { + try { + sdcManager = ComponentContext.inject(sdcManager); + sdcManager.unprepareSDC(host, dataStore); + } catch (Exception e) { + logger.debug("Unable to release the SDC on host {} after a failed prepare: {}", host, describe(e)); + } + } + + /** Releases the host's SDC when nothing is mapped to it, as revokeAccess does, after a copy that mapped nothing. */ + protected void unprepareSdcIfUnused(Host host, DataStore dataStore, String sdcId, ScaleIOGatewayClient client) { + try { + if (client.listVolumesMappedToSdc(sdcId).isEmpty()) { + sdcManager = ComponentContext.inject(sdcManager); + sdcManager.unprepareSDC(host, dataStore); + } + } catch (Exception e) { + logger.warn("Unable to release the SDC {} on host {}: {}", sdcId, host, describe(e)); + } + } + + private static String describe(Exception e) { + return StringUtils.defaultIfBlank(e.getMessage(), e.toString()); + } + + /** + * Serializes copies from the same PowerFlex snapshot on the same host (across management servers), so one such copy does + * not unmap the snapshot, or release the host's SDC, while another one is preparing or reading it. Other operations on + * the host's SDC (for example an Instance stop) are not serialized with it, as for grantAccess and revokeAccess. + * @return the held lock, or null if it was not acquired in time + */ + protected GlobalLock acquireSnapshotCopyLock(String snapshotVolumeId, long hostId, int timeoutSeconds) { + GlobalLock lock = GlobalLock.getInternLock(String.format("powerflex.snapshot.copy.%s.%d", snapshotVolumeId, hostId)); + if (!lock.lock(timeoutSeconds)) { + lock.releaseRef(); + return null; + } + return lock; + } + + protected void releaseSnapshotCopyLock(GlobalLock lock) { + lock.unlock(); + lock.releaseRef(); + } + + protected String prepareSdcOnHost(Host host, DataStore dataStore) { + sdcManager = ComponentContext.inject(sdcManager); + return sdcManager.prepareSDC(host, dataStore); + } + + protected PrimaryDataStoreTO getPrimaryDataStoreTOForManagedVolume(StoragePoolVO storagePool, String volumePath, String volumeName, long volumeSize) { + PrimaryDataStore store = (PrimaryDataStore) dataStoreMgr.getDataStore(storagePool.getId(), DataStoreRole.Primary); + Map details = new HashMap<>(); + details.put(PrimaryDataStore.MANAGED, Boolean.TRUE.toString()); + details.put(PrimaryDataStore.STORAGE_HOST, storagePool.getHostAddress()); + details.put(PrimaryDataStore.STORAGE_PORT, String.valueOf(storagePool.getPort())); + details.put(PrimaryDataStore.MANAGED_STORE_TARGET, volumePath); + details.put(PrimaryDataStore.MANAGED_STORE_TARGET_ROOT_VOLUME, volumeName); + details.put(PrimaryDataStore.VOLUME_SIZE, String.valueOf(volumeSize)); + details.put(StorageManager.STORAGE_POOL_DISK_WAIT.toString(), String.valueOf(StorageManager.STORAGE_POOL_DISK_WAIT.valueIn(storagePool.getId()))); + store.setDetails(details); + return new PrimaryDataStoreTO(store); + } + + protected void deleteVolumeAfterFailedCopy(ScaleIOGatewayClient client, VolumeVO volume, long storagePoolId) { + final String volumeId = ScaleIOUtil.getVolumePath(volume.getPath()); + String failure = null; + try { + if (!client.deleteVolume(volumeId)) { + failure = "the gateway did not remove it"; + } + } catch (Exception e) { + failure = describe(e); + } + if (failure != null) { + String msg = String.format("Failed to remove the PowerFlex volume %s of %s after a failed copy from a snapshot (%s); remove it manually", volumeId, volume, failure); + logger.warn(msg); + StoragePoolVO pool = storagePoolDao.findById(storagePoolId); + if (pool != null) { + alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC, pool.getDataCenterId(), pool.getPodId(), "PowerFlex volume left after a failed copy: " + volumeId, msg); + } + return; + } + volume.setPath(null); + volume.set_iScsiName(null); + volume.setFolder(null); + volumeDao.update(volume.getId(), volume); + StoragePoolVO storagePool = storagePoolDao.findById(storagePoolId); + if (storagePool != null) { + long usedBytes = storagePool.getUsedBytes() - volume.getSize(); + storagePool.setUsedBytes(usedBytes < 0 ? 0 : usedBytes); + storagePoolDao.update(storagePoolId, storagePool); + } + } + private String createTemplateVolume(TemplateInfo templateInfo, long storagePoolId) { logger.debug("Creating PowerFlex template volume"); @@ -693,6 +1087,15 @@ public void deleteAsync(DataStore dataStore, DataObject dataObject, AsyncComplet throw new CloudRuntimeException(errMsg); } + if (dataObject.getType() == DataObjectType.VOLUME && StringUtils.isBlank(scaleIOVolumePath)) { + // e.g. a volume whose creation from a snapshot failed: its PowerFlex volume was already removed + logger.debug("deleteAsync - volume {} has no PowerFlex volume, nothing to delete", dataObject); + if (callback != null) { + callback.complete(new CommandResult()); + } + return; + } + try { String scaleIOVolumeId = ScaleIOUtil.getVolumePath(scaleIOVolumePath); final ScaleIOGatewayClient client = getScaleIOClient(storagePool); diff --git a/plugins/storage/volume/scaleio/src/test/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriverVolumeFromSnapshotTest.java b/plugins/storage/volume/scaleio/src/test/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriverVolumeFromSnapshotTest.java new file mode 100644 index 000000000000..73a5dffbfac0 --- /dev/null +++ b/plugins/storage/volume/scaleio/src/test/java/org/apache/cloudstack/storage/datastore/driver/ScaleIOPrimaryDataStoreDriverVolumeFromSnapshotTest.java @@ -0,0 +1,742 @@ +// 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.storage.datastore.driver; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +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.PrimaryDataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.framework.async.AsyncCompletionCallback; +import org.apache.cloudstack.storage.command.CommandResult; +import org.apache.cloudstack.storage.command.CopyCommand; +import org.apache.cloudstack.storage.datastore.api.Volume; +import org.apache.cloudstack.storage.datastore.client.ScaleIOGatewayClient; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.datastore.manager.ScaleIOSDCManager; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.storage.volume.VolumeObject; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.to.DataObjectType; +import com.cloud.alert.AlertManager; +import com.cloud.configuration.Config; +import com.cloud.dc.ClusterVO; +import com.cloud.dc.dao.ClusterDao; +import com.cloud.host.HostVO; +import com.cloud.host.dao.HostDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.org.Grouping; +import com.cloud.resource.ResourceManager; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.ScopeType; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.Storage; +import com.cloud.storage.VolumeDetailVO; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.dao.VolumeDetailsDao; +import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.exception.CloudRuntimeException; + +@RunWith(MockitoJUnitRunner.class) +public class ScaleIOPrimaryDataStoreDriverVolumeFromSnapshotTest { + + private static final long POOL_ID = 7L; + private static final long SNAPSHOT_ID = 42L; + private static final long NEW_VOLUME_ID = 100L; + private static final long BASE_VOLUME_ID = 99L; + private static final long HOST_ID = 5L; + private static final long NEW_VOLUME_SIZE = 16L << 30; + private static final String SDC_ID = "c70c930300000001"; + private static final String SNAPSHOT_VOLUME_ID = "e44cfc4c00000002"; + private static final String SNAPSHOT_PATH = SNAPSHOT_VOLUME_ID + ":snap-42-abcd-sim"; + private static final String NEW_VOLUME_PF_ID = "e44cfc4c00000003"; + private static final String NEW_VOLUME_PATH = NEW_VOLUME_PF_ID + ":vol-100-abcd-sim"; + + @Spy + @InjectMocks + ScaleIOPrimaryDataStoreDriver driver = new ScaleIOPrimaryDataStoreDriver(); + + @Mock + VolumeDetailsDao volumeDetailsDao; + @Mock + SnapshotDataStoreDao snapshotDataStoreDao; + @Mock + SnapshotDao snapshotDao; + @Mock + VolumeDao volumeDao; + @Mock + PrimaryDataStoreDao storagePoolDao; + @Mock + DataStoreManager dataStoreMgr; + @Mock + VolumeDataFactory volumeDataFactory; + @Mock + EndPointSelector selector; + @Mock + HostDao hostDao; + @Mock + ConfigurationDao configDao; + @Mock + ResourceManager resourceMgr; + @Mock + ClusterDao clusterDao; + @Mock + ScaleIOSDCManager sdcManager; + @Mock + AlertManager alertMgr; + + @Mock + ScaleIOGatewayClient client; + @Mock + StoragePoolVO storagePool; + @Mock + VolumeVO newVolume; + @Mock + VolumeVO baseVolume; + @Mock + SnapshotDataStoreVO snapshotStore; + @Mock + PrimaryDataStore dataStore; + @Mock + VolumeInfo newVolumeInfo; + @Mock + EndPoint endPoint; + @Mock + HostVO host; + @Mock + GlobalLock lock; + + @Before + public void setUp() { + lenient().when(storagePool.getId()).thenReturn(POOL_ID); + lenient().when(newVolume.getId()).thenReturn(NEW_VOLUME_ID); + lenient().when(newVolume.getPath()).thenReturn(NEW_VOLUME_PATH); + lenient().when(newVolume.getSize()).thenReturn(NEW_VOLUME_SIZE); + lenient().when(snapshotStore.getInstallPath()).thenReturn(SNAPSHOT_PATH); + lenient().when(snapshotStore.getDataStoreId()).thenReturn(POOL_ID); + lenient().when(snapshotStore.getSize()).thenReturn(16L << 30); + lenient().when(snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(SNAPSHOT_ID, DataStoreRole.Primary)).thenReturn(snapshotStore); + + SnapshotVO snapshot = mock(SnapshotVO.class); + lenient().when(snapshot.getVolumeId()).thenReturn(BASE_VOLUME_ID); + lenient().when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshot); + // what KVM usually records for PowerFlex data volumes, although the PowerFlex device holds raw data + lenient().when(baseVolume.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + lenient().when(volumeDao.findByIdIncludingRemoved(BASE_VOLUME_ID)).thenReturn(baseVolume); + // unencrypted unless a test says otherwise (Mockito would return 0L for these Long getters) + lenient().when(baseVolume.getPassphraseId()).thenReturn(null); + lenient().when(baseVolume.getKmsKeyId()).thenReturn(null); + lenient().when(newVolumeInfo.getPassphraseId()).thenReturn(null); + lenient().when(newVolumeInfo.getKmsKeyId()).thenReturn(null); + + lenient().when(dataStoreMgr.getDataStore(POOL_ID, DataStoreRole.Primary)).thenReturn(dataStore); + lenient().when(volumeDataFactory.getVolume(NEW_VOLUME_ID, dataStore)).thenReturn(newVolumeInfo); + lenient().when(newVolumeInfo.getTO()).thenReturn(new VolumeObjectTO()); + lenient().when(endPoint.getId()).thenReturn(HOST_ID); + lenient().when(hostDao.findById(HOST_ID)).thenReturn(host); + lenient().when(storagePoolDao.findById(POOL_ID)).thenReturn(storagePool); + } + + private void stubCopyPath() { + doReturn(List.of(host)).when(driver).findHostsForCopy(newVolumeInfo, storagePool, dataStore); + lenient().when(host.getId()).thenReturn(HOST_ID); + lenient().doReturn(endPoint).when(driver).getEndPoint(host); + lenient().doReturn(lock).when(driver).acquireSnapshotCopyLock(eq(SNAPSHOT_VOLUME_ID), eq(HOST_ID), anyInt()); + lenient().doNothing().when(driver).unprepareSdcIfUnused(any(), any(), anyString(), any()); + lenient().doNothing().when(driver).unprepareSdcAfterFailedPrepare(any(), any()); + lenient().doNothing().when(driver).releaseSnapshotCopyLock(lock); + lenient().doReturn(SDC_ID).when(driver).prepareSdcOnHost(host, dataStore); + lenient().doReturn(mock(PrimaryDataStoreTO.class)).when(driver).getPrimaryDataStoreTOForManagedVolume(any(), anyString(), any(), anyLong()); + lenient().doNothing().when(driver).revokeVolumeAccess(anyString(), any(), any()); + lenient().when(client.isVolumeMappedToSdc(SNAPSHOT_VOLUME_ID, SDC_ID)).thenReturn(false); + lenient().when(client.mapVolumeToSdc(anyString(), eq(SDC_ID))).thenReturn(true); + lenient().when(client.deleteVolume(NEW_VOLUME_PF_ID)).thenReturn(true); + } + + private void copy() { + driver.copySnapshotToNewVolume(SNAPSHOT_ID, snapshotStore, newVolume, storagePool, client); + } + + private void assertCopyFailsAndNewVolumeIsRemoved() { + Assert.assertThrows(CloudRuntimeException.class, this::copy); + verify(client).deleteVolume(NEW_VOLUME_PF_ID); + } + + // ---- getSnapshotIdToCreateVolumeFrom + + @Test + public void getSnapshotIdToCreateVolumeFromWithoutDetail() { + VolumeInfo volumeInfo = mock(VolumeInfo.class); + when(volumeInfo.getId()).thenReturn(NEW_VOLUME_ID); + Assert.assertNull(driver.getSnapshotIdToCreateVolumeFrom(volumeInfo)); + } + + @Test + public void getSnapshotIdToCreateVolumeFromWithCloneOfSnapshotDetail() { + VolumeInfo volumeInfo = mock(VolumeInfo.class); + when(volumeInfo.getId()).thenReturn(NEW_VOLUME_ID); + VolumeDetailVO detail = mock(VolumeDetailVO.class); + when(detail.getValue()).thenReturn(String.valueOf(SNAPSHOT_ID)); + when(volumeDetailsDao.findDetail(NEW_VOLUME_ID, ScaleIOPrimaryDataStoreDriver.CLONE_OF_SNAPSHOT)).thenReturn(detail); + Assert.assertEquals(Long.valueOf(SNAPSHOT_ID), driver.getSnapshotIdToCreateVolumeFrom(volumeInfo)); + } + + // ---- validateSnapshotToCreateVolumeFrom + + @Test + public void validateSnapshotToCreateVolumeFromReturnsTheSnapshotStore() { + Assert.assertSame(snapshotStore, driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromSnapshotNotOnPrimary() { + when(snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(SNAPSHOT_ID, DataStoreRole.Primary)).thenReturn(null); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromSnapshotOnAnotherPool() { + when(snapshotStore.getDataStoreId()).thenReturn(POOL_ID + 1); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromEncryptedNewVolume() { + doReturn(true).when(driver).anyVolumeRequiresEncryption(newVolumeInfo); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromEncryptedSourceWithPassphrase() { + when(baseVolume.getPassphraseId()).thenReturn(3L); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromRefusesWhenTheSnapshotVolumeIsGone() { + when(volumeDao.findByIdIncludingRemoved(BASE_VOLUME_ID)).thenReturn(null); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + @Test + public void validateSnapshotToCreateVolumeFromEncryptedSourceWithKmsKey() { + when(baseVolume.getKmsKeyId()).thenReturn(4L); + Assert.assertThrows(CloudRuntimeException.class, () -> driver.validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, newVolumeInfo, storagePool)); + } + + // ---- copySnapshotToNewVolume + + @Test + public void copyMapsCopiesAsRawAndUnmapsUnderTheSnapshotLock() { + stubCopyPath(); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, true, null)); + + copy(); + + ArgumentCaptor cmdCaptor = ArgumentCaptor.forClass(CopyCommand.class); + InOrder order = inOrder(client, endPoint, driver); + order.verify(driver).acquireSnapshotCopyLock(eq(SNAPSHOT_VOLUME_ID), eq(HOST_ID), anyInt()); + order.verify(driver).prepareSdcOnHost(host, dataStore); + order.verify(client).mapVolumeToSdc(SNAPSHOT_VOLUME_ID, SDC_ID); + order.verify(client).mapVolumeToSdc(NEW_VOLUME_PF_ID, SDC_ID); + order.verify(endPoint).sendMessage(cmdCaptor.capture()); + order.verify(driver).revokeVolumeAccess(SNAPSHOT_PATH, host, dataStore); + order.verify(driver).revokeVolumeAccess(NEW_VOLUME_PATH, host, dataStore); + order.verify(driver).releaseSnapshotCopyLock(lock); + + CopyCommand cmd = cmdCaptor.getValue(); + Assert.assertEquals(SNAPSHOT_PATH, cmd.getSrcTO().getPath()); + Assert.assertEquals("the source must be RAW even when the volume record says QCOW2", + Storage.ImageFormat.RAW, ((VolumeObjectTO) cmd.getSrcTO()).getFormat()); + Assert.assertEquals(NEW_VOLUME_PATH, cmd.getDestTO().getPath()); + Assert.assertEquals(Storage.ImageFormat.RAW, ((VolumeObjectTO) cmd.getDestTO()).getFormat()); + // the agent finds each device through the managed store target of its TO + verify(driver).getPrimaryDataStoreTOForManagedVolume(eq(storagePool), eq(SNAPSHOT_PATH), any(), anyLong()); + verify(driver).getPrimaryDataStoreTOForManagedVolume(eq(storagePool), eq(NEW_VOLUME_PATH), any(), eq(NEW_VOLUME_SIZE)); + verify(client, never()).deleteVolume(anyString()); + verify(storagePoolDao, never()).update(anyLong(), any()); + } + + @Test + public void copyFailedAnswerWithoutDetailsIsAFailure() { + stubCopyPath(); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, false, null)); + assertCopyFailsAndNewVolumeIsRemoved(); + } + + @Test + public void copyExceptionWithoutMessageIsAFailure() { + stubCopyPath(); + when(endPoint.sendMessage(any(CopyCommand.class))).thenThrow(new RuntimeException()); + assertCopyFailsAndNewVolumeIsRemoved(); + verify(driver).revokeVolumeAccess(NEW_VOLUME_PATH, host, dataStore); + } + + @Test + public void copyLeavesAnExistingSnapshotMappingInPlace() { + stubCopyPath(); + when(client.isVolumeMappedToSdc(SNAPSHOT_VOLUME_ID, SDC_ID)).thenReturn(true); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, true, null)); + + copy(); + + verify(client, never()).mapVolumeToSdc(SNAPSHOT_VOLUME_ID, SDC_ID); + verify(driver, never()).revokeVolumeAccess(eq(SNAPSHOT_PATH), any(), any()); + verify(driver).revokeVolumeAccess(NEW_VOLUME_PATH, host, dataStore); + } + + @Test + public void copyFailureRemovesNewVolumeUnmapsAndReleasesUsedBytes() { + stubCopyPath(); + when(storagePool.getUsedBytes()).thenReturn(100L << 30); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, false, "qemu-img convert failed")); + + CloudRuntimeException e = Assert.assertThrows(CloudRuntimeException.class, this::copy); + + Assert.assertTrue(e.getMessage(), e.getMessage().contains("qemu-img convert failed")); + verify(driver).revokeVolumeAccess(SNAPSHOT_PATH, host, dataStore); + verify(driver).revokeVolumeAccess(NEW_VOLUME_PATH, host, dataStore); + verify(driver).releaseSnapshotCopyLock(lock); + verify(client).deleteVolume(NEW_VOLUME_PF_ID); + verify(storagePool).setUsedBytes((100L << 30) - NEW_VOLUME_SIZE); + verify(storagePoolDao).update(POOL_ID, storagePool); + } + + @Test + public void copyWithoutAnswerRemovesNewVolume() { + stubCopyPath(); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(null); + assertCopyFailsAndNewVolumeIsRemoved(); + } + + @Test + public void copyMapFailureOfTheNewVolumeUnmapsOnlyTheSnapshot() { + stubCopyPath(); + when(client.mapVolumeToSdc(NEW_VOLUME_PF_ID, SDC_ID)).thenReturn(false); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(endPoint, never()).sendMessage(any()); + verify(driver).revokeVolumeAccess(SNAPSHOT_PATH, host, dataStore); + verify(driver, never()).revokeVolumeAccess(eq(NEW_VOLUME_PATH), any(), any()); + } + + @Test + public void copyNoSdcOnTheOnlyHostRemovesNewVolume() { + stubCopyPath(); + doReturn(null).when(driver).prepareSdcOnHost(host, dataStore); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(driver).releaseSnapshotCopyLock(lock); + verify(driver).unprepareSdcAfterFailedPrepare(host, dataStore); + verify(client, never()).mapVolumeToSdc(anyString(), anyString()); + verify(driver, never()).revokeVolumeAccess(anyString(), any(), any()); + } + + @Test + public void copyMovesToTheNextHostWhenAHostHasNoSdc() { + stubCopyPath(); + HostVO noSdcHost = mock(HostVO.class); + when(noSdcHost.getId()).thenReturn(HOST_ID + 1); + doReturn(List.of(noSdcHost, host)).when(driver).findHostsForCopy(newVolumeInfo, storagePool, dataStore); + GlobalLock otherLock = mock(GlobalLock.class); + doReturn(otherLock).when(driver).acquireSnapshotCopyLock(eq(SNAPSHOT_VOLUME_ID), eq(HOST_ID + 1), anyInt()); + doNothing().when(driver).releaseSnapshotCopyLock(otherLock); + doThrow(new RuntimeException("connection limit reached")).when(driver).prepareSdcOnHost(noSdcHost, dataStore); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, true, null)); + + copy(); + + verify(driver).releaseSnapshotCopyLock(otherLock); + verify(client, never()).deleteVolume(anyString()); + verify(driver).revokeVolumeAccess(NEW_VOLUME_PATH, host, dataStore); + // a short wait on a host when another host can be tried, the full copy wait on the last one + verify(driver).acquireSnapshotCopyLock(SNAPSHOT_VOLUME_ID, HOST_ID + 1, 60); + verify(driver).acquireSnapshotCopyLock(SNAPSHOT_VOLUME_ID, HOST_ID, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue())); + } + + // ---- SDC release + + @Test + public void unprepareSdcIfUnusedReleasesAnIdleSdc() { + when(client.listVolumesMappedToSdc(SDC_ID)).thenReturn(List.of()); + try (MockedStatic context = mockStatic(ComponentContext.class)) { + context.when(() -> ComponentContext.inject(any(ScaleIOSDCManager.class))).thenReturn(sdcManager); + driver.unprepareSdcIfUnused(host, dataStore, SDC_ID, client); + } + verify(sdcManager).unprepareSDC(host, dataStore); + } + + @Test + public void unprepareSdcIfUnusedKeepsAnSdcInUse() { + when(client.listVolumesMappedToSdc(SDC_ID)).thenReturn(List.of(mock(Volume.class))); + driver.unprepareSdcIfUnused(host, dataStore, SDC_ID, client); + verify(sdcManager, never()).unprepareSDC(any(), any()); + } + + @Test + public void copyMovesToTheNextHostWhenAMappingFailsBeforeTheCopy() { + stubCopyPath(); + HostVO firstHost = mock(HostVO.class); + when(firstHost.getId()).thenReturn(HOST_ID + 1); + doReturn(List.of(firstHost, host)).when(driver).findHostsForCopy(newVolumeInfo, storagePool, dataStore); + GlobalLock firstLock = mock(GlobalLock.class); + doReturn(firstLock).when(driver).acquireSnapshotCopyLock(eq(SNAPSHOT_VOLUME_ID), eq(HOST_ID + 1), anyInt()); + doNothing().when(driver).releaseSnapshotCopyLock(firstLock); + doReturn("sdc-of-first-host").when(driver).prepareSdcOnHost(firstHost, dataStore); + when(client.mapVolumeToSdc(anyString(), eq("sdc-of-first-host"))).thenReturn(false); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, true, null)); + + copy(); + + verify(endPoint).sendMessage(any(CopyCommand.class)); + verify(client, never()).deleteVolume(anyString()); + verify(driver).releaseSnapshotCopyLock(firstLock); + } + + @Test + public void copyFailingAfterTheCopyStartedIsNotRetriedOnAnotherHost() { + stubCopyPath(); + HostVO secondHost = mock(HostVO.class); + doReturn(List.of(host, secondHost)).when(driver).findHostsForCopy(newVolumeInfo, storagePool, dataStore); + when(endPoint.sendMessage(any(CopyCommand.class))).thenReturn(new Answer(null, false, "qemu-img convert failed")); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(driver, never()).prepareSdcOnHost(secondHost, dataStore); + } + + @Test + public void copyNoHostRemovesNewVolume() { + stubCopyPath(); + doReturn(List.of()).when(driver).findHostsForCopy(newVolumeInfo, storagePool, dataStore); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(client, never()).mapVolumeToSdc(anyString(), anyString()); + } + + @Test + public void copyLockTimeoutRemovesNewVolumeWithoutPreparingTheSdc() { + stubCopyPath(); + doReturn(null).when(driver).acquireSnapshotCopyLock(eq(SNAPSHOT_VOLUME_ID), eq(HOST_ID), anyInt()); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(driver, never()).prepareSdcOnHost(any(), any()); + verify(client, never()).mapVolumeToSdc(anyString(), anyString()); + verify(driver, never()).releaseSnapshotCopyLock(any()); + } + + @Test + public void copySnapshotMapFailureReleasesTheIdleSdc() { + stubCopyPath(); + when(client.mapVolumeToSdc(SNAPSHOT_VOLUME_ID, SDC_ID)).thenReturn(false); + + assertCopyFailsAndNewVolumeIsRemoved(); + verify(driver).unprepareSdcIfUnused(host, dataStore, SDC_ID, client); + verify(driver, never()).revokeVolumeAccess(anyString(), any(), any()); + } + + // ---- findHostsForCopy + + private HostVO kvmHost(long id, long clusterId) { + HostVO h = mock(HostVO.class); + lenient().when(h.getId()).thenReturn(id); + lenient().when(h.getClusterId()).thenReturn(clusterId); + lenient().when(h.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + return h; + } + + private void enabledCluster(long clusterId, boolean enabled) { + ClusterVO cluster = mock(ClusterVO.class); + lenient().when(cluster.getAllocationState()).thenReturn(enabled ? Grouping.AllocationState.Enabled : Grouping.AllocationState.Disabled); + lenient().when(clusterDao.findById(clusterId)).thenReturn(cluster); + } + + @Test + public void findHostsForCopyPutsTheAttachedHostFirst() { + when(selector.select(newVolumeInfo)).thenReturn(endPoint); + HostVO attached = kvmHost(HOST_ID, 3L); + when(hostDao.findById(HOST_ID)).thenReturn(attached); + HostVO other = kvmHost(6L, 3L); + enabledCluster(3L, true); + when(storagePool.getScope()).thenReturn(ScopeType.ZONE); + when(storagePool.getDataCenterId()).thenReturn(1L); + when(resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, 1L, Hypervisor.HypervisorType.KVM)).thenReturn(List.of(other, attached)); + + Assert.assertEquals(List.of(attached, other), driver.findHostsForCopy(newVolumeInfo, storagePool, dataStore)); + } + + @Test + public void findHostsForCopyWithoutAttachedHostUsesEligibleHostsOfTheZone() { + when(selector.select(newVolumeInfo)).thenReturn(null); + when(storagePool.getScope()).thenReturn(ScopeType.ZONE); + when(storagePool.getDataCenterId()).thenReturn(1L); + HostVO vmwareHost = kvmHost(8L, 3L); + when(vmwareHost.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.VMware); + HostVO kvm = kvmHost(6L, 3L); + HostVO inDisabledCluster = kvmHost(7L, 4L); + enabledCluster(3L, true); + enabledCluster(4L, false); + when(resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, 1L, Hypervisor.HypervisorType.KVM)).thenReturn(List.of(vmwareHost, kvm, inDisabledCluster)); + + Assert.assertEquals(List.of(kvm), driver.findHostsForCopy(newVolumeInfo, storagePool, dataStore)); + } + + @Test + public void findHostsForCopyClusterPoolKeepsOnlyHostsOfThePoolsCluster() { + when(selector.select(newVolumeInfo)).thenReturn(null); + when(storagePool.getScope()).thenReturn(ScopeType.CLUSTER); + when(storagePool.getClusterId()).thenReturn(3L); + when(storagePool.getDataCenterId()).thenReturn(1L); + HostVO inCluster = kvmHost(6L, 3L); + HostVO otherCluster = kvmHost(7L, 4L); + enabledCluster(3L, true); + enabledCluster(4L, true); + when(resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, 1L, Hypervisor.HypervisorType.KVM)).thenReturn(List.of(otherCluster, inCluster)); + + Assert.assertEquals(List.of(inCluster), driver.findHostsForCopy(newVolumeInfo, storagePool, dataStore)); + } + + @Test + public void findHostsForCopyTriesAtMostThreeHosts() { + when(selector.select(newVolumeInfo)).thenReturn(null); + when(storagePool.getScope()).thenReturn(ScopeType.ZONE); + when(storagePool.getDataCenterId()).thenReturn(1L); + enabledCluster(3L, true); + List four = List.of(kvmHost(11L, 3L), kvmHost(12L, 3L), kvmHost(13L, 3L), kvmHost(14L, 3L)); + when(resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(dataStore, 1L, Hypervisor.HypervisorType.KVM)).thenReturn(four); + + Assert.assertEquals(3, driver.findHostsForCopy(newVolumeInfo, storagePool, dataStore).size()); + } + + @Test + public void findHostsForCopyNoHost() { + when(selector.select(newVolumeInfo)).thenReturn(null); + when(resourceMgr.getEligibleUpAndEnabledHostsInZoneForStorageConnection(any(), anyLong(), any())).thenReturn(List.of()); + Assert.assertTrue(driver.findHostsForCopy(newVolumeInfo, storagePool, dataStore).isEmpty()); + } + + // ---- deleteAsync + + @Test + public void deleteAsyncOfAVolumeWithoutPowerFlexVolumeSucceedsWithoutTouchingThePool() { + when(dataStore.getId()).thenReturn(POOL_ID); + when(storagePool.getHostAddress()).thenReturn("192.0.2.10"); + VolumeInfo failed = mock(VolumeInfo.class); + when(failed.getType()).thenReturn(DataObjectType.VOLUME); + when(failed.getPath()).thenReturn(null); + @SuppressWarnings("unchecked") + AsyncCompletionCallback callback = mock(AsyncCompletionCallback.class); + + driver.deleteAsync(dataStore, failed, callback); + + ArgumentCaptor result = ArgumentCaptor.forClass(CommandResult.class); + verify(callback).complete(result.capture()); + Assert.assertTrue(result.getValue().isSuccess()); + verify(client, never()).deleteVolume(any()); + verify(storagePoolDao, never()).update(anyLong(), any()); + } + + // ---- snapshot copy lock + + @Test + public void acquireSnapshotCopyLockTimeoutReleasesTheReference() { + try (MockedStatic globalLock = mockStatic(GlobalLock.class)) { + globalLock.when(() -> GlobalLock.getInternLock("powerflex.snapshot.copy." + SNAPSHOT_VOLUME_ID + "." + HOST_ID)).thenReturn(lock); + when(lock.lock(30)).thenReturn(false); + + Assert.assertNull(driver.acquireSnapshotCopyLock(SNAPSHOT_VOLUME_ID, HOST_ID, 30)); + verify(lock).releaseRef(); + verify(lock, never()).unlock(); + } + } + + @Test + public void acquireAndReleaseSnapshotCopyLock() { + try (MockedStatic globalLock = mockStatic(GlobalLock.class)) { + globalLock.when(() -> GlobalLock.getInternLock("powerflex.snapshot.copy." + SNAPSHOT_VOLUME_ID + "." + HOST_ID)).thenReturn(lock); + when(lock.lock(30)).thenReturn(true); + + Assert.assertSame(lock, driver.acquireSnapshotCopyLock(SNAPSHOT_VOLUME_ID, HOST_ID, 30)); + verify(lock, never()).releaseRef(); + driver.releaseSnapshotCopyLock(lock); + InOrder order = inOrder(lock); + order.verify(lock).unlock(); + order.verify(lock).releaseRef(); + } + } + + @Test + public void copyUnexpectedExceptionBeforeTheCopyRemovesNewVolume() { + when(dataStoreMgr.getDataStore(POOL_ID, DataStoreRole.Primary)).thenThrow(new RuntimeException("db down")); + when(client.deleteVolume(NEW_VOLUME_PF_ID)).thenReturn(true); + + assertCopyFailsAndNewVolumeIsRemoved(); + } + + // ---- deleteVolumeAfterFailedCopy + + @Test + public void deleteVolumeAfterFailedCopyKeepsUsedBytesAndAlertsWhenRemovalFails() { + when(client.deleteVolume(NEW_VOLUME_PF_ID)).thenReturn(false); + when(storagePool.getDataCenterId()).thenReturn(1L); + when(storagePool.getPodId()).thenReturn(2L); + driver.deleteVolumeAfterFailedCopy(client, newVolume, POOL_ID); + verify(storagePoolDao, never()).update(anyLong(), any()); + verify(newVolume, never()).setPath(null); + verify(alertMgr).sendAlert(eq(AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC), eq(1L), eq(2L), anyString(), anyString()); + } + + @Test + public void deleteVolumeAfterFailedCopyReReadsThePoolAndNeverGoesNegative() { + when(client.deleteVolume(NEW_VOLUME_PF_ID)).thenReturn(true); + when(storagePool.getUsedBytes()).thenReturn(1L << 30); + driver.deleteVolumeAfterFailedCopy(client, newVolume, POOL_ID); + verify(storagePoolDao).findById(POOL_ID); + verify(storagePool).setUsedBytes(0L); + verify(storagePoolDao).update(POOL_ID, storagePool); + // the failed volume row no longer points at the removed PowerFlex volume + verify(newVolume).setPath(null); + verify(newVolume).set_iScsiName(null); + verify(newVolume).setFolder(null); + verify(volumeDao).update(NEW_VOLUME_ID, newVolume); + } + + // ---- getPrimaryDataStoreTOForManagedVolume + + @Test + public void primaryDataStoreTOForManagedVolumeTargetsTheVolume() { + when(storagePool.getHostAddress()).thenReturn("192.0.2.10"); + when(storagePool.getPort()).thenReturn(443); + driver.getPrimaryDataStoreTOForManagedVolume(storagePool, SNAPSHOT_PATH, "snap", 16L << 30); + + @SuppressWarnings("unchecked") + ArgumentCaptor> details = ArgumentCaptor.forClass(Map.class); + verify(dataStore).setDetails(details.capture()); + Assert.assertEquals(SNAPSHOT_PATH, details.getValue().get(PrimaryDataStore.MANAGED_STORE_TARGET)); + Assert.assertEquals("true", details.getValue().get(PrimaryDataStore.MANAGED)); + Assert.assertEquals("192.0.2.10", details.getValue().get(PrimaryDataStore.STORAGE_HOST)); + Assert.assertEquals(String.valueOf(16L << 30), details.getValue().get(PrimaryDataStore.VOLUME_SIZE)); + } + + // ---- createVolume + + private VolumeInfo stubCreateVolume(Long cloneOfSnapshot) { + VolumeInfo volumeInfo = mock(VolumeInfo.class); + when(volumeInfo.getId()).thenReturn(NEW_VOLUME_ID); + lenient().when(volumeInfo.getSize()).thenReturn(10L << 30); + if (cloneOfSnapshot != null) { + VolumeDetailVO detail = mock(VolumeDetailVO.class); + when(detail.getValue()).thenReturn(String.valueOf(cloneOfSnapshot)); + when(volumeDetailsDao.findDetail(NEW_VOLUME_ID, ScaleIOPrimaryDataStoreDriver.CLONE_OF_SNAPSHOT)).thenReturn(detail); + } + when(storagePool.getHostAddress()).thenReturn("192.0.2.10"); + lenient().when(storagePool.getUuid()).thenReturn("a1b2c3d4-0000-0000-0000-000000000000"); + lenient().when(storagePool.getPath()).thenReturn("pool-id-1"); + lenient().when(storagePool.getCapacityBytes()).thenReturn(1L << 40); + lenient().doReturn(client).when(driver).getScaleIOClient(storagePool); + lenient().doReturn(false).when(driver).anyVolumeRequiresEncryption(volumeInfo); + Volume created = mock(Volume.class); + lenient().when(created.getId()).thenReturn(NEW_VOLUME_PF_ID); + lenient().when(created.getSizeInKb()).thenReturn(16L * 1024 * 1024); + lenient().when(client.createVolume(anyString(), eq("pool-id-1"), eq(10), any())).thenReturn(created); + lenient().when(volumeDao.findById(NEW_VOLUME_ID)).thenReturn(newVolume); + return volumeInfo; + } + + @Test + public void createVolumeFromSnapshotCopiesTheSnapshotIntoTheNewVolume() { + VolumeInfo volumeInfo = stubCreateVolume(SNAPSHOT_ID); + doNothing().when(driver).copySnapshotToNewVolume(anyLong(), any(), any(), any(), any()); + try (MockedStatic volumeObjectMock = mockStatic(VolumeObject.class)) { + VolumeObject createdObject = mock(VolumeObject.class); + volumeObjectMock.when(() -> VolumeObject.getVolumeObject(any(), any())).thenReturn(createdObject); + + driver.createVolume(volumeInfo, POOL_ID, false, null); + + InOrder order = inOrder(client, createdObject, driver); + order.verify(driver).validateSnapshotToCreateVolumeFrom(SNAPSHOT_ID, volumeInfo, storagePool); + order.verify(client).createVolume(anyString(), eq("pool-id-1"), eq(10), any()); + order.verify(createdObject).update(); + order.verify(driver).copySnapshotToNewVolume(SNAPSHOT_ID, snapshotStore, newVolume, storagePool, client); + } + } + + @Test + public void createVolumeFromSnapshotRefusedBeforeAnythingIsCreatedOnPowerFlex() { + VolumeInfo volumeInfo = stubCreateVolume(SNAPSHOT_ID); + when(snapshotStore.getDataStoreId()).thenReturn(POOL_ID + 1); + + Assert.assertThrows(CloudRuntimeException.class, () -> driver.createVolume(volumeInfo, POOL_ID, false, null)); + verify(client, never()).createVolume(anyString(), anyString(), anyInt(), any()); + verify(driver, never()).copySnapshotToNewVolume(anyLong(), any(), any(), any(), any()); + } + + @Test + public void createVolumeWithoutSnapshotDoesNotCopy() { + VolumeInfo volumeInfo = stubCreateVolume(null); + try (MockedStatic volumeObjectMock = mockStatic(VolumeObject.class)) { + volumeObjectMock.when(() -> VolumeObject.getVolumeObject(any(), any())).thenReturn(mock(VolumeObject.class)); + + driver.createVolume(volumeInfo, POOL_ID, false, null); + + verify(client).createVolume(anyString(), eq("pool-id-1"), eq(10), any()); + verify(driver, never()).validateSnapshotToCreateVolumeFrom(anyLong(), any(), any()); + verify(driver, never()).copySnapshotToNewVolume(anyLong(), any(), any(), any(), any()); + } + } +} diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java index 11b24a9beef6..8ea270d8f029 100644 --- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java @@ -107,8 +107,6 @@ import org.apache.cloudstack.storage.command.TemplateOrVolumePostUploadCommand; import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; @@ -289,8 +287,6 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Inject private SnapshotPolicyDetailsDao snapshotPolicyDetailsDao; @Inject - private SnapshotDataStoreDao _snapshotDataStoreDao; - @Inject private ServiceOfferingDetailsDao _serviceOfferingDetailsDao; @Inject private UserVmDao _userVmDao; @@ -920,14 +916,6 @@ public VolumeVO allocVolume(long ownerId, Long zoneId, Long diskOfferingId, Long throw new InvalidParameterValueException(String.format("Snapshot %s is not in %s state yet and can't be used for volume creation", snapshotCheck, Snapshot.State.BackedUp)); } - SnapshotDataStoreVO snapshotStore = _snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(snapshotId, DataStoreRole.Primary); - if (snapshotStore != null) { - StoragePoolVO storagePoolVO = _storagePoolDao.findById(snapshotStore.getDataStoreId()); - if (storagePoolVO.getPoolType() == Storage.StoragePoolType.PowerFlex) { - throw new InvalidParameterValueException("Create volume from snapshot is not supported for PowerFlex volume snapshots"); - } - } - parentVolume = _volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId()); // Don't support creating templates from encrypted volumes (yet) @@ -959,6 +947,8 @@ public VolumeVO allocVolume(long ownerId, Long zoneId, Long diskOfferingId, Long // check snapshot permissions _accountMgr.checkAccess(caller, null, true, snapshotCheck); + snapshotHelper.validateVolumeFromSnapshotOnStorageCreatingVolumes(snapshotCheck, zoneId, kmsKeyId != null || diskOffering.getEncrypt()); + // one step operation - create volume in VM's cluster and attach it // to the VM if (vmId != null) { diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index 689b748379f7..ae21661613c7 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -4525,6 +4525,9 @@ private UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffe } kmsManager.checkKmsKeyForVolumeEncryption(owner, rootDiskKmsKeyId, zone.getId()); + if (snapshot != null) { + snapshotHelper.validateVolumeFromSnapshotOnStorageCreatingVolumes(snapshot, zone.getId(), rootDiskKmsKeyId != null || rootDiskOffering.getEncrypt()); + } if (dataDiskInfoList != null) { for (VmDiskInfo diskInfo : dataDiskInfoList) { kmsManager.checkKmsKeyForVolumeEncryption(owner, diskInfo.getKmsKeyId(), zone.getId()); diff --git a/server/src/main/java/org/apache/cloudstack/snapshot/SnapshotHelper.java b/server/src/main/java/org/apache/cloudstack/snapshot/SnapshotHelper.java index 98efe7d1c988..a3ac6faf579b 100644 --- a/server/src/main/java/org/apache/cloudstack/snapshot/SnapshotHelper.java +++ b/server/src/main/java/org/apache/cloudstack/snapshot/SnapshotHelper.java @@ -30,6 +30,7 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.utils.exception.CloudRuntimeException; @@ -94,11 +95,20 @@ public class SnapshotHelper { @Inject protected SnapshotJoinDao snapshotJoinDao; + @Inject + protected VolumeDao volumeDao; + protected boolean backupSnapshotAfterTakingSnapshot = SnapshotInfo.BackupSnapshotAfterTakingSnapshot.value(); protected final Set storagePoolTypesToValidateWithBackupSnapshotAfterTakingSnapshot = new HashSet<>(Arrays.asList(StoragePoolType.RBD, StoragePoolType.PowerFlex)); + /** + * Storage pool types whose driver creates a volume from a volume snapshot kept on the pool by itself (see + * {@link DataStoreCapabilities#CAN_CREATE_VOLUME_FROM_SNAPSHOT}), so the snapshot never has to be copied to secondary storage first. + */ + protected final Set storagePoolTypesCreatingVolumesFromPrimarySnapshots = new HashSet<>(Arrays.asList(StoragePoolType.PowerFlex)); + /** * If the snapshot is a backup from a KVM snapshot that should be kept only in primary storage, expunges it from secondary storage. * @param snapInfo the snapshot info to delete. @@ -153,6 +163,68 @@ public void expungeTemporarySnapshot(boolean kvmSnapshotOnlyInPrimaryStorage, Sn snapshotDataStoreDao.expungeReferenceBySnapshotIdAndDataStoreRole(snapInfo.getId(), storeId, DataStoreRole.Image); } + /** + * Verifies if the snapshot info is on a primary storage that creates volumes from its own snapshots (today PowerFlex + * only, see {@link #storagePoolTypesCreatingVolumesFromPrimarySnapshots}). Such a snapshot is not staged on + * secondary storage to create a volume from it. + * @return true if the snapshot info is on primary storage of such a type, else false. + */ + public boolean isSnapshotOnStorageCreatingVolumesFromIt(SnapshotInfo snapInfo) { + if (snapInfo == null || snapInfo.getDataStore() == null || !DataStoreRole.Primary.equals(snapInfo.getDataStore().getRole())) { + return false; + } + StoragePoolVO storagePoolVO = primaryDataStoreDao.findById(snapInfo.getDataStore().getId()); + return storagePoolVO != null && storagePoolTypesCreatingVolumesFromPrimarySnapshots.contains(storagePoolVO.getPoolType()); + } + + /** + * Returns the primary storage pool on which a volume created from the snapshot in the zone must be allocated: the + * snapshot's own pool in that zone, when that pool creates volumes from its own snapshots (see + * {@link #storagePoolTypesCreatingVolumesFromPrimarySnapshots}). + * @return the pool id, or null when any suitable pool can be used. + */ + public Long getStoragePoolIdRequiredToCreateVolumeFromSnapshot(Snapshot snapshot, long zoneId) { + StoragePoolVO storagePoolVO = getStoragePoolCreatingVolumesFromSnapshot(snapshot); + return storagePoolVO != null && storagePoolVO.getDataCenterId() == zoneId ? storagePoolVO.getId() : null; + } + + /** + * A volume created from a snapshot on a primary storage pool that creates volumes from its own snapshots (see + * {@link #storagePoolTypesCreatingVolumesFromPrimarySnapshots}) is created on that pool, with the snapshot's data copied + * in: it must be in the pool's zone, and neither it nor the snapshot's volume can be encrypted. Used by createVolume and + * by deploying an Instance from a snapshot, before anything is allocated. + * @throws InvalidParameterValueException if the volume can't be created from the snapshot that way + */ + public void validateVolumeFromSnapshotOnStorageCreatingVolumes(Snapshot snapshot, long zoneId, boolean encryptionRequested) { + StoragePoolVO storagePoolVO = getStoragePoolCreatingVolumesFromSnapshot(snapshot); + if (storagePoolVO == null) { + return; + } + if (storagePoolVO.getDataCenterId() != zoneId) { + throw new InvalidParameterValueException(String.format("A volume from snapshot %s can only be created in the zone of the snapshot's storage", snapshot.getUuid())); + } + if (encryptionRequested) { + throw new InvalidParameterValueException(String.format("Creating an encrypted volume from snapshot %s is not supported on the snapshot's storage", snapshot.getUuid())); + } + VolumeVO snapshotVolume = volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId()); + if (snapshotVolume == null || snapshotVolume.getPassphraseId() != null || snapshotVolume.getKmsKeyId() != null) { + throw new InvalidParameterValueException(String.format("Creating a volume from snapshot %s of an encrypted or unknown volume is not supported on the snapshot's storage", + snapshot.getUuid())); + } + } + + private StoragePoolVO getStoragePoolCreatingVolumesFromSnapshot(Snapshot snapshot) { + SnapshotDataStoreVO snapshotStore = snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(snapshot.getId(), DataStoreRole.Primary); + if (snapshotStore == null) { + return null; + } + StoragePoolVO storagePoolVO = primaryDataStoreDao.findById(snapshotStore.getDataStoreId()); + if (storagePoolVO == null || !storagePoolTypesCreatingVolumesFromPrimarySnapshots.contains(storagePoolVO.getPoolType())) { + return null; + } + return storagePoolVO; + } + public boolean isStorageSupportSnapshotToTemplate(SnapshotInfo snapInfo) { if (DataStoreRole.Primary.equals(snapInfo.getDataStore().getRole())) { Map capabilities = snapInfo.getDataStore().getDriver().getCapabilities(); diff --git a/server/src/test/java/org/apache/cloudstack/snapshot/SnapshotHelperTest.java b/server/src/test/java/org/apache/cloudstack/snapshot/SnapshotHelperTest.java index ac254ed1c5ec..71b6fbae5442 100644 --- a/server/src/test/java/org/apache/cloudstack/snapshot/SnapshotHelperTest.java +++ b/server/src/test/java/org/apache/cloudstack/snapshot/SnapshotHelperTest.java @@ -20,11 +20,15 @@ package org.apache.cloudstack.snapshot; import com.cloud.api.query.dao.SnapshotJoinDao; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.hypervisor.Hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.DataStoreRole; +import com.cloud.storage.Snapshot; +import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver; @@ -34,8 +38,10 @@ import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy; import org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -86,6 +92,10 @@ public class SnapshotHelperTest { VolumeVO volumeVoMock; @Mock SnapshotJoinDao snapshotJoinDao; + @Mock + PrimaryDataStoreDao primaryDataStoreDaoMock; + @Mock + VolumeDao volumeDaoMock; List dataStoreRoles = Arrays.asList(DataStoreRole.values()); @@ -98,6 +108,136 @@ public void init() { snapshotHelperSpy.snapshotDao = snapshotDaoMock; snapshotHelperSpy.dataStorageManager = dataStoreManager; snapshotHelperSpy.snapshotJoinDao = snapshotJoinDao; + snapshotHelperSpy.primaryDataStoreDao = primaryDataStoreDaoMock; + snapshotHelperSpy.volumeDao = volumeDaoMock; + } + + private void mockSnapshotOnStore(DataStoreRole role, StoragePoolType poolType) { + DataStore store = Mockito.mock(DataStore.class); + Mockito.lenient().when(store.getRole()).thenReturn(role); + Mockito.lenient().when(store.getId()).thenReturn(7L); + Mockito.when(snapshotInfoMock.getDataStore()).thenReturn(store); + StoragePoolVO pool = Mockito.mock(StoragePoolVO.class); + Mockito.lenient().when(pool.getPoolType()).thenReturn(poolType); + Mockito.lenient().when(primaryDataStoreDaoMock.findById(7L)).thenReturn(pool); + } + + @Test + public void isSnapshotOnStorageCreatingVolumesFromItPowerFlexSnapshotOnPrimary() { + mockSnapshotOnStore(DataStoreRole.Primary, StoragePoolType.PowerFlex); + Assert.assertTrue(snapshotHelperSpy.isSnapshotOnStorageCreatingVolumesFromIt(snapshotInfoMock)); + } + + @Test + public void isSnapshotOnStorageCreatingVolumesFromItSnapshotOnSecondary() { + mockSnapshotOnStore(DataStoreRole.Image, StoragePoolType.PowerFlex); + Assert.assertFalse(snapshotHelperSpy.isSnapshotOnStorageCreatingVolumesFromIt(snapshotInfoMock)); + } + + @Test + public void isSnapshotOnStorageCreatingVolumesFromItOtherPoolTypes() { + for (StoragePoolType type : StoragePoolType.values()) { + if (type == StoragePoolType.PowerFlex) { + continue; + } + mockSnapshotOnStore(DataStoreRole.Primary, type); + Assert.assertFalse(type.toString(), snapshotHelperSpy.isSnapshotOnStorageCreatingVolumesFromIt(snapshotInfoMock)); + } + } + + @Test + public void isSnapshotOnStorageCreatingVolumesFromItNullSnapshot() { + Assert.assertFalse(snapshotHelperSpy.isSnapshotOnStorageCreatingVolumesFromIt(null)); + } + + private Snapshot mockSnapshotStoreRef(Long poolId, StoragePoolType poolType) { + return mockSnapshotStoreRef(poolId, poolType, 1L); + } + + private Snapshot mockSnapshotStoreRef(Long poolId, StoragePoolType poolType, long poolZoneId) { + Snapshot snapshot = Mockito.mock(Snapshot.class); + Mockito.when(snapshot.getId()).thenReturn(42L); + if (poolId == null) { + Mockito.when(snapshotDataStoreDaoMock.findOneBySnapshotAndDatastoreRole(42L, DataStoreRole.Primary)).thenReturn(null); + return snapshot; + } + SnapshotDataStoreVO ref = Mockito.mock(SnapshotDataStoreVO.class); + Mockito.when(ref.getDataStoreId()).thenReturn(poolId); + Mockito.when(snapshotDataStoreDaoMock.findOneBySnapshotAndDatastoreRole(42L, DataStoreRole.Primary)).thenReturn(ref); + StoragePoolVO pool = Mockito.mock(StoragePoolVO.class); + Mockito.when(pool.getPoolType()).thenReturn(poolType); + Mockito.lenient().when(pool.getId()).thenReturn(poolId); + Mockito.lenient().when(pool.getDataCenterId()).thenReturn(poolZoneId); + Mockito.when(primaryDataStoreDaoMock.findById(poolId)).thenReturn(pool); + return snapshot; + } + + @Test + public void getStoragePoolIdRequiredToCreateVolumeFromSnapshotPowerFlex() { + Assert.assertEquals(Long.valueOf(7L), snapshotHelperSpy.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex), 1L)); + } + + @Test + public void getStoragePoolIdRequiredToCreateVolumeFromSnapshotOtherPoolType() { + Assert.assertNull(snapshotHelperSpy.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(mockSnapshotStoreRef(7L, StoragePoolType.RBD), 1L)); + } + + @Test + public void getStoragePoolIdRequiredToCreateVolumeFromSnapshotPoolInAnotherZone() { + Assert.assertNull(snapshotHelperSpy.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex, 2L), 1L)); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateVolumeFromSnapshotOnStorageCreatingVolumesRefusesAnotherZone() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex, 2L), 1L, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateVolumeFromSnapshotOnStorageCreatingVolumesRefusesEncryption() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex, 1L), 1L, true); + } + + private Snapshot mockSnapshotOfVolume(Long passphraseId, Long kmsKeyId) { + Snapshot snapshot = mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex, 1L); + Mockito.when(snapshot.getVolumeId()).thenReturn(99L); + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.lenient().when(volume.getPassphraseId()).thenReturn(passphraseId); + Mockito.lenient().when(volume.getKmsKeyId()).thenReturn(kmsKeyId); + Mockito.when(volumeDaoMock.findByIdIncludingRemoved(99L)).thenReturn(volume); + return snapshot; + } + + @Test + public void validateVolumeFromSnapshotOnStorageCreatingVolumesAllowsAnUnencryptedVolumeInTheZone() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotOfVolume(null, null), 1L, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateVolumeFromSnapshotOnStorageCreatingVolumesRefusesASnapshotOfAnEncryptedVolume() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotOfVolume(3L, null), 1L, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateVolumeFromSnapshotOnStorageCreatingVolumesRefusesASnapshotOfAKmsEncryptedVolume() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotOfVolume(null, 4L), 1L, false); + } + + @Test(expected = InvalidParameterValueException.class) + public void validateVolumeFromSnapshotOnStorageCreatingVolumesRefusesWhenTheSnapshotVolumeIsGone() { + Snapshot snapshot = mockSnapshotStoreRef(7L, StoragePoolType.PowerFlex, 1L); + Mockito.when(snapshot.getVolumeId()).thenReturn(99L); + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(snapshot, 1L, false); + } + + @Test + public void validateVolumeFromSnapshotOnStorageCreatingVolumesIgnoresOtherStorage() { + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotStoreRef(7L, StoragePoolType.RBD, 2L), 1L, true); + snapshotHelperSpy.validateVolumeFromSnapshotOnStorageCreatingVolumes(mockSnapshotStoreRef(null, null), 1L, true); + } + + @Test + public void getStoragePoolIdRequiredToCreateVolumeFromSnapshotNotOnPrimary() { + Assert.assertNull(snapshotHelperSpy.getStoragePoolIdRequiredToCreateVolumeFromSnapshot(mockSnapshotStoreRef(null, null), 1L)); } @Test diff --git a/test/integration/plugins/scaleio/test_scaleio_volumes.py b/test/integration/plugins/scaleio/test_scaleio_volumes.py index d6ba569f90f0..f966ddf7c96d 100644 --- a/test/integration/plugins/scaleio/test_scaleio_volumes.py +++ b/test/integration/plugins/scaleio/test_scaleio_volumes.py @@ -44,6 +44,9 @@ # Only KVM hypervisor is supported for PowerFlex/ScaleIO storage pool # KVM host(s) with ScaleIO Data Client (SDC) installed and connected to Metadata Manager (MDM) # +# For test_13 (data check of a volume created from a snapshot), the test must reach the Instance over SSH (a shared or +# basic network routed to the test host) with the template credentials set in TestData.virtualMachineSsh +# # For volume migration tests, additional storage pool(s) are required # One PowerFlex/ScaleIO storage pool on the same ScaleIO storage cluster/instance # One PowerFlex/ScaleIO storage pool on different ScaleIO storage cluster/instance @@ -84,6 +87,7 @@ class TestData(): virtualMachine = "virtualmachine" virtualMachine2 = "virtualmachine2" virtualMachine3 = "virtualmachine3" + virtualMachineSsh = "virtualmachinessh" virtualMachine4 = "virtualmachine4" volume_1 = "volume_1" volume_2 = "volume_2" @@ -139,6 +143,14 @@ def __init__(self): "name": "TestVM2", "displayname": "Test VM 2" }, + # an Instance the test can log in to (set the template's credentials), used to check volume data + TestData.virtualMachineSsh: { + "name": "TestVMSsh", + "displayname": "Test VM SSH", + "username": "root", + "password": "password", + "ssh_port": 22 + }, TestData.virtualMachine3: { "name": "TestVM3", "displayname": "Test VM 3" @@ -1388,6 +1400,146 @@ def test_12_migrate_volume_to_distinct_instance_pool(self): test_virtual_machine.delete(self.apiClient, True) + # md5 of 16 MiB of zeros, and of empty input + _md5_16_mib_of_zeros = "2c7ab85a893283e98c931e9511add182" + _md5_of_nothing = "d41d8cd98f00b204e9800998ecf8427e" + + @attr(tags=['basic'], required_hardware=True) + def test_13_create_volume_from_snapshot_keeps_the_data(self): + '''Create a volume from a volume snapshot and check it holds the data written before the snapshot''' + + test_virtual_machine = VirtualMachine.create( + self.apiClient, + self.testdata[TestData.virtualMachineSsh], + accountid=self.account.name, + zoneid=self.zone.id, + serviceofferingid=self.compute_offering.id, + templateid=self.template.id, + domainid=self.domain.id, + startvm=True + ) + resources = [test_virtual_machine] + try: + time.sleep(90) + try: + ssh = test_virtual_machine.get_ssh_client() + except Exception as e: + self.skipTest("The Instance is not reachable over SSH (see the prerequisites): %s" % e) + + source_volume = Volume.create( + self.apiClient, + self.testdata[TestData.volume_1], + account=self.account.name, + domainid=self.domain.id, + zoneid=self.zone.id, + diskofferingid=self.disk_offering.id + ) + resources.append(source_volume) + disks_before = self._disks(ssh) + test_virtual_machine.attach_volume(self.apiClient, source_volume) + time.sleep(10) + source_device = "/dev/" + self._new_disk(ssh, disks_before) + + # data before the snapshot + self._run(ssh, "dd if=/dev/urandom of=%s bs=1M count=16 oflag=direct" % source_device) + checksum_at_snapshot = self._md5_16_mib(ssh, source_device) + self.assertNotIn(checksum_at_snapshot, (self._md5_16_mib_of_zeros, self._md5_of_nothing), "The test data was not written") + + snapshot = Snapshot.create(self.apiClient, source_volume.id, account=self.account.name, domainid=self.domain.id) + resources.append(snapshot) + + # data after the snapshot, which the new volume must not have + self._run(ssh, "dd if=/dev/zero of=%s bs=1M count=16 oflag=direct" % source_device) + self.assertEqual(self._md5_16_mib(ssh, source_device), self._md5_16_mib_of_zeros, "The source volume was not overwritten") + + new_volume = Volume.create_from_snapshot( + self.apiClient, + snapshot.id, + {"diskname": "vol-from-snapshot"}, + account=self.account.name, + domainid=self.domain.id, + zoneid=self.zone.id + ) + resources.append(new_volume) + new_volume = self._get_volume(new_volume.id) + self.assertEqual(new_volume.state.lower(), "ready", "The volume created from the snapshot is not Ready") + self.assertEqual(new_volume.storageid, self._get_volume(source_volume.id).storageid, + "The volume created from the snapshot is not on the snapshot's storage pool") + + disks_before = self._disks(ssh) + test_virtual_machine.attach_volume(self.apiClient, new_volume) + time.sleep(10) + new_device = "/dev/" + self._new_disk(ssh, disks_before) + + self.assertEqual(self._md5_16_mib(ssh, new_device), checksum_at_snapshot, + "The volume created from the snapshot does not hold the data written before the snapshot") + + test_virtual_machine.detach_volume(self.apiClient, new_volume) + test_virtual_machine.detach_volume(self.apiClient, source_volume) + finally: + # newest first: the new volume and the snapshot before the source volume, the Instance last + self.cleanup.extend(reversed(resources)) + + @attr(tags=['basic'], required_hardware=False) + def test_14_deploy_vm_from_root_volume_snapshot(self): + '''Deploy an Instance from a snapshot of a ROOT volume on PowerFlex''' + + source_vm = VirtualMachine.create( + self.apiClient, + self.testdata[TestData.virtualMachine2], + accountid=self.account.name, + zoneid=self.zone.id, + serviceofferingid=self.compute_offering.id, + templateid=self.template.id, + domainid=self.domain.id, + startvm=True + ) + resources = [source_vm] + try: + root_volume = list_volumes(self.apiClient, virtualmachineid=source_vm.id, type="ROOT", listall=True)[0] + snapshot = Snapshot.create(self.apiClient, root_volume.id, account=self.account.name, domainid=self.domain.id) + resources.append(snapshot) + + new_vm = VirtualMachine.create( + self.apiClient, + self.testdata[TestData.virtualMachine3], + accountid=self.account.name, + zoneid=self.zone.id, + serviceofferingid=self.compute_offering.id, + snapshotid=snapshot.id, + domainid=self.domain.id, + startvm=True + ) + resources.append(new_vm) + + self.assertEqual(self._get_vm(new_vm.id).state.lower(), "running", TestScaleIOVolumes._vm_not_in_running_state_err_msg) + new_root = list_volumes(self.apiClient, virtualmachineid=new_vm.id, type="ROOT", listall=True)[0] + self.assertEqual(new_root.storageid, root_volume.storageid, "The new ROOT volume is not on the snapshot's storage pool") + self.assertNotEqual(new_root.id, root_volume.id, "The new Instance must have its own ROOT volume") + finally: + self.cleanup.extend(reversed(resources)) + + def _run(self, ssh, command): + out = ssh.execute(command + " >/dev/null 2>&1 && echo CMD-OK") + self.assertIn("CMD-OK", [l.strip() for l in out], "Command failed in the Instance: %s" % command) + + def _md5_16_mib(self, ssh, device): + out = ssh.execute("set -o pipefail; dd if=%s bs=1M count=16 iflag=direct 2>/dev/null | md5sum && echo CMD-OK" % device) + self.assertIn("CMD-OK", [l.strip() for l in out], "Could not read %s in the Instance" % device) + return out[0].split()[0] + + @staticmethod + def _disks(ssh): + # whole virtio/SCSI disks (vda, sdb) from /proc/partitions, which old guests without lsblk also have; + # names ending in a digit are partitions here (NVMe-style disk names are not expected in these guests) + return set(l.split()[3] for l in ssh.execute("cat /proc/partitions")[1:] + if len(l.split()) == 4 and not l.split()[3][-1].isdigit()) + + def _new_disk(self, ssh, disks_before): + new_disks = self._disks(ssh) - disks_before + self.assertEqual(len(new_disks), 1, "Could not identify the attached disk in the Instance") + return new_disks.pop() + def _create_vm_using_template_and_destroy_vm(self, template): vm_name = "VM-%d" % random.randint(0, 100) diff --git a/test/integration/smoke/test_snapshots.py b/test/integration/smoke/test_snapshots.py index 4d573a1424c3..b0879a3fd018 100644 --- a/test/integration/smoke/test_snapshots.py +++ b/test/integration/smoke/test_snapshots.py @@ -493,11 +493,6 @@ def test_01_snapshot_to_volume(self): """Test creating volume from snapshot """ self.services['volume_from_snapshot']['zoneid'] = self.zone.id - snapshot_volume_pool_response = list_storage_pools( - self.apiclient, - id=self.volume.storageid - ) - snapshot_volume_pool = snapshot_volume_pool_response[0] try: self.volume_from_snap = Volume.create_from_snapshot( self.userapiclient, @@ -508,11 +503,6 @@ def test_01_snapshot_to_volume(self): ) except CloudstackAPIException as cs: self.debug(cs.errorMsg) - if snapshot_volume_pool.type.lower() == "powerflex": - self.assertTrue( - cs.errorMsg.find("Create volume from snapshot is not supported for PowerFlex volume snapshots") > 0, - msg="Other than unsupported error while creating volume from snapshot for volume on PowerFlex pool") - return self.fail("Failed to create volume from snapshot: %s" % cs) self.cleanup.append(self.volume_from_snap)