diff --git a/api/src/main/java/com/cloud/agent/api/to/DiskTO.java b/api/src/main/java/com/cloud/agent/api/to/DiskTO.java index 5664de790919..1a82095e2f9b 100644 --- a/api/src/main/java/com/cloud/agent/api/to/DiskTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/DiskTO.java @@ -41,6 +41,7 @@ public class DiskTO { public static final String EXPAND_DATASTORE = "expandDatastore"; public static final String TEMPLATE_RESIGN = "templateResign"; public static final String SECRET_CONSUMER_DETAIL = "storageMigrateSecretConsumer"; + public static final String MIGRATION_DEST_POOL_TYPE = "storageMigrateDestPoolType"; private DataTO data; private Long diskSeq; diff --git a/api/src/main/java/com/cloud/storage/Storage.java b/api/src/main/java/com/cloud/storage/Storage.java index 4202610bd87d..dc34a8d7e907 100644 --- a/api/src/main/java/com/cloud/storage/Storage.java +++ b/api/src/main/java/com/cloud/storage/Storage.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Set; public class Storage { public static enum ImageFormat { @@ -227,6 +228,47 @@ public static List getNonSharedStoragePoolTypes() { } + // pool types whose volumes are files, on KVM + public static final Set KVM_FILE_BASED_POOL_TYPES = Set.of(StoragePoolType.NetworkFilesystem, StoragePoolType.SharedMountPoint, + StoragePoolType.Filesystem); + + /** + * True if a volume is migrated between two pools of the same type. + */ + public static boolean arePoolsSameType(StoragePoolType srcType, StoragePoolType destType) { + return srcType != null && srcType.equals(destType); + } + + /** + * True if at least one of the pools is file based (NFS, SharedMountPoint or local) on KVM, whether it is the + * source or the destination, and whether the other one is file based as well. + */ + public static boolean isAnyPoolFileBased(StoragePoolType srcType, StoragePoolType destType) { + return KVM_FILE_BASED_POOL_TYPES.contains(srcType) || KVM_FILE_BASED_POOL_TYPES.contains(destType); + } + + /** + * True if KVM copies a volume in place with a libvirt block copy: between two RBD pools, or between an RBD pool and + * a file based pool (NFS, SharedMountPoint or local). Both pools are then reachable from the host the Instance runs + * on, so the volume of a running Instance can be copied without moving the Instance. + */ + public static boolean isCopiedInPlaceOnKvm(StoragePoolType srcType, StoragePoolType destType) { + if (!StoragePoolType.RBD.equals(srcType) && !StoragePoolType.RBD.equals(destType)) { + return false; + } + return arePoolsSameType(srcType, destType) || isAnyPoolFileBased(srcType, destType); + } + + /** + * True if a volume is migrated between two file based pools (NFS, SharedMountPoint or local) on KVM. Such a volume + * is copied with qemu-img, which reads and writes an encrypted volume with its passphrase, so it is not limited to + * the pools a libvirt block copy can reach. It is the way a volume is moved when it is not in use by a running + * Instance. + */ + public static boolean areBothPoolsFileBased(StoragePoolType srcType, StoragePoolType destType) { + return KVM_FILE_BASED_POOL_TYPES.contains(srcType) && KVM_FILE_BASED_POOL_TYPES.contains(destType); + } + public static enum StorageResourceType { STORAGE_POOL, STORAGE_HOST, SECONDARY_STORAGE, LOCAL_SECONDARY_STORAGE } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StoragePoolInformation.java b/api/src/main/java/com/cloud/storage/StoragePoolInformation.java similarity index 88% rename from plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StoragePoolInformation.java rename to api/src/main/java/com/cloud/storage/StoragePoolInformation.java index f330c9f24f05..521ddf1e7455 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StoragePoolInformation.java +++ b/api/src/main/java/com/cloud/storage/StoragePoolInformation.java @@ -14,13 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.hypervisor.kvm.storage; - -import com.cloud.storage.Storage; +package com.cloud.storage; import java.util.Map; -class StoragePoolInformation { +/** + * What an agent needs to know to reach a primary storage pool: for a pool that is not (yet) defined on the host, e.g. a + * pool of another cluster to which an Instance is migrated. + */ +public class StoragePoolInformation { private String name; private String host; private int port; diff --git a/api/src/test/java/com/cloud/storage/StorageTest.java b/api/src/test/java/com/cloud/storage/StorageTest.java index b9edda569dab..82fad26ec78b 100644 --- a/api/src/test/java/com/cloud/storage/StorageTest.java +++ b/api/src/test/java/com/cloud/storage/StorageTest.java @@ -85,4 +85,82 @@ public void equalityTest() { Assert.assertTrue(t1.equals(StoragePoolType.NetworkFilesystem)); Assert.assertFalse(t1.equals(StoragePoolType.EXT)); } + + @Test + public void arePoolsSameTypeForTwoPoolsOfThatType() { + for (StoragePoolType poolType : StoragePoolType.values()) { + Assert.assertTrue(poolType + " -> " + poolType, Storage.arePoolsSameType(poolType, poolType)); + for (StoragePoolType other : StoragePoolType.values()) { + if (other.equals(poolType)) { + continue; + } + Assert.assertFalse(poolType + " -> " + other, Storage.arePoolsSameType(poolType, other)); + } + } + } + + @Test + public void isAnyPoolFileBasedForOneFileBasedPool() { + for (StoragePoolType fileBased : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue("RBD -> " + fileBased, Storage.isAnyPoolFileBased(StoragePoolType.RBD, fileBased)); + Assert.assertTrue(fileBased + " -> RBD", Storage.isAnyPoolFileBased(fileBased, StoragePoolType.RBD)); + for (StoragePoolType otherFileBased : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue(fileBased + " -> " + otherFileBased, Storage.isAnyPoolFileBased(fileBased, otherFileBased)); + } + } + Assert.assertFalse("RBD -> RBD", Storage.isAnyPoolFileBased(StoragePoolType.RBD, StoragePoolType.RBD)); + } + + @Test + public void isCopiedInPlaceOnKvmForRbdAndForRbdAndFileBasedPools() { + Assert.assertTrue("RBD -> RBD", Storage.isCopiedInPlaceOnKvm(StoragePoolType.RBD, StoragePoolType.RBD)); + for (StoragePoolType fileBased : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue("RBD -> " + fileBased, Storage.isCopiedInPlaceOnKvm(StoragePoolType.RBD, fileBased)); + Assert.assertTrue(fileBased + " -> RBD", Storage.isCopiedInPlaceOnKvm(fileBased, StoragePoolType.RBD)); + } + } + + @Test + public void isCopiedInPlaceOnKvmNotBetweenTwoFileBasedPools() { + for (StoragePoolType srcType : Storage.KVM_FILE_BASED_POOL_TYPES) { + for (StoragePoolType destType : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertFalse(srcType + " -> " + destType, Storage.isCopiedInPlaceOnKvm(srcType, destType)); + } + } + } + + @Test + public void isCopiedInPlaceOnKvmNotWithOtherPoolTypes() { + for (StoragePoolType other : StoragePoolType.values()) { + if (StoragePoolType.RBD.equals(other) || Storage.KVM_FILE_BASED_POOL_TYPES.contains(other)) { + continue; + } + Assert.assertFalse(other + " -> " + other, Storage.isCopiedInPlaceOnKvm(other, other)); + Assert.assertFalse("RBD -> " + other, Storage.isCopiedInPlaceOnKvm(StoragePoolType.RBD, other)); + Assert.assertFalse(other + " -> RBD", Storage.isCopiedInPlaceOnKvm(other, StoragePoolType.RBD)); + } + } + + @Test + public void areBothPoolsFileBasedBetweenTwoFileBasedPools() { + for (StoragePoolType srcType : Storage.KVM_FILE_BASED_POOL_TYPES) { + for (StoragePoolType destType : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue(srcType + " -> " + destType, Storage.areBothPoolsFileBased(srcType, destType)); + } + } + } + + @Test + public void areBothPoolsFileBasedNotWithOtherPoolTypes() { + for (StoragePoolType other : StoragePoolType.values()) { + if (Storage.KVM_FILE_BASED_POOL_TYPES.contains(other)) { + continue; + } + Assert.assertFalse(other + " -> " + other, Storage.areBothPoolsFileBased(other, other)); + for (StoragePoolType fileBased : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertFalse(fileBased + " -> " + other, Storage.areBothPoolsFileBased(fileBased, other)); + Assert.assertFalse(other + " -> " + fileBased, Storage.areBothPoolsFileBased(other, fileBased)); + } + } + } } diff --git a/core/src/main/java/com/cloud/agent/api/MigrateCommand.java b/core/src/main/java/com/cloud/agent/api/MigrateCommand.java index eaaee660ba85..87a1afcba504 100644 --- a/core/src/main/java/com/cloud/agent/api/MigrateCommand.java +++ b/core/src/main/java/com/cloud/agent/api/MigrateCommand.java @@ -27,6 +27,7 @@ import com.cloud.agent.api.to.DpdkTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.storage.Storage; +import com.cloud.storage.StoragePoolInformation; public class MigrateCommand extends Command { private String vmName; @@ -190,7 +191,7 @@ public void setNicBridgeMapping(Map nicBridgeMapping) { public static class MigrateDiskInfo { public enum DiskType { - FILE, BLOCK; + FILE, BLOCK, NETWORK; @Override public String toString() { @@ -208,7 +209,7 @@ public String toString() { } public enum Source { - FILE, DEV; + FILE, DEV, NETWORK; @Override public String toString() { @@ -225,6 +226,7 @@ public String toString() { private boolean isSourceDiskOnStorageFileSystem; private Storage.StoragePoolType sourcePoolType; private Storage.StoragePoolType destPoolType; + private StoragePoolInformation destPoolInformation; public MigrateDiskInfo(final String serialNumber, final DiskType diskType, final DriverType driverType, final Source source, final String sourceText) { this.serialNumber = serialNumber; @@ -289,6 +291,19 @@ public Storage.StoragePoolType getDestPoolType() { public void setDestPoolType(Storage.StoragePoolType destPoolType) { this.destPoolType = destPoolType; } + + /** + * Describes the destination pool of a {@link DiskType#NETWORK} disk: the source host cannot look it up, as the + * pool may belong to a cluster it is not part of. The name is the UUID of the pool, the host holds the + * (comma separated) monitors and the user info only the user, so that no secret travels with the command. + */ + public void setDestPoolInformation(StoragePoolInformation destPoolInformation) { + this.destPoolInformation = destPoolInformation; + } + + public StoragePoolInformation getDestPoolInformation() { + return destPoolInformation; + } } @Override diff --git a/core/src/main/java/com/cloud/agent/api/storage/MigrateVolumeCommand.java b/core/src/main/java/com/cloud/agent/api/storage/MigrateVolumeCommand.java index 70375c30a1bb..5559057ecd24 100644 --- a/core/src/main/java/com/cloud/agent/api/storage/MigrateVolumeCommand.java +++ b/core/src/main/java/com/cloud/agent/api/storage/MigrateVolumeCommand.java @@ -124,6 +124,14 @@ public DataTO getDestData() { return destData; } + public void setSrcData(DataTO srcData) { + this.srcData = srcData; + } + + public void setDestData(DataTO destData) { + this.destData = destData; + } + public void setSrcDetails(Map details) { srcDetails = details; } diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java index 78d720737b3e..726f26e1d6c9 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java @@ -95,7 +95,10 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { private static final List SUPPORTED_POOL_TYPES_TO_BYPASS_SECONDARY_STORE = Arrays.asList( StoragePoolType.NetworkFilesystem, StoragePoolType.Filesystem, - StoragePoolType.RBD + StoragePoolType.SharedMountPoint, + StoragePoolType.RBD, + StoragePoolType.CLVM, + StoragePoolType.CLVM_NG ); @Inject @@ -642,6 +645,8 @@ protected Answer migrateVolumeToPool(DataObject srcData, DataObject destData) { command.setContextParam(DiskTO.PROTOCOL_TYPE, Storage.StoragePoolType.DatastoreCluster.toString()); } + command.setSrcData(srcData.getTO()); + command.setDestData(destData.getTO()); boolean encryptionRequired = anyVolumeRequiresEncryption(srcData, destData); EndPoint ep = selector.select(srcData, StorageAction.MIGRATEVOLUME); @@ -675,6 +680,21 @@ protected Answer migrateVolumeToPool(DataObject srcData, DataObject destData) { volumeVo.setLastPoolId(oldPoolId); if (destPool.getPoolType() == StoragePoolType.CLVM) { volumeVo.setFormat(ImageFormat.RAW); + } else if (destPool.getPoolType() == StoragePoolType.RBD) { + // RBD only ever stores raw images; keep the volume's format metadata consistent + // regardless of what format it had on the source pool (e.g. QCOW2 on NFS). + volumeVo.setFormat(ImageFormat.RAW); + } else if (srcPool.getPoolType() == StoragePoolType.RBD && volumeVo.getFormat() == ImageFormat.RAW + && Storage.KVM_FILE_BASED_POOL_TYPES.contains(destPool.getPoolType())) { + // The KVM agent (LibvirtMigrateVolumeCommandWrapper) writes a real QCOW2 file when the + // destination is file-based; without updating this, the volume keeps looking RAW to + // LibvirtComputingResource, which then (mis)treats a plain qcow2 file on NFS as a raw + // block device the next time the Instance is started. + volumeVo.setFormat(ImageFormat.QCOW2); + } + if (volumeVo.getEncryptFormat() != null && (srcPool.getPoolType() == StoragePoolType.RBD) != (destPool.getPoolType() == StoragePoolType.RBD)) { + // The KVM agent encrypts an RBD volume natively with librbd (LUKS2), and a volume on any other pool with qemu (LUKS) + volumeVo.setEncryptFormat(destPool.getPoolType() == StoragePoolType.RBD ? "luks2" : "luks"); } if (ClvmPoolManager.isClvmPoolType(destPool.getPoolType())) { clvmPoolManager.setClvmLockHostId(volume.getId(), ep.getId()); diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java index e55302b8044d..b5ab4b6b9647 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/DataMotionServiceImpl.java @@ -106,10 +106,11 @@ private void cleanUpVolumesForFailedMigrations(DataObject srcData, DataObject de destinationVO.setPassphraseId(null); volDao.update(destinationVO.getId(), destinationVO); - if (passphraseId != null) { + // the destination shares the source's passphrase, so keep it while the source still needs it + if (passphraseId != null && !passphraseId.equals(sourceVO.getPassphraseId())) { + logger.debug("Deleting passphrase {}", passphraseId); passphraseDao.remove(passphraseId); } - } @Override diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageDataMotionStrategy.java index 867470dac040..93bdd2359686 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageDataMotionStrategy.java @@ -44,6 +44,7 @@ import com.cloud.exception.OperationTimedoutException; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.storage.clvm.ClvmPoolManager; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.Storage; @@ -90,13 +91,35 @@ protected StrategyPriority internalCanHandle(Map volumeMa Set volumeInfoSet = volumeMap.keySet(); for (VolumeInfo volumeInfo : volumeInfoSet) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(volumeInfo.getPoolId()); - if (!supportStoragePoolType(storagePoolVO.getPoolType())) { + if (!supportStoragePoolType(storagePoolVO.getPoolType()) && !isRbdSourceSupported(storagePoolVO, volumeMap.get(volumeInfo))) { return StrategyPriority.CANT_HANDLE; } } return StrategyPriority.HYPERVISOR; } + /** + * True if the volume lives on an RBD pool and goes to an RBD, NFS, SharedMountPoint, local or CLVM/CLVM_NG pool, which can be in + * another cluster. The Instance is live migrated with its disk copied over NBD to an image or file on the + * destination pool. A volume which stays on its + * pool is not copied (see {@link #shouldMigrateVolume}). + */ + protected boolean isRbdSourceSupported(StoragePoolVO sourcePool, DataStore destDataStore) { + if (sourcePool == null || destDataStore == null || sourcePool.getPoolType() != StoragePoolType.RBD) { + return false; + } + StoragePoolVO destPool = _storagePoolDao.findById(destDataStore.getId()); + return destPool != null && isDestinationOfRbdSource(destPool.getPoolType()); + } + + /** + * An RBD volume can be copied to an RBD, NFS, SharedMountPoint, local or CLVM/CLVM_NG pool. + */ + protected boolean isDestinationOfRbdSource(StoragePoolType destPoolType) { + return destPoolType == StoragePoolType.RBD || ClvmPoolManager.isClvmPoolType(destPoolType) + || supportStoragePoolType(destPoolType, StoragePoolType.Filesystem); + } + /** * Allow KVM live storage migration for non managed storage when: * - Source host and destination host are different, and are on the same cluster @@ -173,6 +196,10 @@ protected String generateDestPath(Host destHost, StoragePoolVO destStoragePool, return String.format("/dev/%s/%s", vgName, destVolumeInfo.getUuid()); } + if (destStoragePool.getPoolType() == StoragePoolType.RBD) { + return String.format("%s/%s", destStoragePool.getPath(), destVolumeInfo.getUuid()); + } + return new File(destStoragePool.getPath(), destVolumeInfo.getUuid()).getAbsolutePath(); } @@ -210,7 +237,9 @@ protected void setVolumePath(VolumeVO volume) { */ @Override protected boolean shouldMigrateVolume(StoragePoolVO sourceStoragePool, Host destHost, StoragePoolVO destStoragePool) { - return supportStoragePoolType(sourceStoragePool.getPoolType()); + return supportStoragePoolType(sourceStoragePool.getPoolType()) + || (sourceStoragePool.getPoolType() == StoragePoolType.RBD && sourceStoragePool.getId() != destStoragePool.getId() + && isDestinationOfRbdSource(destStoragePool.getPoolType())); } /** diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java index 17f84b780698..703f4bb2aae3 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java @@ -36,6 +36,7 @@ import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.resource.ResourceManager; +import com.cloud.storage.StoragePoolInformation; import com.cloud.storage.clvm.ClvmPoolManager; import org.apache.cloudstack.backup.InternalBackupService; import org.apache.cloudstack.storage.clvm.command.ClvmLockTransferCommand; @@ -2129,13 +2130,17 @@ public void copyAsync(Map volumeDataStoreMap, VirtualMach MigrateCommand.MigrateDiskInfo migrateDiskInfo; - boolean isNonManagedToNfs = supportStoragePoolType(sourceStoragePool.getPoolType(), StoragePoolType.Filesystem, StoragePoolType.CLVM, StoragePoolType.CLVM_NG) && destStoragePool.getPoolType() == StoragePoolType.NetworkFilesystem && !managedStorageDestination; + boolean isNonManagedToNfs = supportStoragePoolType(sourceStoragePool.getPoolType(), StoragePoolType.Filesystem, StoragePoolType.CLVM, StoragePoolType.CLVM_NG, StoragePoolType.RBD) && destStoragePool.getPoolType() == StoragePoolType.NetworkFilesystem && !managedStorageDestination; if (isNonManagedToNfs) { migrateDiskInfo = new MigrateCommand.MigrateDiskInfo(srcVolumeInfo.getPath(), MigrateCommand.MigrateDiskInfo.DiskType.FILE, MigrateCommand.MigrateDiskInfo.DriverType.QCOW2, MigrateCommand.MigrateDiskInfo.Source.FILE, connectHostToVolume(destHost, destVolumeInfo.getPoolId(), volumeIdentifier)); + } else if (destStoragePool.getPoolType() == StoragePoolType.RBD && !managedStorageDestination) { + migrateDiskInfo = configureMigrateDiskInfoForRbd(srcVolumeInfo, destPath, destStoragePool); + migrateDiskInfo.setSourceDiskOnStorageFileSystem(isStoragePoolTypeOfFile(sourceStoragePool)); + migrateDiskInfoList.add(migrateDiskInfo); } else { String backingPath = generateBackingPath(destStoragePool, destVolumeInfo); migrateDiskInfo = configureMigrateDiskInfo(srcVolumeInfo, destPath, backingPath); @@ -2145,7 +2150,7 @@ public void copyAsync(Map volumeDataStoreMap, VirtualMach } migrateDiskInfo.setSourcePoolType(sourceStoragePool.getPoolType()); migrateDiskInfo.setDestPoolType(destVolumeInfo.getStoragePoolType()); - prepareDiskWithSecretConsumerDetail(vmTO, srcVolumeInfo, destVolumeInfo.getPath()); + prepareDiskWithSecretConsumerDetail(vmTO, srcVolumeInfo, destVolumeInfo.getPath(), destStoragePool.getPoolType()); migrateStorage.put(srcVolumeInfo.getPath(), migrateDiskInfo); @@ -2259,12 +2264,7 @@ public void copyAsync(Map volumeDataStoreMap, VirtualMach throw new CloudRuntimeException(errMsg); } finally { if (!success && !srcVolumeInfoToDestVolumeInfo.isEmpty()) { - for (VolumeInfo destVolumeInfo : srcVolumeInfoToDestVolumeInfo.values()) { - logger.info(String.format("Expunging dest volume [id: %s, state: %s] as part of failed VM migration with volumes command for VM [%s].", destVolumeInfo.getId(), destVolumeInfo.getState(), vmTO.getId())); - destVolumeInfo.processEvent(Event.OperationFailed); - destVolumeInfo.processEvent(Event.DestroyRequested); - _volumeService.expungeVolumeAsync(destVolumeInfo); - } + cleanUpDestVolumesOfFailedMigration(srcVolumeInfoToDestVolumeInfo.values(), vmTO); } CopyCmdAnswer copyCmdAnswer = new CopyCmdAnswer(errMsg); @@ -2277,6 +2277,27 @@ public void copyAsync(Map volumeDataStoreMap, VirtualMach } } + /** + * Expunges the destination volumes created for a failed VM migration with volumes. When the migrate command itself failed, + * {@link #handlePostMigration} has already destroyed and expunged them, so volumes which are gone (or being removed) are skipped: + * sending more events to a volume whose row is already removed ends in a NullPointerException in the volume object. + */ + protected void cleanUpDestVolumesOfFailedMigration(Collection destVolumeInfos, VirtualMachineTO vmTO) { + for (VolumeInfo destVolumeInfo : destVolumeInfos) { + VolumeVO destVolumeVO = _volumeDao.findById(destVolumeInfo.getId()); + if (destVolumeVO == null || Arrays.asList(Volume.State.Expunging, Volume.State.Expunged).contains(destVolumeVO.getState())) { + logger.debug("Dest volume [id: {}] is already cleaned up after the failed VM migration with volumes command for VM [{}].", destVolumeInfo.getId(), vmTO.getId()); + continue; + } + logger.info("Expunging dest volume [id: {}, state: {}] as part of failed VM migration with volumes command for VM [{}].", destVolumeInfo.getId(), destVolumeVO.getState(), vmTO.getId()); + if (destVolumeVO.getState() != Volume.State.Destroy) { + destVolumeInfo.processEvent(Event.OperationFailed); + destVolumeInfo.processEvent(Event.DestroyRequested); + } + _volumeService.expungeVolumeAsync(destVolumeInfo); + } + } + private void prepareDisksForMigrationForClvm(VirtualMachineTO vmTO, Map volumeDataStoreMap, Host srcHost) { // For CLVM/CLVM_NG source pools, convert volumes from exclusive to shared mode // on the source host BEFORE PrepareForMigrationCommand on the destination. @@ -2311,9 +2332,11 @@ private MigrationOptions.Type decideMigrationTypeAndCopyTemplateIfNeeded(Host de // For block device sources, use FullClone (VIR_MIGRATE_NON_SHARED_DISK) boolean sourceIsBlockDevice = sourceStoragePool.getPoolType() == StoragePoolType.CLVM || sourceStoragePool.getPoolType() == StoragePoolType.CLVM_NG; + // An RBD image is a raw clone of the template: libvirt sees no backing chain, so the whole image has to be copied + boolean sourceIsRbd = sourceStoragePool.getPoolType() == StoragePoolType.RBD; if (StringUtils.isNotBlank(srcVolumeBackingFile) && supportStoragePoolType(destStoragePool.getPoolType(), StoragePoolType.Filesystem) && - !sourceIsBlockDevice && + !sourceIsBlockDevice && !sourceIsRbd && srcVolumeInfo.getTemplateId() != null && Objects.nonNull(vmTemplate) && !Arrays.asList(KVM_VM_IMPORT_DEFAULT_TEMPLATE_NAME, VM_IMPORT_DEFAULT_TEMPLATE_NAME).contains(vmTemplate.getName())) { @@ -2392,6 +2415,21 @@ protected MigrateCommand.MigrateDiskInfo configureMigrateDiskInfo(VolumeInfo src MigrateCommand.MigrateDiskInfo.Source.DEV, destPath, backingPath); } + /** + * Configures a {@link MigrateDiskInfo} for a destination volume on a Ceph RBD pool: a network disk of the raw format + * that is addressed as "pool/image". The monitors and the authentication of the destination pool are handed over as + * the host the Instance runs on may not know that pool, which can belong to another cluster. + */ + protected MigrateCommand.MigrateDiskInfo configureMigrateDiskInfoForRbd(VolumeInfo srcVolumeInfo, String destPath, StoragePoolVO destStoragePool) { + MigrateCommand.MigrateDiskInfo migrateDiskInfo = new MigrateCommand.MigrateDiskInfo(srcVolumeInfo.getPath(), + MigrateCommand.MigrateDiskInfo.DiskType.NETWORK, + MigrateCommand.MigrateDiskInfo.DriverType.RAW, + MigrateCommand.MigrateDiskInfo.Source.NETWORK, destPath); + migrateDiskInfo.setDestPoolInformation(new StoragePoolInformation(destStoragePool.getUuid(), destStoragePool.getHostAddress(), destStoragePool.getPort(), + destStoragePool.getPath(), StringUtils.substringBefore(destStoragePool.getUserInfo(), ":"), StoragePoolType.RBD, null, true)); + return migrateDiskInfo; + } + /** * UpdatesMigrateDiskInfo for CLVM/CLVM_NG block devices by returning a new instance with corrected disk type, driver type, and source. * For CLVM/CLVM_NG destinations, returns a new MigrateDiskInfo with BLOCK disk type, DEV source, and appropriate driver type (QCOW2 for CLVM_NG, RAW for CLVM). @@ -2517,7 +2555,7 @@ private void handlePostMigration(boolean success, Map sr VolumeVO volumeVO = _volumeDao.findById(destVolumeInfo.getId()); StoragePoolVO srcPoolVO = _storagePoolDao.findById(srcVolumeInfo.getPoolId()); StoragePoolVO destPoolVO = _storagePoolDao.findById(destVolumeInfo.getPoolId()); - volumeVO.setFormat(destPoolVO != null && destPoolVO.getPoolType() == StoragePoolType.CLVM + volumeVO.setFormat(destPoolVO != null && (destPoolVO.getPoolType() == StoragePoolType.CLVM || destPoolVO.getPoolType() == StoragePoolType.RBD) ? ImageFormat.RAW : ImageFormat.QCOW2); volumeVO.setLastId(srcVolumeInfo.getId()); @@ -2611,14 +2649,23 @@ private VolumeVO duplicateVolumeOnAnotherStorage(Volume volume, StoragePoolVO st newVol.setPoolType(storagePoolVO.getPoolType()); newVol.setLastPoolId(lastPoolId); newVol.setLastId(volume.getId()); + // the destination volume is created in the format of its pool: raw on RBD, qcow2 on a file based pool + if (storagePoolVO.getPoolType() == StoragePoolType.RBD) { + newVol.setFormat(ImageFormat.RAW); + } else if (volume.getFormat() == ImageFormat.RAW && isStoragePoolTypeInList(storagePoolVO.getPoolType(), + StoragePoolType.NetworkFilesystem, StoragePoolType.SharedMountPoint, StoragePoolType.Filesystem)) { + newVol.setFormat(ImageFormat.QCOW2); + } + // librbd encrypts an RBD volume natively (LUKS2), a volume on any other pool with qemu (LUKS) + String newEncryptFormat = storagePoolVO.getPoolType() == StoragePoolType.RBD ? "luks2" : "luks"; if (volume.getKmsKeyId() != null) { newVol.setKmsKeyId(volume.getKmsKeyId()); newVol.setKmsWrappedKeyId(volume.getKmsWrappedKeyId()); - newVol.setEncryptFormat(volume.getEncryptFormat()); + newVol.setEncryptFormat(newEncryptFormat); } else if (volume.getPassphraseId() != null) { newVol.setPassphraseId(volume.getPassphraseId()); - newVol.setEncryptFormat(volume.getEncryptFormat()); + newVol.setEncryptFormat(newEncryptFormat); } return _volumeDao.persist(newVol); @@ -2705,10 +2752,12 @@ protected void postVolumeCreationActions(VolumeInfo srcVolumeInfo, VolumeInfo de } /** - * Include some destination volume info in vmTO, required for some PrepareForMigrationCommand processing + * Include some destination volume info in vmTO, required for some PrepareForMigrationCommand processing. * + * @param destPoolType the disk's destination pool, passed through as {@link DiskTO#MIGRATION_DEST_POOL_TYPE} since + * the disk's own VolumeObjectTO still reports its source pool at this point. */ - protected void prepareDiskWithSecretConsumerDetail(VirtualMachineTO vmTO, VolumeInfo srcVolume, String destPath) { + protected void prepareDiskWithSecretConsumerDetail(VirtualMachineTO vmTO, VolumeInfo srcVolume, String destPath, StoragePoolType destPoolType) { if (vmTO.getDisks() != null) { logger.debug(String.format("Preparing VM TO '%s' disks with migration data", vmTO)); Arrays.stream(vmTO.getDisks()).filter(diskTO -> diskTO.getData().getId() == srcVolume.getId()).forEach( diskTO -> { @@ -2716,6 +2765,9 @@ protected void prepareDiskWithSecretConsumerDetail(VirtualMachineTO vmTO, Volume diskTO.setDetails(new HashMap<>()); } diskTO.getDetails().put(DiskTO.SECRET_CONSUMER_DETAIL, destPath); + if (destPoolType != null) { + diskTO.getDetails().put(DiskTO.MIGRATION_DEST_POOL_TYPE, destPoolType.toString()); + } }); } } diff --git a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageSystemDataMotionTest.java b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageSystemDataMotionTest.java index 6f0776b27c8c..e5410c753d93 100644 --- a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageSystemDataMotionTest.java +++ b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/KvmNonManagedStorageSystemDataMotionTest.java @@ -181,7 +181,8 @@ public void internalCanHandleTestNonManaged() { Map volumeMap = configureTestInternalCanHandle(false, storagePoolTypeArray[i]); StrategyPriority strategyPriority = kvmNonManagedStorageDataMotionStrategy.internalCanHandle(volumeMap, new HostVO("sourceHostUuid"), new HostVO("destHostUuid")); - if (supportStoragePoolType(storagePoolTypeArray[i])) { + // the test maps the volumes to a pool of their own type, which for RBD is a live copy to another RBD pool + if (supportStoragePoolType(storagePoolTypeArray[i]) || StoragePoolType.RBD.equals(storagePoolTypeArray[i])) { Assert.assertEquals(StrategyPriority.HYPERVISOR, strategyPriority); } else { Assert.assertEquals(StrategyPriority.CANT_HANDLE, strategyPriority); @@ -280,6 +281,64 @@ public void shouldMigrateVolumeTest() { } } + @Test + public void shouldMigrateVolumeTestRbdSourceToOtherRbdFileAndClvmPools() { + StoragePoolVO sourceStoragePool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn(StoragePoolType.RBD).when(sourceStoragePool).getPoolType(); + Mockito.doReturn(1L).when(sourceStoragePool).getId(); + HostVO destHost = new HostVO("guid"); + for (StoragePoolType destType : StoragePoolType.values()) { + StoragePoolVO destStoragePool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn(destType).when(destStoragePool).getPoolType(); + Mockito.doReturn(2L).when(destStoragePool).getId(); + boolean expected = destType == StoragePoolType.RBD || destType == StoragePoolType.NetworkFilesystem + || destType == StoragePoolType.SharedMountPoint || destType == StoragePoolType.Filesystem + || destType == StoragePoolType.CLVM || destType == StoragePoolType.CLVM_NG; + assertEquals(destType.name(), expected, kvmNonManagedStorageDataMotionStrategy.shouldMigrateVolume(sourceStoragePool, destHost, destStoragePool)); + } + } + + @Test + public void shouldMigrateVolumeTestRbdVolumeStaysOnItsPool() { + StoragePoolVO pool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn(StoragePoolType.RBD).when(pool).getPoolType(); + Mockito.doReturn(1L).when(pool).getId(); + assertFalse(kvmNonManagedStorageDataMotionStrategy.shouldMigrateVolume(pool, new HostVO("guid"), pool)); + } + + @Test + public void generateDestPathTestRbdDestination() { + StoragePoolVO destStoragePool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn(StoragePoolType.RBD).when(destStoragePool).getPoolType(); + Mockito.doReturn("cephpool").when(destStoragePool).getPath(); + VolumeInfo destVolumeInfo = Mockito.mock(VolumeInfo.class); + Mockito.doReturn("vol-uuid").when(destVolumeInfo).getUuid(); + assertEquals("cephpool/vol-uuid", kvmNonManagedStorageDataMotionStrategy.generateDestPath(new HostVO("guid"), destStoragePool, destVolumeInfo)); + } + + @Test + public void configureMigrateDiskInfoForRbdTest() { + StoragePoolVO destStoragePool = Mockito.spy(new StoragePoolVO()); + Mockito.doReturn("10.0.0.1,10.0.0.2").when(destStoragePool).getHostAddress(); + Mockito.doReturn(6789).when(destStoragePool).getPort(); + Mockito.doReturn("cephuser:secretkey").when(destStoragePool).getUserInfo(); + Mockito.doReturn("pool-uuid").when(destStoragePool).getUuid(); + Mockito.doReturn("cephpool").when(destStoragePool).getPath(); + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + Mockito.doReturn("volume path").when(srcVolumeInfo).getPath(); + + MigrateCommand.MigrateDiskInfo info = kvmNonManagedStorageDataMotionStrategy.configureMigrateDiskInfoForRbd(srcVolumeInfo, "cephpool/vol", destStoragePool); + + assertEquals(MigrateCommand.MigrateDiskInfo.DiskType.NETWORK, info.getDiskType()); + assertEquals(MigrateCommand.MigrateDiskInfo.DriverType.RAW, info.getDriverType()); + assertEquals("cephpool/vol", info.getSourceText()); + assertEquals("volume path", info.getSerialNumber()); + assertEquals("10.0.0.1,10.0.0.2", info.getDestPoolInformation().getHost()); + assertEquals(6789, info.getDestPoolInformation().getPort()); + assertEquals("cephuser", info.getDestPoolInformation().getUserInfo()); + assertEquals("pool-uuid", info.getDestPoolInformation().getName()); + } + @Test public void sendCopyCommandTest() throws AgentUnavailableException, OperationTimedoutException { configureAndTestSendCommandTest(null); diff --git a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java index fc51eeba7b6e..5360841e32fa 100644 --- a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java +++ b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategyTest.java @@ -25,6 +25,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.MockitoAnnotations.initMocks; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; @@ -33,6 +34,8 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore; import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.storage.datastore.PrimaryDataStoreImpl; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; @@ -45,6 +48,10 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.storage.Volume; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.VolumeDao; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; @@ -55,8 +62,6 @@ import com.cloud.storage.ScopeType; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.storage.Volume; -import com.cloud.storage.VolumeVO; import java.util.AbstractMap; import java.util.Arrays; import java.util.HashSet; @@ -81,6 +86,11 @@ public class StorageSystemDataMotionStrategyTest { @Mock private PrimaryDataStoreDao primaryDataStoreDao; + @Mock + private VolumeDao volumeDao; + @Mock + private VolumeService volumeService; + @Mock StoragePoolVO sourceStoragePoolVoMock, destinationStoragePoolVoMock; @@ -651,4 +661,109 @@ public void testInternalCanHandle_ClvmNgToClvm() { Assert.assertEquals(StrategyPriority.HIGHEST, result); } + + private VolumeVO volumeInState(Volume.State state) { + VolumeVO volumeVO = mock(VolumeVO.class); + doReturn(state).when(volumeVO).getState(); + return volumeVO; + } + + @Test + public void cleanUpDestVolumesOfFailedMigrationExpungesVolumeStillInTheDatabase() { + VolumeInfo destVolume = mock(VolumeInfo.class); + doReturn(75L).when(destVolume).getId(); + doReturn(volumeInState(Volume.State.Ready)).when(volumeDao).findById(75L); + + strategy.cleanUpDestVolumesOfFailedMigration(Arrays.asList(destVolume), mock(VirtualMachineTO.class)); + + Mockito.verify(destVolume).processEvent(Event.OperationFailed); + Mockito.verify(destVolume).processEvent(Event.DestroyRequested); + Mockito.verify(volumeService).expungeVolumeAsync(destVolume); + } + + @Test + public void cleanUpDestVolumesOfFailedMigrationExpungesVolumeInDestroyStateWithoutProcessingEvents() { + // Destroy has no transition for DestroyRequested; sending it throws NoTransitionException and masks the + // real migration error, so a Destroy-state volume skips straight to expungeVolumeAsync (which sends + // ExpungeRequested instead, and Destroy -> Expunging is a valid transition). + VolumeInfo destVolume = mock(VolumeInfo.class); + doReturn(78L).when(destVolume).getId(); + doReturn(volumeInState(Volume.State.Destroy)).when(volumeDao).findById(78L); + + strategy.cleanUpDestVolumesOfFailedMigration(Arrays.asList(destVolume), mock(VirtualMachineTO.class)); + + Mockito.verify(destVolume, Mockito.never()).processEvent(Mockito.any(Event.class)); + Mockito.verify(volumeService).expungeVolumeAsync(destVolume); + } + + @Test + public void cleanUpDestVolumesOfFailedMigrationSkipsVolumeAlreadyExpunged() { + VolumeInfo destVolume = mock(VolumeInfo.class); + doReturn(76L).when(destVolume).getId(); + doReturn(null).when(volumeDao).findById(76L); + + strategy.cleanUpDestVolumesOfFailedMigration(Arrays.asList(destVolume), mock(VirtualMachineTO.class)); + + Mockito.verify(destVolume, Mockito.never()).processEvent(Mockito.any(Event.class)); + Mockito.verify(volumeService, Mockito.never()).expungeVolumeAsync(Mockito.any()); + } + + @Test + public void cleanUpDestVolumesOfFailedMigrationSkipsVolumeBeingRemoved() { + for (Volume.State state : new Volume.State[] {Volume.State.Expunging, Volume.State.Expunged}) { + VolumeInfo destVolume = mock(VolumeInfo.class); + doReturn(77L).when(destVolume).getId(); + doReturn(volumeInState(state)).when(volumeDao).findById(77L); + + strategy.cleanUpDestVolumesOfFailedMigration(Arrays.asList(destVolume), mock(VirtualMachineTO.class)); + + Mockito.verify(destVolume, Mockito.never()).processEvent(Mockito.any(Event.class)); + } + Mockito.verify(volumeService, Mockito.never()).expungeVolumeAsync(Mockito.any()); + } + + private VolumeVO invokeDuplicateVolumeOnAnotherStorage(VolumeVO sourceVolume, StoragePoolVO destPool) throws Exception { + sourceVolume.setSize(1073741824L); + Mockito.doAnswer(invocation -> invocation.getArgument(0)).when(volumeDao).persist(Mockito.any(VolumeVO.class)); + Method method = StorageSystemDataMotionStrategy.class.getDeclaredMethod("duplicateVolumeOnAnotherStorage", Volume.class, StoragePoolVO.class); + method.setAccessible(true); + return (VolumeVO) method.invoke(strategy, sourceVolume, destPool); + } + + @Test + public void duplicateVolumeOnAnotherStorageSetsLuks2WhenDestinationIsRbd() throws Exception { + VolumeVO sourceVolume = new VolumeVO() {}; + sourceVolume.setPassphraseId(99L); + sourceVolume.setEncryptFormat("luks"); + + doReturn(StoragePoolType.RBD).when(destinationStoragePoolVoMock).getPoolType(); + + VolumeVO result = invokeDuplicateVolumeOnAnotherStorage(sourceVolume, destinationStoragePoolVoMock); + + Assert.assertEquals("luks2", result.getEncryptFormat()); + } + + @Test + public void duplicateVolumeOnAnotherStorageSetsLuksWhenDestinationIsNotRbd() throws Exception { + VolumeVO sourceVolume = new VolumeVO() {}; + sourceVolume.setPassphraseId(99L); + sourceVolume.setEncryptFormat("luks2"); + + doReturn(StoragePoolType.NetworkFilesystem).when(destinationStoragePoolVoMock).getPoolType(); + + VolumeVO result = invokeDuplicateVolumeOnAnotherStorage(sourceVolume, destinationStoragePoolVoMock); + + Assert.assertEquals("luks", result.getEncryptFormat()); + } + + @Test + public void duplicateVolumeOnAnotherStorageLeavesEncryptFormatNullWhenNotEncrypted() throws Exception { + VolumeVO sourceVolume = new VolumeVO() {}; + + doReturn(StoragePoolType.RBD).when(destinationStoragePoolVoMock).getPoolType(); + + VolumeVO result = invokeDuplicateVolumeOnAnotherStorage(sourceVolume, destinationStoragePoolVoMock); + + Assert.assertNull(result.getEncryptFormat()); + } } diff --git a/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index 0ce2cedb944c..5e63fc8d1311 100644 --- a/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -603,7 +603,7 @@ public EndPoint select(DataObject object, StorageAction action, boolean encrypti } case MIGRATEVOLUME: { VolumeInfo volume = (VolumeInfo) object; - if (volume.getHypervisorType() == Hypervisor.HypervisorType.Hyperv || volume.getHypervisorType() == Hypervisor.HypervisorType.VMware) { + if (List.of(Hypervisor.HypervisorType.VMware, Hypervisor.HypervisorType.Hyperv, Hypervisor.HypervisorType.KVM).contains(volume.getHypervisorType())) { VirtualMachine vm = volume.getAttachedVM(); if ((vm != null) && (vm.getState() == VirtualMachine.State.Running)) { Long hostId = vm.getHostId(); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index cadb70a0d4e5..560ed80c4456 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -1436,7 +1436,7 @@ public boolean configure(final String name, final Map params) th if (this.bridgeType == BridgeType.OPENVSWITCH) { if (conn.getLibVirVersion() < 10 * 1000 + 0) { - throw new ConfigurationException("Libvirt version 0.10.0 required for openvswitch support, but version " + conn.getLibVirVersion() + " detected"); + throw new ConfigurationException("Libvirt version 0.10.0 required for openvswitch support, but version " + prettyVersion(conn.getLibVirVersion()) + " detected"); } } } catch (final LibvirtException e) { @@ -6146,7 +6146,7 @@ public Pair getNicStats(final String nicName) { } } - private String prettyVersion(final long version) { + public static String prettyVersion(final long version) { final long major = version / 1000000; final long minor = version % 1000000 / 1000; final long release = version % 1000000 % 1000; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java index 9d47f497196e..eaf343b9a43e 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java @@ -44,10 +44,10 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.utils.RbdUtils; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @@ -98,11 +98,7 @@ public Answer execute(final BackupSnapshotCommand command, final LibvirtComputin */ if (primaryPool.getType() == StoragePoolType.RBD) { try { - final Rados r = new Rados(primaryPool.getAuthUserName()); - r.confSet("mon_host", RbdUtils.getRbdMonitors(primaryPool.getSourceHost(), primaryPool.getSourcePort())); - r.confSet("key", primaryPool.getAuthSecret()); - r.confSet("client_mount_timeout", "30"); - r.connect(); + final Rados r = LibvirtStorageAdaptor.connectToCeph(primaryPool); logger.debug("Successfully connected to Ceph cluster at " + r.confGet("mon_host")); final IoCTX io = r.ioCtxCreate(primaryPool.getSourceDir()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java index 2d3e33107500..8695484a8ccf 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java @@ -41,10 +41,10 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.utils.RbdUtils; import com.cloud.utils.script.Script; @ResourceWrapper(handles = ManageSnapshotCommand.class) @@ -116,11 +116,7 @@ public Answer execute(final ManageSnapshotCommand command, final LibvirtComputin */ if (primaryPool.getType() == StoragePoolType.RBD) { try { - final Rados r = new Rados(primaryPool.getAuthUserName()); - r.confSet("mon_host", RbdUtils.getRbdMonitors(primaryPool.getSourceHost(), primaryPool.getSourcePort())); - r.confSet("key", primaryPool.getAuthSecret()); - r.confSet("client_mount_timeout", "30"); - r.connect(); + final Rados r = LibvirtStorageAdaptor.connectToCeph(primaryPool); logger.debug("Successfully connected to Ceph cluster at " + r.confGet("mon_host")); final IoCTX io = r.ioCtxCreate(primaryPool.getSourceDir()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java index f15ad8e562f8..ad50e218b211 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java @@ -48,6 +48,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtXMLParser; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; +import com.cloud.storage.StoragePoolInformation; import com.cloud.storage.Storage; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; @@ -974,6 +975,11 @@ protected String replaceStorage(String xmlDesc, Map toRemove = new ArrayList<>(); + NodeList diskChildNodes = diskNode.getChildNodes(); + for (int i = 0; i < diskChildNodes.getLength(); i++) { + Node child = diskChildNodes.item(i); + // a backing chain of the source (a qcow2 volume cloned from a template) is flattened into the raw image + if ("source".equals(child.getNodeName()) || "auth".equals(child.getNodeName()) || "backingStore".equals(child.getNodeName())) { + toRemove.add(child); + } + } + toRemove.forEach(diskNode::removeChild); + + StoragePoolInformation destPool = migrateDiskInfo.getDestPoolInformation(); + Element sourceNode = doc.createElement("source"); + sourceNode.setAttribute("protocol", "rbd"); + sourceNode.setAttribute("name", migrateDiskInfo.getSourceText()); + for (String monitorHost : StringUtils.split(destPool.getHost(), ',')) { + Element hostNode = doc.createElement("host"); + hostNode.setAttribute("name", monitorHost.trim()); + if (destPool.getPort() > 0) { + hostNode.setAttribute("port", String.valueOf(destPool.getPort())); + } + sourceNode.appendChild(hostNode); + } + diskNode.appendChild(sourceNode); + + if (StringUtils.isNotBlank(destPool.getUserInfo())) { + Element authNode = doc.createElement("auth"); + authNode.setAttribute("username", destPool.getUserInfo()); + Element secretNode = doc.createElement("secret"); + secretNode.setAttribute("type", "ceph"); + secretNode.setAttribute("uuid", destPool.getName()); + authNode.appendChild(secretNode); + diskNode.appendChild(authNode); + } + } + private String getOldVolumePath(List disks, String vmName) { String oldIsoVolumePath = null; for (DiskDef disk : disks) { @@ -1305,7 +1365,11 @@ private boolean shouldUpdateDriverTypeForMigration(boolean migrateStorageManaged boolean destIsClvm = Storage.StoragePoolType.CLVM == migrateDiskInfo.getDestPoolType() || Storage.StoragePoolType.CLVM_NG == migrateDiskInfo.getDestPoolType(); + // an RBD image is raw, whereas a volume on a file based pool is qcow2 + boolean isRbdRelatedMigration = Storage.StoragePoolType.RBD == migrateDiskInfo.getSourcePoolType() || + Storage.StoragePoolType.RBD == migrateDiskInfo.getDestPoolType(); + boolean isClvmRelatedMigration = sourceIsClvm || destIsClvm; - return migrateStorageManaged || isClvmRelatedMigration; + return migrateStorageManaged || isClvmRelatedMigration || isRbdRelatedMigration; } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapper.java index 85574c447417..b52b356d7aea 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapper.java @@ -26,9 +26,12 @@ import com.cloud.agent.api.to.DiskTO; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.disconnecthook.VolumeMigrationCancelHook; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.KVMStorageProcessor; +import com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; import com.cloud.storage.Storage; @@ -38,12 +41,14 @@ import java.io.IOException; import java.io.StringWriter; import java.util.Map; +import java.util.Objects; import java.util.UUID; import org.apache.cloudstack.storage.datastore.client.ScaleIOGatewayClient; import org.apache.cloudstack.storage.datastore.util.ScaleIOUtil; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.security.ParserUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -56,6 +61,8 @@ import org.libvirt.LibvirtException; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; @@ -77,9 +84,14 @@ public Answer execute(final MigrateVolumeCommand command, final LibvirtComputing VolumeObjectTO srcVolumeObjectTO = (VolumeObjectTO)command.getSrcData(); PrimaryDataStoreTO srcPrimaryDataStore = (PrimaryDataStoreTO)srcVolumeObjectTO.getDataStore(); + VolumeObjectTO destVolumeObjectTO = (VolumeObjectTO)command.getDestData(); + PrimaryDataStoreTO destPrimaryDataStore = (PrimaryDataStoreTO)destVolumeObjectTO.getDataStore(); + MigrateVolumeAnswer answer; - if (srcPrimaryDataStore.getPoolType().equals(Storage.StoragePoolType.PowerFlex)) { + if (Objects.equals(Storage.StoragePoolType.PowerFlex, srcPrimaryDataStore.getPoolType())) { answer = migratePowerFlexVolume(command, libvirtComputingResource); + } else if (Storage.isCopiedInPlaceOnKvm(srcPrimaryDataStore.getPoolType(), destPrimaryDataStore.getPoolType())) { + answer = migrateRBDVolume(command, libvirtComputingResource); } else { answer = migrateRegularVolume(command, libvirtComputingResource); } @@ -134,7 +146,7 @@ protected MigrateVolumeAnswer migratePowerFlexVolume(final MigrateVolumeCommand destSecretUUID = libvirtComputingResource.createLibvirtVolumeSecret(conn, destVolumeObjectTO.getPath(), destVolumeObjectTO.getPassphrase()); } - String diskdef = generateDestinationDiskXML(dm, srcVolumeId, diskFilePath, destSecretUUID); + String diskdef = generateDestinationDiskXMLForPowerFlex(dm, srcVolumeId, diskFilePath, destSecretUUID); destDiskLabel = generateDestinationDiskLabel(diskdef); TypedUlongParameter parameter = new TypedUlongParameter("bandwidth", 0); @@ -198,8 +210,14 @@ protected MigrateVolumeAnswer checkBlockJobStatus(MigrateVolumeCommand command, if (blockJobInfo.end > 0) { logger.info(String.format("Block copy completed for the volume %s : %s", diskLabel, srcPath)); dm.blockJobAbort(diskLabel, Domain.BlockJobAbortFlags.PIVOT); + // the Instance uses the destination volume from here on, so what is left to do must not fail the migration if (StringUtils.isNotEmpty(srcSecretUUID)) { - libvirtComputingResource.removeLibvirtVolumeSecret(conn, srcSecretUUID); + try { + libvirtComputingResource.removeLibvirtVolumeSecret(conn, srcSecretUUID); + } catch (Exception e) { + logger.warn(String.format("Failed to remove the libvirt secret %s of the source volume %s after the block copy completed: %s", + srcSecretUUID, srcPath, e.getMessage()), e); + } } break; } else { @@ -249,7 +267,7 @@ private String generateDestinationDiskLabel(String diskXml) throws ParserConfigu return diskLabel; } - protected String generateDestinationDiskXML(Domain dm, String srcVolumeId, String diskFilePath, String destSecretUUID) throws LibvirtException, ParserConfigurationException, IOException, TransformerException, SAXException { + protected String generateDestinationDiskXMLForPowerFlex(Domain dm, String srcVolumeId, String diskFilePath, String destSecretUUID) throws LibvirtException, ParserConfigurationException, IOException, TransformerException, SAXException { final String domXml = dm.getXMLDesc(0); DocumentBuilderFactory dbFactory = ParserUtils.getSaferDocumentBuilderFactory(); @@ -374,4 +392,411 @@ protected MigrateVolumeAnswer migrateRegularVolume(final MigrateVolumeCommand co return new MigrateVolumeAnswer(command, true, null, destPath); } + + + protected MigrateVolumeAnswer migrateRBDVolume(final MigrateVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) { + final String vmName = command.getAttachedVmName(); + + VolumeObjectTO srcVolumeObjectTO = (VolumeObjectTO)command.getSrcData(); + PrimaryDataStoreTO sourcePool = (PrimaryDataStoreTO)srcVolumeObjectTO.getDataStore(); + + VolumeObjectTO destVolumeObjectTO = (VolumeObjectTO)command.getDestData(); + PrimaryDataStoreTO destPool = (PrimaryDataStoreTO)destVolumeObjectTO.getDataStore(); + + String destDiskLabel = null; + + VolumeMigrationCancelHook cancelHook = null; + + final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr(); + + Domain dm = null; + MigrateVolumeAnswer answer = null; + boolean destVolumeCreated = false; + // whether the block copy has been pivoted: the Instance then uses the destination volume, so nothing + // that follows may turn the migration into a failure + boolean pivoted = false; + KVMStoragePool destKvmPool = null; + try { + // libvirt < 10.1.0 cannot add the LUKS secret of an encrypted RBD image to a running domain before the + // image itself (see KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG), so the block copy + // into it fails. Refuse before anything is created on the destination pool. + if (Objects.equals(Storage.StoragePoolType.RBD, destPool.getPoolType()) && ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase()) + && libvirtComputingResource.getHypervisorLibvirtVersion() < KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG) { + return new MigrateVolumeAnswer(command, false, String.format("Libvirt version %s required to live migrate a volume to an encrypted RBD volume, but version %s detected." + + " Stop the Instance to migrate the volume, or upgrade libvirt.", + LibvirtComputingResource.prettyVersion(KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG), + LibvirtComputingResource.prettyVersion(libvirtComputingResource.getHypervisorLibvirtVersion())), null); + } + + final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper(); + Connect conn = libvirtUtilitiesHelper.getConnection(); + dm = libvirtComputingResource.getDomain(conn, vmName); + if (dm == null) { + return new MigrateVolumeAnswer(command, false, "Migrate volume failed due to can not find vm: " + vmName, null); + } + + DomainInfo.DomainState domainState = dm.getInfo().state ; + if (domainState != DomainInfo.DomainState.VIR_DOMAIN_RUNNING) { + return new MigrateVolumeAnswer(command, false, "Migrate volume failed due to VM is not running: " + vmName + " with domainState = " + domainState, null); + } + + KVMStoragePool pool = storagePoolMgr.getStoragePool(destPool.getPoolType(), destPool.getUuid()); + destKvmPool = pool; + pool.connectPhysicalDisk(destVolumeObjectTO.getPath(), null); + + KVMStoragePool srcKvmPool = storagePoolMgr.getStoragePool(sourcePool.getPoolType(), sourcePool.getUuid()); + final String sourceFilePath = generateVolumePathOnHost(srcKvmPool, sourcePool, srcVolumeObjectTO); + final String destFilePath = generateVolumePathOnHost(pool, destPool, destVolumeObjectTO); + + String srcSecretUUID = null; + String destSecretUUID = null; + if (ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase())) { + srcSecretUUID = libvirtComputingResource.createLibvirtVolumeSecret(conn, srcVolumeObjectTO.getPath(), srcVolumeObjectTO.getPassphrase()); + destSecretUUID = libvirtComputingResource.createLibvirtVolumeSecret(conn, destVolumeObjectTO.getPath(), destVolumeObjectTO.getPassphrase()); + if (Objects.equals(srcSecretUUID, destSecretUUID)) { + // the secret is named after the volume path and is shared by both disks: keep it for the Instance + srcSecretUUID = null; + } + } + + // A block copy between two RBD pools only has to copy the active layer, as the destination image is + // already provisioned. When NFS is involved the backing chain of the source differs from what the + // destination can reference, so the whole chain is flattened into the destination instead. + boolean srcAndDestOnRbd = Objects.equals(Storage.StoragePoolType.RBD, sourcePool.getPoolType()) + && Objects.equals(Storage.StoragePoolType.RBD, destPool.getPoolType()); + + String diskdef = generateDestinationDiskXMLForRBD(dm, sourceFilePath, destFilePath, destSecretUUID, pool, destPool.getPoolType(), + srcAndDestOnRbd); + if (diskdef == null) { + return new MigrateVolumeAnswer(command, false, + String.format("Migrate volume failed as the disk with path %s was not found in the XML domain of vm %s", sourceFilePath, vmName), null); + } + destDiskLabel = generateDestinationDiskLabel(diskdef); + + TypedUlongParameter parameter = new TypedUlongParameter("bandwidth", 0); + TypedParameter[] parameters = new TypedParameter[1]; + parameters[0] = parameter; + + int blockCopyFlags = srcAndDestOnRbd ? Domain.BlockCopyFlags.SHALLOW : 0; + if (ArrayUtils.isNotEmpty(destVolumeObjectTO.getPassphrase())) { + // libvirt can not create (and format) an encrypted mirror itself, so the destination volume is + // created with its encryption header up front and the block copy writes into it. + long guestSize = getEncryptedVolumeSize(srcKvmPool, sourcePool, srcVolumeObjectTO.getPath()); + createEncryptedDestinationVolume(pool, destPool, destVolumeObjectTO, guestSize); + destVolumeCreated = true; + blockCopyFlags |= Domain.BlockCopyFlags.REUSE_EXT; + } + + cancelHook = new VolumeMigrationCancelHook(dm, destDiskLabel); + libvirtComputingResource.addDisconnectHook(cancelHook); + + libvirtComputingResource.createOrUpdateLogFileForCommand(command, Command.State.PROCESSING_IN_BACKEND); + + dm.blockCopy(destDiskLabel, diskdef, parameters, blockCopyFlags); + logger.info(String.format("Block copy has started for the volume %s : %s to %s", destDiskLabel, sourceFilePath, destFilePath)); + + answer = checkBlockJobStatus(command, dm, destDiskLabel, sourceFilePath, destFilePath, libvirtComputingResource, conn, srcSecretUUID); + if (answer != null && answer.getResult()) { + // the block copy was pivoted: from here on the migration is done, and what follows only logs a failure + pivoted = true; + answer = new MigrateVolumeAnswer(command, true, null, destVolumeObjectTO.getPath()); + try { + libvirtComputingResource.createOrUpdateLogFileForCommand(command, Command.State.COMPLETED); + } catch (Exception e) { + logger.warn(String.format("Failed to finish the migration of the volume %s to the pool %s after the block copy was pivoted: %s", + destVolumeObjectTO.getPath(), destPool.getUuid(), e.getMessage()), e); + } + } else if (answer != null) { + libvirtComputingResource.createOrUpdateLogFileForCommand(command, Command.State.FAILED); + } + return answer; + } catch (Exception e) { + if (pivoted) { + // the Instance already uses the destination volume: report the migration as done, as it is + logger.warn(String.format("Ignoring %s after the block copy of the volume %s was pivoted", e.toString(), destVolumeObjectTO.getPath()), e); + return answer; + } + String msg = "Migrate volume failed due to " + e.toString(); + logger.warn(msg, e); + if (destDiskLabel != null) { + try { + dm.blockJobAbort(destDiskLabel, Domain.BlockJobAbortFlags.ASYNC); + } catch (LibvirtException ex) { + logger.error("Migrate volume failed while aborting the block job due to " + ex.getMessage()); + } + } + libvirtComputingResource.createOrUpdateLogFileForCommand(command, Command.State.FAILED); + answer = new MigrateVolumeAnswer(command, false, msg, null); + return answer; + } finally { + if (cancelHook != null) { + libvirtComputingResource.removeDisconnectHook(cancelHook); + } + if (destVolumeCreated && (answer == null || !answer.getResult())) { + deleteDestinationVolume(destKvmPool, destPool, destVolumeObjectTO.getPath()); + } + if (pivoted) { + // Remove old volume after successful migration. The Instance uses the destination volume already, so a + // failure to remove the source one is only logged: it must not turn the migration into a failure. + try { + KVMStoragePool libvirtSourcePool = storagePoolMgr.getStoragePool(sourcePool.getPoolType(), sourcePool.getUuid()); + Storage.ImageFormat srcFormat = Objects.equals(Storage.StoragePoolType.RBD, sourcePool.getPoolType()) + ? Storage.ImageFormat.RAW : Storage.ImageFormat.QCOW2; + libvirtSourcePool.deletePhysicalDisk(srcVolumeObjectTO.getPath(), srcFormat); + } catch (Exception e) { + logger.warn(String.format("Failed to remove the source volume %s from the pool %s after it was migrated: %s. It has to be removed manually", + srcVolumeObjectTO.getPath(), sourcePool.getUuid(), e.getMessage()), e); + } + } + if (dm != null) { + try { + dm.free(); + } catch (LibvirtException l) { + logger.trace("Ignoring libvirt error.", l); + } + } + } + } + + + /** + * Returns the size of an encrypted volume as the Instance sees it, which the destination of the block copy must + * have as well: an RBD image keeps its LUKS2 header in front of the data, a QCOW2 file keeps it apart from them. + */ + protected long getEncryptedVolumeSize(KVMStoragePool kvmStoragePool, PrimaryDataStoreTO dataStore, String path) { + if (Objects.equals(Storage.StoragePoolType.RBD, dataStore.getPoolType())) { + return LibvirtStorageAdaptor.getEncryptedRbdVolumeSize(kvmStoragePool, path); + } + return kvmStoragePool.getPhysicalDisk(path).getVirtualSize(); + } + + /** + * Creates the (empty) destination volume of a live migration of an encrypted volume, with its encryption + * header, so that the block copy can write into it. An RBD volume gets a native librbd LUKS2 header, a volume + * on a file based pool is a qemu LUKS encrypted QCOW2 file. Either one is created with room for its header, + * so that the Instance sees the given size. + * + * @param guestSize size of the disk as seen by the Instance + */ + protected void createEncryptedDestinationVolume(KVMStoragePool pool, PrimaryDataStoreTO destPool, VolumeObjectTO destVolumeObjectTO, long guestSize) { + String path = destVolumeObjectTO.getPath(); + // a previous failed attempt may have left the volume behind + deleteDestinationVolume(pool, destPool, path); + PhysicalDiskFormat format = Objects.equals(Storage.StoragePoolType.RBD, destPool.getPoolType()) ? PhysicalDiskFormat.RAW : PhysicalDiskFormat.QCOW2; + pool.createPhysicalDisk(path, format, Storage.ProvisioningType.THIN, guestSize, destVolumeObjectTO.getPassphrase()); + } + + protected void deleteDestinationVolume(KVMStoragePool pool, PrimaryDataStoreTO destPool, String path) { + if (pool == null) { + return; + } + try { + pool.deletePhysicalDisk(path, Objects.equals(Storage.StoragePoolType.RBD, destPool.getPoolType()) + ? Storage.ImageFormat.RAW : Storage.ImageFormat.QCOW2); + } catch (Exception e) { + logger.debug("Could not remove the destination volume {} (it may not exist): {}", path, e.getMessage()); + } + } + + /** + * Returns the path of the volume as it is referenced in the XML domain of the Instance on this host. RBD volumes + * are addressed as "/", while file based volumes (e.g. NFS) are addressed by their path on the + * local mount point of the pool. + */ + protected String generateVolumePathOnHost(KVMStoragePool kvmStoragePool, PrimaryDataStoreTO dataStore, VolumeObjectTO volumeObjectTO) { + if (Objects.equals(Storage.StoragePoolType.RBD, dataStore.getPoolType())) { + return String.format("%s/%s", dataStore.getPath(), volumeObjectTO.getPath()); + } + return String.format("%s/%s", kvmStoragePool.getLocalPath(), volumeObjectTO.getPath()); + } + + /** + * Generates the XML of the destination disk used by the libvirt block copy. The source disk is located in the XML + * domain of the Instance by its current path, and is then rewritten to point at the destination pool. Both an RBD + * (network) and an NFS (file) destination are supported, independently of the type of the source disk. + */ + /** + * Build the mirror disk XML handed to {@code blockCopy} from the disk the volume currently uses. + * + * @param shallowBlockCopy whether the copy will run with {@code VIR_DOMAIN_BLOCK_COPY_SHALLOW}, which decides + * whether the source's backing chain may be carried over to the mirror. + */ + protected String generateDestinationDiskXMLForRBD(Domain dm, String srcVolumePath, String diskFilePath, String destSecretUUID, KVMStoragePool pool, + Storage.StoragePoolType destPoolType, boolean shallowBlockCopy) + throws LibvirtException, ParserConfigurationException, IOException, TransformerException, SAXException { + final String domXml = dm.getXMLDesc(0); + + DocumentBuilderFactory dbFactory = ParserUtils.getSaferDocumentBuilderFactory(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(new ByteArrayInputStream(domXml.getBytes("UTF-8"))); + doc.getDocumentElement().normalize(); + + NodeList disks = doc.getElementsByTagName("disk"); + + for (int i = 0; i < disks.getLength(); i++) { + Node diskNode = disks.item(i); + if (!isDiskNodeOfVolume(diskNode, srcVolumePath)) { + continue; + } + + logger.debug(String.format("Found disk node with source volume path %s, generating destination disk XML for %s on %s", srcVolumePath, diskFilePath, + destPoolType)); + updateDiskNodeForDestinationPool(doc, diskNode, diskFilePath, destSecretUUID, pool, destPoolType, shallowBlockCopy); + + StringWriter diskSection = new StringWriter(); + Transformer xformer = TransformerFactory.newInstance().newTransformer(); + xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + xformer.transform(new DOMSource(diskNode), new StreamResult(diskSection)); + + return diskSection.toString(); + } + return null; + } + + /** + * True if the disk node is the one backing the volume with the given path, be it an RBD (network) or a file disk. + */ + protected boolean isDiskNodeOfVolume(Node diskNode, String srcVolumePath) { + Node diskTypeAttribute = diskNode.getAttributes().getNamedItem("type"); + if (diskTypeAttribute == null) { + return false; + } + String diskType = diskTypeAttribute.getNodeValue(); + boolean networkDisk = LibvirtVMDef.DiskDef.DiskType.NETWORK.toString().equalsIgnoreCase(diskType); + boolean fileDisk = LibvirtVMDef.DiskDef.DiskType.FILE.toString().equalsIgnoreCase(diskType); + if (!networkDisk && !fileDisk) { + return false; + } + + Node sourceNode = getChildNode(diskNode, "source"); + if (sourceNode == null) { + return false; + } + NamedNodeMap sourceAttributes = sourceNode.getAttributes(); + + if (networkDisk) { + Node protocolAttribute = sourceAttributes.getNamedItem("protocol"); + if (protocolAttribute == null || !protocolAttribute.getNodeValue().equalsIgnoreCase(LibvirtVMDef.DiskDef.DiskProtocol.RBD.toString())) { + logger.debug("Skipped disk node with protocol: " + protocolAttribute); + return false; + } + Node nameAttribute = sourceAttributes.getNamedItem("name"); + return nameAttribute != null && nameAttribute.getNodeValue().contains(srcVolumePath); + } + + Node fileAttribute = sourceAttributes.getNamedItem("file"); + return fileAttribute != null && fileAttribute.getNodeValue().contains(srcVolumePath); + } + + /** + * Rewrites the disk node so that it refers to the volume on the destination pool. The disk type, the source, the + * driver type and the Ceph authentication are all adjusted to what the destination pool requires. + */ + protected void updateDiskNodeForDestinationPool(Document doc, Node diskNode, String diskFilePath, String destSecretUUID, KVMStoragePool pool, + Storage.StoragePoolType destPoolType, boolean shallowBlockCopy) { + boolean destinationOnRbd = Objects.equals(Storage.StoragePoolType.RBD, destPoolType); + + Element diskElement = (Element)diskNode; + diskElement.setAttribute("type", destinationOnRbd ? LibvirtVMDef.DiskDef.DiskType.NETWORK.toString().toLowerCase() + : LibvirtVMDef.DiskDef.DiskType.FILE.toString().toLowerCase()); + + Node sourceNode = getChildNode(diskNode, "source"); + if (sourceNode != null) { + diskNode.removeChild(sourceNode); + } + diskNode.appendChild(destinationOnRbd ? createRbdSourceNode(doc, diskFilePath, pool) : createFileSourceNode(doc, diskFilePath)); + + // A disk cloned from a template keeps that template as its backing file, and libvirt reports the whole + // chain in the live domain XML. Only a shallow copy may carry that chain into the mirror: a full copy + // flattens every layer into the destination, so a there describes a chain the destination + // does not have. libvirt refuses that combination outright with "backingStore of mirror without + // VIR_DOMAIN_BLOCK_COPY_SHALLOW doesn't make sense", which is why the element is dropped here. + if (!shallowBlockCopy) { + Node backingStoreNode = getChildNode(diskNode, "backingStore"); + if (backingStoreNode != null) { + diskNode.removeChild(backingStoreNode); + } + } + + Node driverNode = getChildNode(diskNode, "driver"); + if (driverNode instanceof Element) { + // RBD volumes are raw, whereas volumes on a file based pool are qcow2 + ((Element)driverNode).setAttribute("type", destinationOnRbd ? "raw" : "qcow2"); + } + + // The Ceph authentication of the source pool does not apply to the destination pool, so it is always replaced + Node authNode = getChildNode(diskNode, "auth"); + if (authNode != null) { + diskNode.removeChild(authNode); + } + if (destinationOnRbd && StringUtils.isNotBlank(pool.getAuthUserName())) { + diskNode.appendChild(createAuthNode(doc, pool)); + } + + if (StringUtils.isNotBlank(destSecretUUID)) { + Node encryptionNode = getChildNode(diskNode, "encryption"); + if (encryptionNode instanceof Element) { + // librbd encrypts an RBD image natively (LUKS2), a file is encrypted by qemu (LUKS) + Element encryptionElement = (Element)encryptionNode; + if (destinationOnRbd) { + encryptionElement.setAttribute("format", "luks2"); + encryptionElement.setAttribute("engine", "librbd"); + } else { + encryptionElement.setAttribute("format", "luks"); + encryptionElement.removeAttribute("engine"); + } + } + if (encryptionNode != null) { + Node secretNode = getChildNode(encryptionNode, "secret"); + if (secretNode != null) { + Node uuidAttribute = secretNode.getAttributes().getNamedItem("uuid"); + if (uuidAttribute != null) { + uuidAttribute.setTextContent(destSecretUUID); + } + } + } + } + } + + protected Element createRbdSourceNode(Document doc, String diskFilePath, KVMStoragePool pool) { + Element sourceNode = doc.createElement("source"); + sourceNode.setAttribute("protocol", LibvirtVMDef.DiskDef.DiskProtocol.RBD.toString().toLowerCase()); + sourceNode.setAttribute("name", diskFilePath); + for (String sourceHost : pool.getSourceHost().split(",")) { + Element hostNode = doc.createElement("host"); + hostNode.setAttribute("name", sourceHost); + if (pool.getSourcePort() != 0) { + hostNode.setAttribute("port", String.valueOf(pool.getSourcePort())); + } + sourceNode.appendChild(hostNode); + } + return sourceNode; + } + + protected Element createFileSourceNode(Document doc, String diskFilePath) { + Element sourceNode = doc.createElement("source"); + sourceNode.setAttribute("file", diskFilePath); + return sourceNode; + } + + protected Element createAuthNode(Document doc, KVMStoragePool pool) { + Element authNode = doc.createElement("auth"); + authNode.setAttribute("username", pool.getAuthUserName()); + Element secretNode = doc.createElement("secret"); + secretNode.setAttribute("type", "ceph"); + secretNode.setAttribute("uuid", pool.getAuthSecretUUID()); + authNode.appendChild(secretNode); + return authNode; + } + + protected Node getChildNode(Node parent, String nodeName) { + NodeList childNodes = parent.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node childNode = childNodes.item(i); + if (nodeName.equals(childNode.getNodeName())) { + return childNode; + } + } + return null; + } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java index 7d02c728b526..1f51ab65229f 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java @@ -25,6 +25,7 @@ import java.util.Map; import org.apache.cloudstack.storage.configdrive.ConfigDrive; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.commons.collections.MapUtils; import org.libvirt.Connect; @@ -44,9 +45,11 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.GuestNetType; import com.cloud.hypervisor.kvm.resource.VifDriver; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.KVMStorageProcessor; import com.cloud.network.Networks; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; +import com.cloud.storage.Storage; import com.cloud.storage.Volume; import com.cloud.utils.exception.CloudRuntimeException; @@ -113,6 +116,11 @@ public Answer execute(final PrepareForMigrationCommand command, final LibvirtCom final VolumeObjectTO volumeObjectTO = (VolumeObjectTO)data; if (volumeObjectTO.requiresEncryption()) { + Answer refusal = refuseIfDestinationCannotHotplugEncryptedRbd(command, vm, volume, volumeObjectTO, libvirtComputingResource); + if (refusal != null) { + return refusal; + } + String secretConsumer = volumeObjectTO.getPath(); if (volume.getDetails() != null && volume.getDetails().containsKey(DiskTO.SECRET_CONSUMER_DETAIL)) { secretConsumer = volume.getDetails().get(DiskTO.SECRET_CONSUMER_DETAIL); @@ -182,6 +190,29 @@ protected PrepareForMigrationAnswer createPrepareForMigrationAnswer(PrepareForMi return answer; } + /** + * Refuses the migration if {@code volumeObjectTO} is encrypted, lands on RBD, and this (destination) host's + * libvirt is too old to hot-plug an encrypted RBD volume (checked before its libvirt secret is even created). + * Prefers {@link DiskTO#MIGRATION_DEST_POOL_TYPE} over the volume's own pool, which still reports its source + * pool here if it is migrating to a new one. + * + * @return a failed {@link PrepareForMigrationAnswer}, or {@code null} if the migration may proceed. + */ + protected Answer refuseIfDestinationCannotHotplugEncryptedRbd(PrepareForMigrationCommand command, VirtualMachineTO vm, DiskTO volume, + VolumeObjectTO volumeObjectTO, LibvirtComputingResource libvirtComputingResource) { + String destPoolTypeDetail = volume.getDetails() != null ? volume.getDetails().get(DiskTO.MIGRATION_DEST_POOL_TYPE) : null; + Storage.StoragePoolType destPoolType = destPoolTypeDetail != null ? Storage.StoragePoolType.valueOf(destPoolTypeDetail) + : volumeObjectTO.getDataStore() instanceof PrimaryDataStoreTO ? ((PrimaryDataStoreTO) volumeObjectTO.getDataStore()).getPoolType() : null; + if (!Storage.StoragePoolType.RBD.equals(destPoolType) + || libvirtComputingResource.getHypervisorLibvirtVersion() >= KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG) { + return null; + } + return new PrepareForMigrationAnswer(command, String.format("Libvirt version %s required on this host to migrate Instance %s into an" + + " encrypted RBD volume, but version %s detected. Stop the Instance to migrate it, or upgrade libvirt on this host.", + LibvirtComputingResource.prettyVersion(KVMStorageProcessor.MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG), vm.getName(), + LibvirtComputingResource.prettyVersion(libvirtComputingResource.getHypervisorLibvirtVersion()))); + } + private Answer handleRollback(PrepareForMigrationCommand command, LibvirtComputingResource libvirtComputingResource) { KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr(); VirtualMachineTO vmTO = command.getVirtualMachine(); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java index 32e756607e55..06906f3b8595 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java @@ -48,6 +48,7 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor; import com.cloud.hypervisor.kvm.storage.MultipathNVMeOFPool; import com.cloud.hypervisor.kvm.storage.MultipathSCSIPool; import com.cloud.resource.CommandWrapper; @@ -187,7 +188,9 @@ notify the guest in one step (no passphrase needed, qemu already has the secret /* fetch new size as seen from libvirt, don't want to assume anything */ pool = storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid()); pool.refresh(); - final long finalSize = pool.getPhysicalDisk(volumeId).getVirtualSize(); + // an encrypted RBD image keeps its LUKS2 header in front of the data, which is not part of the size of the volume + final long finalSize = rbdEncrypted ? LibvirtStorageAdaptor.getEncryptedRbdVolumeSize(pool, volumeId) + : pool.getPhysicalDisk(volumeId).getVirtualSize(); logger.debug("after resize, size reports as: " + toHumanReadableSize(finalSize) + ", requested: " + toHumanReadableSize(newSize)); return new ResizeVolumeAnswer(command, true, "success", finalSize); } catch (final CloudRuntimeException e) { diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertSnapshotCommandWrapper.java index e27b8460f624..2c3906e3b574 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertSnapshotCommandWrapper.java @@ -47,11 +47,11 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; +import com.cloud.hypervisor.kvm.storage.LibvirtStorageAdaptor; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; import com.cloud.storage.DataStoreRole; import com.cloud.storage.Storage.StoragePoolType; -import com.cloud.utils.RbdUtils; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; @@ -65,11 +65,6 @@ @ResourceWrapper(handles = RevertSnapshotCommand.class) public class LibvirtRevertSnapshotCommandWrapper extends CommandWrapper { - private static final String MON_HOST = "mon_host"; - private static final String KEY = "key"; - private static final String CLIENT_MOUNT_TIMEOUT = "client_mount_timeout"; - private static final String RADOS_CONNECTION_TIMEOUT = "30"; - protected Set storagePoolTypesThatSupportRevertSnapshot = new HashSet<>(Arrays.asList(StoragePoolType.RBD, StoragePoolType.Filesystem, StoragePoolType.NetworkFilesystem, StoragePoolType.SharedMountPoint)); @@ -96,11 +91,7 @@ public Answer execute(final RevertSnapshotCommand command, final LibvirtComputin KVMStoragePool primaryPool = snapshotDisk.getPool(); if (primaryPool.getType() == StoragePoolType.RBD) { - Rados rados = new Rados(primaryPool.getAuthUserName()); - rados.confSet(MON_HOST, RbdUtils.getRbdMonitors(primaryPool.getSourceHost(), primaryPool.getSourcePort())); - rados.confSet(KEY, primaryPool.getAuthSecret()); - rados.confSet(CLIENT_MOUNT_TIMEOUT, RADOS_CONNECTION_TIMEOUT); - rados.connect(); + Rados rados = LibvirtStorageAdaptor.connectToCeph(primaryPool); String[] rbdPoolAndVolumeAndSnapshot = snapshotRelPath.split("/"); int snapshotIndex = rbdPoolAndVolumeAndSnapshot.length - 1; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePool.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePool.java index 64aea9e8cee5..4b03fa82716f 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePool.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePool.java @@ -198,6 +198,10 @@ default LibvirtVMDef.DiskDef.BlockIOSize getSupportedPhysicalBlockSize() { default void customizeLibvirtDiskDef(LibvirtVMDef.DiskDef disk) { } + default String getAuthSecretUUID() { + return null; + } + /** * Whether the volume {@code volumeUuid}, freshly created in this pool, already reads as zeroes, * so a copy onto it may skip zero regions (qemu-img --target-is-zero). Says nothing about a diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java index 9cc3a754c7f6..62f678b7a9c9 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java @@ -42,6 +42,7 @@ import com.cloud.hypervisor.kvm.resource.KVMHABase; import com.cloud.hypervisor.kvm.resource.KVMHABase.PoolType; import com.cloud.hypervisor.kvm.resource.KVMHAMonitor; +import com.cloud.storage.StoragePoolInformation; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java index b9a85806c8ea..a5e00bfe1843 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java @@ -157,7 +157,6 @@ import com.cloud.storage.template.QCOW2Processor; import com.cloud.storage.template.TemplateConstants; import com.cloud.storage.template.TemplateLocation; -import com.cloud.utils.RbdUtils; import com.cloud.utils.Pair; import com.cloud.utils.UriUtils; import com.cloud.utils.exception.CloudRuntimeException; @@ -180,16 +179,12 @@ public class KVMStorageProcessor implements StorageProcessor { private static final String MANAGE_SNAPSTHOT_CREATE_OPTION = "-c"; private static final String NAME_OPTION = "-n"; - private static final String CEPH_MON_HOST = "mon_host"; - private static final String CEPH_AUTH_KEY = "key"; - private static final String CEPH_CLIENT_MOUNT_TIMEOUT = "client_mount_timeout"; - private static final String CEPH_DEFAULT_MOUNT_TIMEOUT = "30"; // libvirt < 10.1.0 has an object apply-order bug (fixed in 10.1.0) that breaks hot-plug of an encrypted // blockdev: on attach the disk is opened before its LUKS secret object is defined, so the attach fails with // "No secret with id '...-format-encryption-secret0'". Booting a VM from an encrypted disk is unaffected (the // QEMU command line resolves all -object before -blockdev). See qemuBlockStorageSourceAttachApply() in libvirt. - private static final long MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG = 10001000L; // libvirt 10.1.0 + public static final long MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG = 10001000L; // libvirt 10.1.0 /** * Time interval before rechecking virsh commands */ @@ -666,7 +661,8 @@ public Answer copyVolumeFromImageCacheToPrimary(final CopyCommand cmd) { final KVMPhysicalDisk volume = secondaryStoragePool.getPhysicalDisk(srcVolumeName); - volume.setFormat(PhysicalDiskFormat.valueOf(srcFormat.toString())); + // the file tells the format: a volume from RBD or CLVM is RAW, but its copy on secondary storage is qcow2 + volume.setFormat(srcVolumeName.endsWith(".qcow2") ? PhysicalDiskFormat.QCOW2 : PhysicalDiskFormat.valueOf(srcFormat.toString())); volume.setDispName(srcVol.getName()); volume.setVmName(srcVol.getVmName()); @@ -1819,7 +1815,7 @@ protected void ensureLibvirtSupportsEncryptedRbdHotplug(StoragePoolType poolType if (poolType == StoragePoolType.RBD && resource.getHypervisorLibvirtVersion() < MIN_LIBVIRT_VERSION_FOR_RBD_ENCRYPTED_HOTPLUG) { throw new CloudRuntimeException("Libvirt version 10.1.0 required to attach an encrypted RBD volume to a running VM, but version " - + resource.getHypervisorLibvirtVersion() + " detected. Booting a VM from an encrypted RBD disk is not affected."); + + LibvirtComputingResource.prettyVersion(resource.getHypervisorLibvirtVersion()) + " detected. Booting a VM from an encrypted RBD disk is not affected."); } } @@ -1934,8 +1930,12 @@ protected KVMPhysicalDisk createLinkedCloneVolume(MigrationOptions migrationOpti * Create full clone volume from VM snapshot */ protected KVMPhysicalDisk createFullCloneVolume(MigrationOptions migrationOptions, VolumeObjectTO volume, KVMStoragePool primaryPool, PhysicalDiskFormat format) { - logger.debug("For VM migration with full-clone volume: Creating empty stub disk for source disk " + migrationOptions.getSrcVolumeUuid() + " and size: " + toHumanReadableSize(volume.getSize()) + " and format: " + format); - return primaryPool.createPhysicalDisk(volume.getUuid(), format, volume.getProvisioningType(), volume.getSize(), volume.getPassphrase()); + // The Instance sees the size of the volume on every pool type: an encrypted volume is created with room for its + // encryption header, on RBD as on a file based pool. So the declared size is the size of the source disk, which + // the host creating the destination may not even reach (a local pool, or a pool of another cluster). + long size = volume.getSize(); + logger.debug("For VM migration with full-clone volume: Creating empty stub disk for source disk " + migrationOptions.getSrcVolumeUuid() + " and size: " + toHumanReadableSize(size) + " and format: " + format); + return primaryPool.createPhysicalDisk(volume.getUuid(), format, volume.getProvisioningType(), size, volume.getPassphrase()); } @Override @@ -2610,7 +2610,7 @@ protected Long takeRbdVolumeSnapshotOfStoppedVm(KVMStoragePool primaryPool, KVMP Rbd rbd = null; RbdImage image = null; try { - r = radosConnect(primaryPool); + r = LibvirtStorageAdaptor.connectToCeph(primaryPool); io = r.ioCtxCreate(primaryPool.getSourceDir()); rbd = new Rbd(io); @@ -2919,16 +2919,6 @@ protected boolean isAvailablePoolSizeDividedByDiskSizeLesserThanMinRate(long ava return ((availablePoolSize * 1d) / (diskSize * 1d)) < MIN_RATE_BETWEEN_AVAILABLE_POOL_AND_DISK_SIZE_TO_TAKE_DISK_SNAPSHOT; } - protected Rados radosConnect(final KVMStoragePool primaryPool) throws RadosException { - Rados r = new Rados(primaryPool.getAuthUserName()); - r.confSet(CEPH_MON_HOST, RbdUtils.getRbdMonitors(primaryPool.getSourceHost(), primaryPool.getSourcePort())); - r.confSet(CEPH_AUTH_KEY, primaryPool.getAuthSecret()); - r.confSet(CEPH_CLIENT_MOUNT_TIMEOUT, CEPH_DEFAULT_MOUNT_TIMEOUT); - r.connect(); - logger.debug("Successfully connected to Ceph cluster at " + r.confGet(CEPH_MON_HOST)); - return r; - } - /** * Closes an RBD image if it was opened; never throws. An image left open keeps this client's RBD * exclusive-lock, which later makes 'rbd snap rollback' (revertSnapshot) fail with EROFS and keeps @@ -3137,11 +3127,7 @@ private KVMPhysicalDisk createRBDvolumeFromRBDSnapshot(KVMPhysicalDisk volume, S try { - r = new Rados(srcPool.getAuthUserName()); - r.confSet("mon_host", RbdUtils.getRbdMonitors(srcPool.getSourceHost(), srcPool.getSourcePort())); - r.confSet("key", srcPool.getAuthSecret()); - r.confSet("client_mount_timeout", "30"); - r.connect(); + r = LibvirtStorageAdaptor.connectToCeph(srcPool); io = r.ioCtxCreate(srcPool.getSourceDir()); rbd = new Rbd(io); @@ -3200,7 +3186,7 @@ public Answer deleteSnapshot(final DeleteCommand cmd) { if (primaryPool.getType() == StoragePoolType.RBD) { KVMPhysicalDisk disk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volume.getPath()); snapshotFullName = disk.getName() + "@" + snapshotName; - Rados r = radosConnect(primaryPool); + Rados r = LibvirtStorageAdaptor.connectToCeph(primaryPool); IoCTX io = r.ioCtxCreate(primaryPool.getSourceDir()); Rbd rbd = new Rbd(io); RbdImage image = rbd.open(disk.getName()); @@ -3401,6 +3387,16 @@ public Answer handleDownloadTemplateToPrimaryStorage(DirectDownloadCommand cmd) return new DirectDownloadAnswer(true, template.getSize(), template.getName()); } + /** + * CLVM and CLVM_NG volumes are named after the logical volume, without a file extension. The name of an RBD image + * survives an online migration to a file based pool, where the block copy writes a qcow2 file, so a ".raw" + * extension would outlive the format it names. + */ + protected String generateVolumeName(StoragePoolType poolType, ImageFormat format) { + String volumeName = UUID.randomUUID().toString(); + return ClvmPoolManager.isClvmPoolType(poolType) || StoragePoolType.RBD.equals(poolType) ? volumeName : volumeName + "." + format.getFileExtension(); + } + @Override public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { final DataTO srcData = cmd.getSrcTO(); @@ -3454,8 +3450,7 @@ public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { } else { PhysicalDiskFormat destPoolDefaultFormat = destPool.getDefaultFormat(); destFormat = getFormat(destPoolDefaultFormat); - final String volumeName = UUID.randomUUID().toString(); - destVolumeName = volumeName + "." + destFormat.getFileExtension(); + destVolumeName = generateVolumeName(destPrimaryStore.getPoolType(), destFormat); // Update path in the command for reconciliation if (StringUtils.isBlank(destVolumePath)) { @@ -3498,7 +3493,8 @@ public Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd) { newVol.setPath(path); ImageFormat newVolumeFormat = getFormat(newVolume.getFormat()); newVol.setFormat(newVolumeFormat); - newVol.setEncryptFormat(destVol.getEncryptFormat()); + // an encrypted volume copied to another kind of pool is encrypted differently (librbd LUKS2 on RBD, qemu LUKS otherwise) + newVol.setEncryptFormat(newVolume.getQemuEncryptFormat() != null ? newVolume.getQemuEncryptFormat().toString() : destVol.getEncryptFormat()); return new CopyCmdAnswer(newVol); } catch (final CloudRuntimeException e) { logger.debug("Failed to copyVolumeFromPrimaryToPrimary: ", e); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java index 3fdaaf8430a6..7cb18a72b17e 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java @@ -21,8 +21,12 @@ import java.io.File; import java.io.IOException; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; import java.util.Arrays; +import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -45,6 +49,7 @@ import org.apache.cloudstack.utils.qemu.QemuObject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -98,12 +103,19 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { private static final int RBD_FEATURE_DEEP_FLATTEN = 32; public static final int RBD_FEATURES = RBD_FEATURE_LAYERING + RBD_FEATURE_EXCLUSIVE_LOCK + RBD_FEATURE_OBJECT_MAP + RBD_FEATURE_FAST_DIFF + RBD_FEATURE_DEEP_FLATTEN; private int rbdOrder = 0; /* Order 0 means 4MB blocks (the default) */ - /* Space reserved at the front of an encrypted RBD image for the LUKS2 header/keyslots so the - usable (decrypted) size still matches the requested volume size. */ - private static final long LUKS2_HEADER_RESERVE_BYTES = 16L << 20; // 16 MiB + /* Size of the LUKS2 header (and keyslots) librbd keeps at the front of an encrypted RBD image with objects of + up to 16 MiB, see getRbdLuks2HeaderSize(long). The image is made larger than the volume by the size of its + header, so that the Instance sees the size of the volume, as it does on every other pool type. */ + public static final long LUKS2_HEADER_RESERVE_BYTES = 16L << 20; // 16 MiB /* libvirt's VIR_STORAGE_VOL_DELETE_WITH_SNAPSHOTS, not exposed as a constant by libvirt-java */ private static final int VIR_STORAGE_VOL_DELETE_WITH_SNAPSHOTS = 2; + /* pool types an encrypted volume can be copied between, see copyEncryptedPhysicalDisk */ + private static final Set ENCRYPTED_COPY_POOL_TYPES = Set.of(StoragePoolType.RBD, StoragePoolType.NetworkFilesystem, + StoragePoolType.Filesystem, StoragePoolType.SharedMountPoint); + private static final String SRC_LUKS_SECRET_ID = "srcsec0"; + private static final String DEST_LUKS_SECRET_ID = "destsec0"; + private static final Set QEMU_IMG_MANAGED_POOL_TYPES = Set.of(StoragePoolType.NetworkFilesystem, StoragePoolType.Filesystem, StoragePoolType.SharedMountPoint); public LibvirtStorageAdaptor(StorageLayer storage) { @@ -608,6 +620,7 @@ public KVMStoragePool getStoragePool(String uuid, boolean refreshInfo) { pool.setAuthSecret(secretValue); } } + pool.setAuthSecretUUID(spd.getSecretUUID()); /** * On large (RBD) storage pools it can take up to a couple of minutes @@ -710,21 +723,9 @@ public KVMPhysicalDisk getPhysicalDisk(String volumeUuid, KVMStoragePool pool) { * an RBD volume. */ private KVMPhysicalDisk getRbdPhysicalDisk(String volumeUuid, LibvirtStoragePool pool) { - Rados r = new Rados(pool.getAuthUserName()); + Rados r = null; try { - r.confSet("mon_host", pool.getSourceHost() + ":" + pool.getSourcePort()); - /* - * The secret is null when the pool has no cephx user, and librados - * aborts the process rather than returning an error if it is handed a - * null value here. - */ - if (pool.getAuthUserName() != null) { - r.confSet("key", pool.getAuthSecret()); - } else { - r.confSet("auth_client_required", "none"); - } - r.confSet("client_mount_timeout", "30"); - r.connect(); + r = connectToCeph(pool); IoCTX io = r.ioCtxCreate(pool.getSourceDir()); try { @@ -753,7 +754,91 @@ private KVMPhysicalDisk getRbdPhysicalDisk(String volumeUuid, LibvirtStoragePool + " - " + ErrorCode.getErrorMessage(e.getReturnValue())); throw new CloudRuntimeException(e.toString(), e); } finally { - r.shutDown(); + if (r != null) { + r.shutDown(); + } + } + } + + /** + * Returns the size of the LUKS2 header librbd keeps at the front of an encrypted RBD image with objects of the given + * size: 16 MiB, or one object if the objects are larger, as librbd starts the data of the image on an object boundary. + */ + public static long getRbdLuks2HeaderSize(long objectSize) { + return Math.max(LUKS2_HEADER_RESERVE_BYTES, objectSize); + } + + /** + * Returns the size of an encrypted RBD volume as the Instance sees it: the size of its image without the LUKS2 header + * librbd keeps at the front of the image. + */ + public static long getEncryptedRbdVolumeSize(KVMStoragePool pool, String image) { + try { + Rados r = connectToCeph(pool); + try { + IoCTX io = r.ioCtxCreate(pool.getSourceDir()); + try { + Rbd rbd = new Rbd(io); + // The image is only stat'ed, so it is opened read only: a running Instance holds its exclusive lock. + RbdImage rbdImage = rbd.openReadOnly(image); + try { + RbdImageInfo info = rbdImage.stat(); + return info.size - getRbdLuks2HeaderSize(info.obj_size); + } finally { + try { + rbd.close(rbdImage); + } catch (RbdException ignored) { + // the size was read already, a failing close must not hide it + } + } + } finally { + r.ioCtxDestroy(io); + } + } finally { + r.shutDown(); + } + } catch (RadosException | RbdException e) { + throw new CloudRuntimeException(String.format("Failed to get the size of the encrypted RBD volume %s/%s: %s", + pool.getSourceDir(), image, e.getMessage()), e); + } + } + + /** + * Makes room for the LUKS2 header in front of the given size in a new RBD image, which was created with room for a + * header of {@link #LUKS2_HEADER_RESERVE_BYTES}: the image is grown if its objects are larger, as the header then + * takes one object (see {@link #getRbdLuks2HeaderSize(long)}). + */ + private void reserveRbdLuks2Header(KVMStoragePool pool, String image, long size) { + try { + Rados r = connectToCeph(pool); + try { + IoCTX io = r.ioCtxCreate(pool.getSourceDir()); + try { + reserveRbdLuks2Header(new Rbd(io), image, size); + } finally { + r.ioCtxDestroy(io); + } + } finally { + r.shutDown(); + } + } catch (RadosException | RbdException e) { + throw new CloudRuntimeException(String.format("Failed to make room for the encryption header in RBD image %s/%s: %s", + pool.getSourceDir(), image, e.getMessage()), e); + } + } + + private void reserveRbdLuks2Header(Rbd rbd, String image, long size) throws RbdException { + RbdImage rbdImage = rbd.open(image); + try { + RbdImageInfo info = rbdImage.stat(); + long imageSize = size + getRbdLuks2HeaderSize(info.obj_size); + if (info.size < imageSize) { + logger.debug("Growing RBD image {} to {}, as the encryption header of an image with objects of {} takes one object", + image, toHumanReadableSize(imageSize), toHumanReadableSize(info.obj_size)); + rbdImage.resize(imageSize); + } + } finally { + closeRbdImage(rbd, rbdImage, image); } } @@ -1080,11 +1165,16 @@ public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, // Create the raw RBD image first. For encrypted volumes we apply a native librbd LUKS header // afterwards via `rbd encryption format` (engine='librbd'). We deliberately do NOT hand the // passphrase to qemu-img, which would instead produce a qemu-native LUKS container. + // librbd keeps the header in the image, in front of the data, so the image of an encrypted volume + // is larger than the volume by the size of the header: the Instance then sees the size of the volume. + boolean encrypted = passphrase != null && passphrase.length > 0; + long imageSize = encrypted ? size + LUKS2_HEADER_RESERVE_BYTES : size; KVMPhysicalDisk disk = (dataPool == null) ? - createPhysicalDiskByLibVirt(name, pool, PhysicalDiskFormat.RAW, provisioningType, size) : - createPhysicalDiskByQemuImg(name, pool, PhysicalDiskFormat.RAW, provisioningType, size, null); + createPhysicalDiskByLibVirt(name, pool, PhysicalDiskFormat.RAW, provisioningType, imageSize) : + createPhysicalDiskByQemuImg(name, pool, PhysicalDiskFormat.RAW, provisioningType, imageSize, null); - if (passphrase != null && passphrase.length > 0) { + if (encrypted) { + reserveRbdLuks2Header(pool, name, size); formatRbdImageEncryption(pool, name, passphrase); disk.setQemuEncryptFormat(QemuObject.EncryptFormat.LUKS2); } @@ -1269,6 +1359,64 @@ public boolean deletePhysicalDisk(String uuid, KVMStoragePool pool, Storage.Imag } } + static String maskRbdKey(String message) { + return message == null ? null : message.replaceAll("key=[^:\\s]*", "key=******"); + } + + public static Rados connectToCeph(KVMStoragePool pool) throws RadosException { + Rados r = new Rados(pool.getAuthUserName()); + r.confSet("mon_host", RbdUtils.getRbdMonitors(pool.getSourceHost(), pool.getSourcePort())); + // librados aborts the process rather than returning an error if it is handed a null key, which a pool without + // a cephx user has + if (pool.getAuthUserName() != null) { + r.confSet("key", pool.getAuthSecret()); + } else { + r.confSet("auth_client_required", "none"); + } + r.confSet("client_mount_timeout", "30"); + r.connect(); + return r; + } + + private boolean rbdImageExists(KVMStoragePool pool, String imageName) throws RadosException, RbdException { + Rados r = connectToCeph(pool); + try { + IoCTX io = r.ioCtxCreate(pool.getSourceDir()); + try { + return Arrays.asList(new Rbd(io).list()).contains(imageName); + } finally { + r.ioCtxDestroy(io); + } + } finally { + r.shutDown(); + } + } + + /** + * Removes an RBD image left behind by a failed copy, so that it does not make every later copy fail with "File exists" + */ + private void removeRbdImageQuietly(KVMStoragePool pool, String imageName) { + try { + Rados r = connectToCeph(pool); + try { + IoCTX io = r.ioCtxCreate(pool.getSourceDir()); + try { + Rbd rbd = new Rbd(io); + if (Arrays.asList(rbd.list()).contains(imageName)) { + rbd.remove(imageName); + logger.info("Removed the incomplete RBD image {}/{} left by the failed copy", pool.getSourceDir(), imageName); + } + } finally { + r.ioCtxDestroy(io); + } + } finally { + r.shutDown(); + } + } catch (RadosException | RbdException e) { + logger.warn("Failed to remove the incomplete RBD image {}/{} left by the failed copy, remove it manually: {}", pool.getSourceDir(), imageName, e.getMessage()); + } + } + /** * This function copies a physical disk from Secondary Storage to Primary Storage * or from Primary to Primary Storage @@ -1435,15 +1583,11 @@ private KVMPhysicalDisk createDiskFromTemplateOnRBD(KVMPhysicalDisk template, /* We are on the same Ceph cluster, but we require RBD format 2 on the source image */ logger.debug("Trying to perform a RBD clone (layering) since we are operating in the same storage pool"); - Rados r = new Rados(srcPool.getAuthUserName()); - r.confSet("mon_host", RbdUtils.getRbdMonitors(srcPool.getSourceHost(), srcPool.getSourcePort())); - r.confSet("key", srcPool.getAuthSecret()); - r.confSet("client_mount_timeout", "30"); + Rados r = connectToCeph(srcPool); if (dataPool != null) { logger.debug("Setting RBD data pool to " + dataPool + " for the new image " + disk.getName()); r.confSet(KVMPhysicalDisk.RBD_DEFAULT_DATA_POOL, dataPool); } - r.connect(); logger.debug("Successfully connected to Ceph cluster at " + r.confGet("mon_host")); IoCTX io = r.ioCtxCreate(srcPool.getSourceDir()); @@ -1508,22 +1652,14 @@ private KVMPhysicalDisk createDiskFromTemplateOnRBD(KVMPhysicalDisk template, /* The source pool or host is not the same Ceph cluster, we do a simple copy with Qemu-Img */ logger.debug("Both the source and destination are RBD, but not the same Ceph cluster. Performing a copy"); - Rados rSrc = new Rados(srcPool.getAuthUserName()); - rSrc.confSet("mon_host", RbdUtils.getRbdMonitors(srcPool.getSourceHost(), srcPool.getSourcePort())); - rSrc.confSet("key", srcPool.getAuthSecret()); - rSrc.confSet("client_mount_timeout", "30"); - rSrc.connect(); + Rados rSrc = connectToCeph(srcPool); logger.debug("Successfully connected to source Ceph cluster at " + rSrc.confGet("mon_host")); - Rados rDest = new Rados(destPool.getAuthUserName()); - rDest.confSet("mon_host", RbdUtils.getRbdMonitors(destPool.getSourceHost(), destPool.getSourcePort())); - rDest.confSet("key", destPool.getAuthSecret()); - rDest.confSet("client_mount_timeout", "30"); + Rados rDest = connectToCeph(destPool); if (dataPool != null) { logger.debug("Setting RBD data pool to " + dataPool + " on the destination cluster for the new image " + disk.getName()); rDest.confSet(KVMPhysicalDisk.RBD_DEFAULT_DATA_POOL, dataPool); } - rDest.connect(); logger.debug("Successfully connected to source Ceph cluster at " + rDest.confGet("mon_host")); IoCTX sIO = rSrc.ioCtxCreate(srcPool.getSourceDir()); @@ -1566,9 +1702,10 @@ private KVMPhysicalDisk createDiskFromTemplateOnRBD(KVMPhysicalDisk template, /** * Option A (thin CoW encrypted root), used when the template already lives on the same RBD cluster * as the destination pool. Per the Ceph "Image Encryption" clone recipe: grow the template base to - * reserve LUKS2-header space, snapshot+protect that grown state, clone from it, apply a LUKS2 header, - * then resize the clone to the requested size. The inherited (plaintext) template data stays readable - * through the clone's encryption, and the clone is a thin CoW image (only the header is written). + * reserve LUKS2-header space, snapshot+protect that grown state (the template itself is shrunk back), + * clone from it, apply a LUKS2 header, then resize the clone to the requested size. The inherited + * (plaintext) template data stays readable through the clone's encryption, and the clone is a thin CoW + * image (only the header is written). * * @return the encrypted CoW clone, or {@code null} if the Ceph operations failed */ @@ -1579,29 +1716,46 @@ private KVMPhysicalDisk createEncryptedRootCoWClone(KVMPhysicalDisk template, KV IoCTX ioContext = null; Rbd rbdClient = null; RbdImage templateImage = null; + long cloneSize; try { - radosConnection = new Rados(destPool.getAuthUserName()); - radosConnection.confSet("mon_host", RbdUtils.getRbdMonitors(destPool.getSourceHost(), destPool.getSourcePort())); - radosConnection.confSet("key", destPool.getAuthSecret()); - radosConnection.confSet("client_mount_timeout", "30"); - radosConnection.connect(); + radosConnection = connectToCeph(destPool); ioContext = radosConnection.ioCtxCreate(destPool.getSourceDir()); rbdClient = new Rbd(ioContext); templateImage = rbdClient.open(template.getName()); - boolean luksSnapshotExists = false; - for (RbdSnapInfo snapshotInfo : templateImage.snapList()) { - if (luksReservedSnapshotName.equals(snapshotInfo.name)) { - luksSnapshotExists = true; - break; + RbdSnapInfo existingSnapshot = findRbdSnapshot(templateImage, luksReservedSnapshotName); + Long luksSnapshotSize = existingSnapshot != null ? existingSnapshot.size : null; + if (luksSnapshotSize == null) { + // The template is grown by the size of the header only for the snapshot the encrypted clones are made of, + // and shrunk back right after: its unencrypted clones are made of its base snapshot, which may not exist + // yet, and must keep the size of the template. + RbdImageInfo templateInfo = templateImage.stat(); + long templateSize = templateInfo.size; + luksSnapshotSize = templateSize + getRbdLuks2HeaderSize(templateInfo.obj_size); + templateImage.resize(luksSnapshotSize); + try { + templateImage.snapCreate(luksReservedSnapshotName); + templateImage.snapProtect(luksReservedSnapshotName); + } catch (RbdException e) { + // Another deployment may have prepared the template in the meantime, possibly from the size this one + // saw while that one had the template grown: the size of its snapshot tells the size of the template + RbdSnapInfo preparedSnapshot = findRbdSnapshot(templateImage, luksReservedSnapshotName); + if (preparedSnapshot == null) { + throw e; + } + luksSnapshotSize = preparedSnapshot.size; + templateSize = luksSnapshotSize - getRbdLuks2HeaderSize(templateInfo.obj_size); + } finally { + templateImage.resize(templateSize); } - } - if (!luksSnapshotExists) { - templateImage.resize(template.getVirtualSize() + LUKS2_HEADER_RESERVE_BYTES); - templateImage.snapCreate(luksReservedSnapshotName); - templateImage.snapProtect(luksReservedSnapshotName); logger.debug("Prepared LUKS-reserved template snapshot {}@{}", template.getName(), luksReservedSnapshotName); } rbdClient.clone(template.getName(), luksReservedSnapshotName, ioContext, newUuid, RBD_FEATURES, rbdOrder); + RbdImage cloneImage = rbdClient.open(newUuid); + try { + cloneSize = luksSnapshotSize - getRbdLuks2HeaderSize(cloneImage.stat().obj_size); + } finally { + closeRbdImage(rbdClient, cloneImage, newUuid); + } } catch (RadosException | RbdException e) { logger.error("Failed to create encrypted CoW clone {}: {}", newUuid, e.getMessage()); return null; @@ -1618,16 +1772,26 @@ private KVMPhysicalDisk createEncryptedRootCoWClone(KVMPhysicalDisk template, KV } } formatRbdImageEncryption(destPool, newUuid, passphrase); - if (disk.getVirtualSize() > template.getVirtualSize()) { - // grow the clone to the requested root size (encryption-aware) + if (disk.getVirtualSize() != cloneSize) { + // the header of the clone follows its own object size, which may differ from the one the snapshot was + // sized with: grow or shrink the clone to the requested root size (encryption-aware) new RbdEncryption().resize(destPool.getSourceHost(), destPool.getSourcePort(), destPool.getAuthUserName(), destPool.getAuthSecret(), destPool.getSourceDir(), - newUuid, disk.getVirtualSize(), false, passphrase); + newUuid, disk.getVirtualSize(), disk.getVirtualSize() < cloneSize, passphrase); } disk.setQemuEncryptFormat(QemuObject.EncryptFormat.LUKS2); return disk; } + private static RbdSnapInfo findRbdSnapshot(RbdImage image, String snapshotName) throws RbdException { + for (RbdSnapInfo snapshotInfo : image.snapList()) { + if (snapshotName.equals(snapshotInfo.name)) { + return snapshotInfo; + } + } + return null; + } + /** * Option B (full-copy encrypted root), used when the template is not on the same RBD cluster (e.g. first * use from secondary storage). Create an empty image, apply a LUKS2 header, then import the template @@ -1641,14 +1805,11 @@ private KVMPhysicalDisk createEncryptedRootFullCopy(KVMStoragePool srcPool, KVMP Rados radosConnection = null; IoCTX ioContext = null; try { - radosConnection = new Rados(destPool.getAuthUserName()); - radosConnection.confSet("mon_host", RbdUtils.getRbdMonitors(destPool.getSourceHost(), destPool.getSourcePort())); - radosConnection.confSet("key", destPool.getAuthSecret()); - radosConnection.confSet("client_mount_timeout", "30"); - radosConnection.connect(); + radosConnection = connectToCeph(destPool); ioContext = radosConnection.ioCtxCreate(destPool.getSourceDir()); Rbd rbdClient = new Rbd(ioContext); rbdClient.create(newUuid, imageSizeWithLuksHeader, RBD_FEATURES, rbdOrder); + reserveRbdLuks2Header(rbdClient, newUuid, disk.getVirtualSize()); } catch (RadosException | RbdException e) { logger.error("Failed to create encrypted RBD image {}: {}", newUuid, e.getMessage()); return null; @@ -1725,6 +1886,13 @@ public KVMPhysicalDisk copyPhysicalDisk(KVMPhysicalDisk disk, String name, KVMSt */ KVMStoragePool srcPool = disk.getPool(); + if (ArrayUtils.isNotEmpty(srcPassphrase) && ENCRYPTED_COPY_POOL_TYPES.contains(srcPool.getType()) + && ENCRYPTED_COPY_POOL_TYPES.contains(destPool.getType())) { + // the volume keeps its passphrase when it is copied to another pool + return copyEncryptedPhysicalDisk(disk, name, destPool, timeout, srcPassphrase, + ArrayUtils.isNotEmpty(dstPassphrase) ? dstPassphrase : srcPassphrase); + } + /* Linstor images are always stored as RAW, but Linstor uses qcow2 in DB, to support snapshots(backuped) as qcow2 files. */ PhysicalDiskFormat sourceFormat = srcPool.getType() != StoragePoolType.Linstor ? @@ -1774,7 +1942,7 @@ to support snapshots(backuped) as qcow2 files. */ Map info = qemu.info(srcFile); String backingFile = info.get(QemuImg.BACKING_FILE); // qcow2 templates can just be copied into place - if (sourceFormat.equals(destFormat) && backingFile == null && sourcePath.endsWith(".qcow2")) { + if (sourceFormat.equals(destFormat) && PhysicalDiskFormat.QCOW2.equals(destFormat) && backingFile == null && sourcePath.endsWith(".qcow2")) { String result = Script.runSimpleBashScript("cp -f " + sourcePath + " " + destPath, timeout); if (result != null) { throw new CloudRuntimeException("Failed to create disk: " + result); @@ -1809,33 +1977,43 @@ to support snapshots(backuped) as qcow2 files. */ * To do so it's mandatory that librbd on the system is at least 0.67.7 (Ceph Dumpling) */ logger.debug("The source image is not RBD, but the destination is. We will convert into RBD format 2"); + String rbdDestPath = destPool.getSourceDir() + "/" + name; + // The copy is made into an image no other operation knows, which is renamed when it is complete: the rename + // fails if the image exists, so an image created by another operation is neither overwritten nor removed + String stagingName = name + ".copy-" + UUID.randomUUID(); + boolean destCreatedByCopy = false; try { srcFile = new QemuImgFile(sourcePath, sourceFormat); - String rbdDestPath = destPool.getSourceDir() + "/" + name; - String rbdDestFile = KVMPhysicalDisk.RBDStringBuilder(destPool, rbdDestPath); - destFile = new QemuImgFile(rbdDestFile, destFormat); + String rbdStagingPath = destPool.getSourceDir() + "/" + stagingName; + destFile = new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(destPool, rbdStagingPath), destFormat); + + if (rbdImageExists(destPool, name)) { + // don't touch it: qemu-img can't tell if the existing image is complete + logger.error("RBD image {} already exists, it will not be overwritten by the copy of {}", rbdDestPath, srcFile.getFileName()); + return null; + } + destCreatedByCopy = true; logger.debug("Starting copy from source image " + srcFile.getFileName() + " to RBD image " + rbdDestPath); qemu.convert(srcFile, destFile); logger.debug("Successfully converted source image " + srcFile.getFileName() + " to RBD image " + rbdDestPath); /* We have to stat the RBD image to see how big it became afterwards */ - Rados r = new Rados(destPool.getAuthUserName()); - r.confSet("mon_host", RbdUtils.getRbdMonitors(destPool.getSourceHost(), destPool.getSourcePort())); - r.confSet("key", destPool.getAuthSecret()); - r.confSet("client_mount_timeout", "30"); - r.connect(); + Rados r = connectToCeph(destPool); logger.debug("Successfully connected to Ceph cluster at " + r.confGet("mon_host")); IoCTX io = r.ioCtxCreate(destPool.getSourceDir()); Rbd rbd = new Rbd(io); - RbdImage image = rbd.open(name); + RbdImage image = rbd.open(stagingName); RbdImageInfo rbdInfo = image.stat(); newDisk.setSize(rbdInfo.size); newDisk.setVirtualSize(rbdInfo.size); logger.debug("After copy the resulting RBD image " + rbdDestPath + " is " + toHumanReadableSize(rbdInfo.size) + " bytes long"); rbd.close(image); + // fails, and leaves the image of the other operation alone, if it has been created in the meantime + rbd.rename(stagingName, name); + destCreatedByCopy = false; r.ioCtxDestroy(io); } catch (QemuImgException | LibvirtException e) { @@ -1843,12 +2021,21 @@ to support snapshots(backuped) as qcow2 files. */ String destFilename = destFile != null ? destFile.getFileName() : null; logger.error(String.format("Failed to convert from %s to %s the error was: %s", srcFilename, destFilename, e.getMessage())); newDisk = null; + if (destCreatedByCopy) { + removeRbdImageQuietly(destPool, stagingName); + } } catch (RadosException e) { logger.error("A Ceph RADOS operation failed (" + e.getReturnValue() + "). The error was: " + e.getMessage()); newDisk = null; + if (destCreatedByCopy) { + removeRbdImageQuietly(destPool, stagingName); + } } catch (RbdException e) { logger.error("A Ceph RBD operation failed (" + e.getReturnValue() + "). The error was: " + e.getMessage()); newDisk = null; + if (destCreatedByCopy) { + removeRbdImageQuietly(destPool, stagingName); + } } } else { /** @@ -1879,6 +2066,99 @@ to support snapshots(backuped) as qcow2 files. */ return newDisk; } + /** + * Copies an encrypted volume to another pool. The data is read through the encryption of the source and written + * through the encryption of the destination, which is created up front: an RBD image gets a native librbd LUKS2 + * header, a volume on a file based pool is a qemu LUKS encrypted QCOW2 file. Copying the encrypted data as is + * would not do: the destination may need another kind of encryption than the source, and an encrypted RBD clone + * reads the data it inherits from its (plaintext) parent unencrypted. Any backing chain of the source (an RBD + * parent or a QCOW2 backing file) is flattened into the destination. + */ + private KVMPhysicalDisk copyEncryptedPhysicalDisk(KVMPhysicalDisk disk, String name, KVMStoragePool destPool, int timeout, + byte[] srcPassphrase, byte[] dstPassphrase) { + KVMStoragePool srcPool = disk.getPool(); + boolean srcOnRbd = srcPool.getType() == StoragePoolType.RBD; + boolean destOnRbd = destPool.getType() == StoragePoolType.RBD; + // the size of the disk as seen by the Instance: an RBD image keeps its LUKS2 header in front of the data + long guestSize = srcOnRbd ? getEncryptedRbdVolumeSize(srcPool, disk.getName()) : disk.getVirtualSize(); + logger.debug("Copying encrypted volume {} from pool {} to {} in pool {}, with a size of {}", disk.getPath(), srcPool.getUuid(), + name, destPool.getUuid(), toHumanReadableSize(guestSize)); + + KVMPhysicalDisk newDisk = destPool.createPhysicalDisk(name, destOnRbd ? PhysicalDiskFormat.RAW : PhysicalDiskFormat.QCOW2, + Storage.ProvisioningType.THIN, guestSize, dstPassphrase); + + List cephAuthFiles = new ArrayList<>(); + try (KeyFile srcKeyFile = new KeyFile(srcPassphrase); KeyFile destKeyFile = new KeyFile(dstPassphrase)) { + QemuImageOptions srcImageOpts = encryptedImageOptions(srcPool, disk.getName(), disk.getPath(), + disk.getFormat() == PhysicalDiskFormat.QCOW2 ? PhysicalDiskFormat.QCOW2 : PhysicalDiskFormat.LUKS, SRC_LUKS_SECRET_ID, cephAuthFiles); + srcImageOpts.setImageOptsFlag(true); + QemuImageOptions destImageOpts = encryptedImageOptions(destPool, name, newDisk.getPath(), PhysicalDiskFormat.QCOW2, + DEST_LUKS_SECRET_ID, cephAuthFiles); + + QemuImgFile srcFile = new QemuImgFile(disk.getPath(), srcOnRbd ? PhysicalDiskFormat.RAW : disk.getFormat()); + List secrets = List.of(createSecretObject(SRC_LUKS_SECRET_ID, srcKeyFile), createSecretObject(DEST_LUKS_SECRET_ID, destKeyFile)); + new QemuImg(timeout).convert(srcFile, null, null, null, secrets, srcImageOpts, destImageOpts, null, false, false, false, false, null, null); + } catch (IOException | QemuImgException | LibvirtException e) { + logger.error("Failed to copy encrypted volume {} to {} in pool {}: {}", disk.getPath(), name, destPool.getUuid(), e.getMessage()); + try { + destPool.deletePhysicalDisk(name, destOnRbd ? Storage.ImageFormat.RAW : Storage.ImageFormat.QCOW2); + } catch (Exception ex) { + logger.warn("Failed to remove {} from pool {} after the failed copy: {}", name, destPool.getUuid(), ex.getMessage()); + } + throw new CloudRuntimeException(String.format("Failed to copy encrypted volume %s to %s", disk.getPath(), name), e); + } finally { + for (Path file : cephAuthFiles) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + logger.warn("Failed to remove temporary file {}: {}", file, e.getMessage()); + } + } + } + + newDisk.setFormat(destOnRbd ? PhysicalDiskFormat.RAW : PhysicalDiskFormat.QCOW2); + newDisk.setVirtualSize(guestSize); + newDisk.setQemuEncryptFormat(destOnRbd ? QemuObject.EncryptFormat.LUKS2 : QemuObject.EncryptFormat.LUKS); + return newDisk; + } + + /** + * qemu image options addressing an encrypted volume: an RBD image (with librbd LUKS2 encryption, authenticated through + * a temporary ceph.conf and keyring that are added to {@code cephAuthFiles}) or a file of the given format. + */ + private QemuImageOptions encryptedImageOptions(KVMStoragePool pool, String rbdImage, String filePath, PhysicalDiskFormat fileFormat, + String secretId, List cephAuthFiles) throws IOException { + if (pool.getType() != StoragePoolType.RBD) { + return new QemuImageOptions(fileFormat, filePath, secretId); + } + Path keyring = Files.createTempFile("cs-ceph-", ".keyring", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + cephAuthFiles.add(keyring); + Files.writeString(keyring, "[client." + pool.getAuthUserName() + "]\n\tkey = " + pool.getAuthSecret() + "\n"); + Path conf = Files.createTempFile("cs-ceph-", ".conf", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + cephAuthFiles.add(conf); + String monHost = RbdUtils.getRbdMonitors(pool.getSourceHost(), pool.getSourcePort()); + Files.writeString(conf, "[global]\nmon_host = " + monHost + "\nkeyring = " + keyring + "\n"); + + Map options = new HashMap<>(); + options.put("driver", "rbd"); + options.put("pool", pool.getSourceDir()); + options.put("image", rbdImage); + options.put("conf", conf.toString()); + if (pool.getAuthUserName() != null) { + options.put("user", pool.getAuthUserName()); + } + options.put("encrypt.format", CryptSetup.LuksType.LUKS2.toString()); + options.put("encrypt.key-secret", secretId); + return new QemuImageOptions(options); + } + + private QemuObject createSecretObject(String secretId, KeyFile keyFile) { + Map params = new EnumMap<>(QemuObject.ObjectParameter.class); + params.put(QemuObject.ObjectParameter.ID, secretId); + params.put(QemuObject.ObjectParameter.FILE, keyFile.toString()); + return new QemuObject(QemuObject.ObjectType.SECRET, params); + } + @Override public boolean refresh(KVMStoragePool pool) { LibvirtStoragePool libvirtPool = (LibvirtStoragePool)pool; diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStoragePool.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStoragePool.java index 58ec911cb16c..22ca9967a3bd 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStoragePool.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStoragePool.java @@ -65,6 +65,7 @@ public class LibvirtStoragePool implements KVMStoragePool { protected StoragePool _pool; protected String authUsername; protected String authSecret; + protected String authSecretUUID; protected String sourceHost; protected int sourcePort; protected String sourceDir; @@ -318,6 +319,15 @@ public void setType(StoragePoolType type) { this.type = type; } + @Override + public String getAuthSecretUUID() { + return authSecretUUID; + } + + public void setAuthSecretUUID(String authSecretUUID) { + this.authSecretUUID = authSecretUUID; + } + public StoragePool getPool() { return this._pool; } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapperTest.java index 235002a2d45c..70f2577762ef 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapperTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapperTest.java @@ -61,6 +61,8 @@ import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo; +import com.cloud.storage.StoragePoolInformation; +import com.cloud.storage.Storage; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DiskType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DriverType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.Source; @@ -881,6 +883,134 @@ public void testReplaceStorageWithSecrets() throws Exception { assertXpath(doc, "/domain/devices/disk/encryption/secret/@uuid", expectedSecretUuid); } + private static final String ENCRYPTED_FILE_DISK_XML = + "" + + " " + + " \n" + + " \n" + + " \n" + + " \n" + + " bf8621b3027c497d963b\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " " + + ""; + + @Test + public void testReplaceStorageSetsTheLibrbdEncryptionEngineWhenMigratingOntoRbd() throws Exception { + Map mapMigrateStorage = new HashMap<>(); + mapMigrateStorage.put("bf8621b3-027c-497d-963b-06319650f048", rbdDestination("destpool/destimage", "bf8621b3-027c-497d-963b-06319650f048")); + + Document doc = parseXml(libvirtMigrateCmdWrapper.replaceStorage(ENCRYPTED_FILE_DISK_XML, mapMigrateStorage, false)); + + assertXpath(doc, "/domain/devices/disk/encryption/@format", "luks2"); + assertXpath(doc, "/domain/devices/disk/encryption/@engine", "librbd"); + } + + @Test + public void testReplaceStorageKeepsTheGenericLuksEncryptionWhenNotMigratingOntoRbd() throws Exception { + Map mapMigrateStorage = createMapMigrateStorage("3530f749-82fd-458e-9485-a357e6e541db", + "/mnt/07eb495b-5590-3877-9fb7-23c6e9a40d40/bf8621b3-027c-497d-963b-06319650f048"); + + Document doc = parseXml(libvirtMigrateCmdWrapper.replaceStorage(ENCRYPTED_FILE_DISK_XML, mapMigrateStorage, false)); + + assertXpath(doc, "/domain/devices/disk/encryption/@format", "luks"); + assertXpath(doc, "/domain/devices/disk/encryption/@engine", ""); + } + + private Document parseXml(String xml) throws Exception { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(IOUtils.toInputStream(xml, "UTF-8")); + } + + private MigrateDiskInfo rbdDestination(String path, String srcPath) { + MigrateDiskInfo info = new MigrateDiskInfo("serial", DiskType.NETWORK, DriverType.RAW, Source.NETWORK, path); + info.setDestPoolInformation(new StoragePoolInformation("pool-uuid", "10.0.0.1,10.0.0.2", 6789, "destpool", "cephuser", Storage.StoragePoolType.RBD, null, true)); + info.setSourcePoolType(Storage.StoragePoolType.RBD); + info.setDestPoolType(Storage.StoragePoolType.RBD); + return info; + } + + @Test + public void testReplaceStorageRbdToRbd() throws Exception { + final String xmlDesc = + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + Map mapMigrateStorage = new HashMap<>(); + mapMigrateStorage.put("srcimage", rbdDestination("destpool/destimage", "srcimage")); + + Document doc = parseXml(libvirtMigrateCmdWrapper.replaceStorage(xmlDesc, mapMigrateStorage, false)); + + assertXpath(doc, "/domain/devices/disk/@type", "network"); + assertXpath(doc, "/domain/devices/disk/driver/@type", "raw"); + assertXpath(doc, "/domain/devices/disk/source/@protocol", "rbd"); + assertXpath(doc, "/domain/devices/disk/source/@name", "destpool/destimage"); + assertXpath(doc, "count(/domain/devices/disk/source/host)", "2"); + assertXpath(doc, "/domain/devices/disk/source/host[1]/@name", "10.0.0.1"); + assertXpath(doc, "/domain/devices/disk/source/host[2]/@port", "6789"); + assertXpath(doc, "count(/domain/devices/disk/auth)", "1"); + assertXpath(doc, "/domain/devices/disk/auth/@username", "cephuser"); + assertXpath(doc, "/domain/devices/disk/auth/secret/@uuid", "pool-uuid"); + } + + @Test + public void testReplaceStorageFileWithBackingStoreToRbd() throws Exception { + final String xmlDesc = + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + Map mapMigrateStorage = new HashMap<>(); + MigrateDiskInfo info = rbdDestination("destpool/destimage", "srcfile"); + info.setSourcePoolType(Storage.StoragePoolType.NetworkFilesystem); + mapMigrateStorage.put("srcfile", info); + + Document doc = parseXml(libvirtMigrateCmdWrapper.replaceStorage(xmlDesc, mapMigrateStorage, false)); + + assertXpath(doc, "/domain/devices/disk/@type", "network"); + assertXpath(doc, "/domain/devices/disk/driver/@type", "raw"); + assertXpath(doc, "/domain/devices/disk/source/@name", "destpool/destimage"); + assertXpath(doc, "count(/domain/devices/disk/source/@file)", "0"); + assertXpath(doc, "count(/domain/devices/disk/backingStore)", "0"); + } + + @Test + public void testReplaceStorageRbdToFile() throws Exception { + final String xmlDesc = + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + Map mapMigrateStorage = new HashMap<>(); + MigrateDiskInfo info = new MigrateDiskInfo("srcimage", DiskType.FILE, DriverType.QCOW2, Source.FILE, "/mnt/dest/destfile"); + info.setSourcePoolType(Storage.StoragePoolType.RBD); + info.setDestPoolType(Storage.StoragePoolType.NetworkFilesystem); + mapMigrateStorage.put("srcimage", info); + + Document doc = parseXml(libvirtMigrateCmdWrapper.replaceStorage(xmlDesc, mapMigrateStorage, false)); + + assertXpath(doc, "/domain/devices/disk/@type", "file"); + assertXpath(doc, "/domain/devices/disk/driver/@type", "qcow2"); + assertXpath(doc, "/domain/devices/disk/source/@file", "/mnt/dest/destfile"); + assertXpath(doc, "count(/domain/devices/disk/source/host)", "0"); + assertXpath(doc, "count(/domain/devices/disk/auth)", "0"); + } + @Test public void testReplaceBackingStore() throws Exception { Map mapMigrateStorage = new HashMap(); diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapperTest.java index e3d35dfb4d1f..b09a5afaf999 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapperTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateVolumeCommandWrapperTest.java @@ -23,12 +23,15 @@ import com.cloud.agent.api.storage.MigrateVolumeAnswer; import com.cloud.agent.api.storage.MigrateVolumeCommand; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.storage.Storage; +import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.storage.datastore.client.ScaleIOGatewayClient; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -228,6 +231,11 @@ public void testPowerFlexMigrateVolumeMethod() { Mockito.doReturn(srcPrimaryDataStore).when(srcVolumeObjectTO).getDataStore(); Mockito.doReturn(Storage.StoragePoolType.PowerFlex).when(srcPrimaryDataStore).getPoolType(); + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(destVolumeObjectTO).when(command).getDestData(); + PrimaryDataStoreTO destPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destPrimaryDataStore).when(destVolumeObjectTO).getDataStore(); + MigrateVolumeAnswer powerFlexAnswer = Mockito.mock(MigrateVolumeAnswer.class); MigrateVolumeAnswer regularVolumeAnswer = Mockito.mock(MigrateVolumeAnswer.class); @@ -246,7 +254,13 @@ public void testRegularMigrateVolumeMethod() { PrimaryDataStoreTO srcPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); Mockito.doReturn(srcPrimaryDataStore).when(srcVolumeObjectTO).getDataStore(); - Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(srcPrimaryDataStore).getPoolType(); + Mockito.doReturn(Storage.StoragePoolType.Filesystem).when(srcPrimaryDataStore).getPoolType(); + + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(destVolumeObjectTO).when(command).getDestData(); + PrimaryDataStoreTO destPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destPrimaryDataStore).when(destVolumeObjectTO).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.Filesystem).when(destPrimaryDataStore).getPoolType(); MigrateVolumeAnswer powerFlexAnswer = Mockito.mock(MigrateVolumeAnswer.class); MigrateVolumeAnswer regularVolumeAnswer = Mockito.mock(MigrateVolumeAnswer.class); @@ -259,6 +273,47 @@ public void testRegularMigrateVolumeMethod() { Assert.assertFalse(answer.getResult()); } + private Answer executeMigrationBetween(Storage.StoragePoolType srcType, Storage.StoragePoolType destType, boolean blockCopy) { + VolumeObjectTO srcVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(srcVolumeObjectTO).when(command).getSrcData(); + PrimaryDataStoreTO srcPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(srcPrimaryDataStore).when(srcVolumeObjectTO).getDataStore(); + Mockito.doReturn(srcType).when(srcPrimaryDataStore).getPoolType(); + + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(destVolumeObjectTO).when(command).getDestData(); + PrimaryDataStoreTO destPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destPrimaryDataStore).when(destVolumeObjectTO).getDataStore(); + Mockito.doReturn(destType).when(destPrimaryDataStore).getPoolType(); + + MigrateVolumeAnswer blockCopyAnswer = Mockito.mock(MigrateVolumeAnswer.class); + MigrateVolumeAnswer regularVolumeAnswer = Mockito.mock(MigrateVolumeAnswer.class); + Mockito.doReturn(blockCopy).when(blockCopyAnswer).getResult(); + Mockito.doReturn(!blockCopy).when(regularVolumeAnswer).getResult(); + Mockito.doReturn(blockCopyAnswer).when(libvirtMigrateVolumeCommandWrapper).migrateRBDVolume(command, libvirtComputingResource); + Mockito.doReturn(regularVolumeAnswer).when(libvirtMigrateVolumeCommandWrapper).migrateRegularVolume(command, libvirtComputingResource); + + return libvirtMigrateVolumeCommandWrapper.execute(command, libvirtComputingResource); + } + + @Test + public void testBlockCopyMigrateVolumeMethodBetweenRbdPoolsAndWithFileBasedPools() { + Assert.assertTrue("RBD -> RBD", executeMigrationBetween(Storage.StoragePoolType.RBD, Storage.StoragePoolType.RBD, true).getResult()); + for (Storage.StoragePoolType fileBased : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue("RBD -> " + fileBased, executeMigrationBetween(Storage.StoragePoolType.RBD, fileBased, true).getResult()); + Assert.assertTrue(fileBased + " -> RBD", executeMigrationBetween(fileBased, Storage.StoragePoolType.RBD, true).getResult()); + } + } + + @Test + public void testRegularMigrateVolumeMethodBetweenFileBasedPools() { + for (Storage.StoragePoolType src : Storage.KVM_FILE_BASED_POOL_TYPES) { + for (Storage.StoragePoolType dest : Storage.KVM_FILE_BASED_POOL_TYPES) { + Assert.assertTrue(src + " -> " + dest, executeMigrationBetween(src, dest, false).getResult()); + } + } + } + @Test public void testMigratePowerFlexVolume() throws LibvirtException, ParserConfigurationException, IOException, TransformerException, SAXException { VolumeObjectTO srcVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); @@ -349,6 +404,97 @@ public void testMigratePowerFlexVolumeFailure() throws LibvirtException, ParserC Assert.assertFalse(migrateVolumeAnswer.getResult()); } + /** + * Domain XML of a running Instance whose ROOT disk was thin-cloned from a template on an NFS pool: the disk + * carries the template as its backing file, and libvirt reports the whole chain in the live XML. + */ + private static final String DOMAIN_XML_WITH_BACKING_CHAIN = + "\n" + + " i-2-428-VM\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + + private Domain domainWithBackingChain() throws LibvirtException { + Domain dm = Mockito.mock(Domain.class); + Mockito.when(dm.getXMLDesc(0)).thenReturn(DOMAIN_XML_WITH_BACKING_CHAIN); + return dm; + } + + private KVMStoragePool rbdDestinationPool() { + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + Mockito.when(pool.getSourceHost()).thenReturn("10.0.33.44"); + Mockito.when(pool.getSourcePort()).thenReturn(0); + Mockito.when(pool.getAuthUserName()).thenReturn("admin"); + Mockito.when(pool.getAuthSecretUUID()).thenReturn("7684f6e5-fd91-3435-b04e-59ae0efb3914"); + return pool; + } + + /** + * A ROOT volume cloned from a template keeps that template as its backing file. Migrating it from NFS to Ceph is + * a full (non-shallow) block copy that flattens the chain into the destination, so the mirror XML must not carry + * a <backingStore> over - libvirt rejects it with "backingStore of mirror without + * VIR_DOMAIN_BLOCK_COPY_SHALLOW doesn't make sense" and the migration never starts. + */ + @Test + public void testGenerateDestinationDiskXMLForRBDDropsBackingStoreWhenCopyIsNotShallow() throws Exception { + String diskXml = libvirtMigrateVolumeCommandWrapper.generateDestinationDiskXMLForRBD( + domainWithBackingChain(), "5d468388-e71e-4169-805e-0398dbe7274a", + "cloudstack1/aa11bb22-cc33-dd44-ee55-ff6677889900", null, rbdDestinationPool(), + Storage.StoragePoolType.RBD, false); + + Assert.assertNotNull(diskXml); + Assert.assertFalse("the inherited backing chain must not reach a non-shallow mirror", + diskXml.contains("backingStore")); + Assert.assertTrue(diskXml.contains("protocol=\"rbd\"")); + Assert.assertTrue(diskXml.contains("cloudstack1/aa11bb22-cc33-dd44-ee55-ff6677889900")); + Assert.assertTrue("an RBD destination is raw", diskXml.contains("type=\"raw\"")); + } + + /** + * An RBD to RBD migration copies only the active layer, so the backing chain stays meaningful and is preserved. + */ + @Test + public void testGenerateDestinationDiskXMLForRBDKeepsBackingStoreWhenCopyIsShallow() throws Exception { + String diskXml = libvirtMigrateVolumeCommandWrapper.generateDestinationDiskXMLForRBD( + domainWithBackingChain(), "5d468388-e71e-4169-805e-0398dbe7274a", + "cloudstack1/aa11bb22-cc33-dd44-ee55-ff6677889900", null, rbdDestinationPool(), + Storage.StoragePoolType.RBD, true); + + Assert.assertNotNull(diskXml); + Assert.assertTrue("a shallow copy keeps the backing chain", diskXml.contains("backingStore")); + } + + /** + * The same applies migrating the other way: a Ceph to NFS copy is not shallow either, so the destination file + * disk must be free of the source's backing chain. + */ + @Test + public void testGenerateDestinationDiskXMLForFileDestinationDropsBackingStore() throws Exception { + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + + String diskXml = libvirtMigrateVolumeCommandWrapper.generateDestinationDiskXMLForRBD( + domainWithBackingChain(), "5d468388-e71e-4169-805e-0398dbe7274a", + "/mnt/nfs-pool/aa11bb22-cc33-dd44-ee55-ff6677889900", null, pool, + Storage.StoragePoolType.NetworkFilesystem, false); + + Assert.assertNotNull(diskXml); + Assert.assertFalse(diskXml.contains("backingStore")); + Assert.assertTrue(diskXml.contains("/mnt/nfs-pool/aa11bb22-cc33-dd44-ee55-ff6677889900")); + Assert.assertTrue("a file destination is qcow2", diskXml.contains("type=\"qcow2\"")); + } + @Test public void testCheckBlockJobStatus() throws LibvirtException { Connect conn = Mockito.mock(Connect.class); @@ -385,4 +531,192 @@ public void testCheckBlockJobStatusFailure() throws LibvirtException { Assert.assertFalse(answer.getResult()); } + private static final long ENCRYPTED_VOLUME_SIZE = 1073741824L; + + /** + * Prepares migrateRBDVolume for a block copy which completes and is pivoted, and returns the source and the + * destination pool. + */ + private KVMStoragePool[] prepareMigrationOfVolumeWhichIsPivoted(Storage.StoragePoolType srcType, Storage.StoragePoolType destType, byte[] passphrase) throws Exception { + String vmName = "i-2-27-VM"; + Mockito.doReturn(vmName).when(command).getAttachedVmName(); + + VolumeObjectTO srcVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(srcVolumeObjectTO).when(command).getSrcData(); + Mockito.doReturn("src-volume").when(srcVolumeObjectTO).getPath(); + PrimaryDataStoreTO srcPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(srcPrimaryDataStore).when(srcVolumeObjectTO).getDataStore(); + Mockito.doReturn(srcType).when(srcPrimaryDataStore).getPoolType(); + Mockito.doReturn("src-pool").when(srcPrimaryDataStore).getUuid(); + + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(destVolumeObjectTO).when(command).getDestData(); + Mockito.doReturn("dest-volume").when(destVolumeObjectTO).getPath(); + Mockito.doReturn(passphrase).when(destVolumeObjectTO).getPassphrase(); + PrimaryDataStoreTO destPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destPrimaryDataStore).when(destVolumeObjectTO).getDataStore(); + Mockito.doReturn(destType).when(destPrimaryDataStore).getPoolType(); + Mockito.doReturn("dest-pool").when(destPrimaryDataStore).getUuid(); + + Mockito.doReturn(libvirtUtilitiesHelper).when(libvirtComputingResource).getLibvirtUtilitiesHelper(); + Connect conn = Mockito.mock(Connect.class); + Domain dm = Mockito.mock(Domain.class); + Mockito.doReturn(conn).when(libvirtUtilitiesHelper).getConnection(); + Mockito.doReturn(dm).when(libvirtComputingResource).getDomain(conn, vmName); + DomainInfo domainInfo = Mockito.mock(DomainInfo.class); + domainInfo.state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING; + Mockito.doReturn(domainInfo).when(dm).getInfo(); + + KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class); + Mockito.doReturn(storagePoolMgr).when(libvirtComputingResource).getStoragePoolMgr(); + KVMStoragePool srcKvmPool = Mockito.mock(KVMStoragePool.class); + KVMStoragePool destKvmPool = Mockito.mock(KVMStoragePool.class); + Mockito.doReturn(srcKvmPool).when(storagePoolMgr).getStoragePool(srcType, "src-pool"); + Mockito.doReturn(destKvmPool).when(storagePoolMgr).getStoragePool(destType, "dest-pool"); + Mockito.doReturn(true).when(destKvmPool).connectPhysicalDisk(Mockito.any(), Mockito.any()); + + Mockito.doReturn("/path/on/host").when(libvirtMigrateVolumeCommandWrapper).generateVolumePathOnHost(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doReturn("").when(libvirtMigrateVolumeCommandWrapper) + .generateDestinationDiskXMLForRBD(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doNothing().when(libvirtMigrateVolumeCommandWrapper).createEncryptedDestinationVolume(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyLong()); + Mockito.lenient().doReturn(ENCRYPTED_VOLUME_SIZE).when(libvirtMigrateVolumeCommandWrapper).getEncryptedVolumeSize(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(dm).blockCopy(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(TypedParameter[].class), ArgumentMatchers.anyInt()); + MigrateVolumeAnswer pivoted = new MigrateVolumeAnswer(command, true, null, "dest-volume"); + Mockito.doReturn(pivoted).when(libvirtMigrateVolumeCommandWrapper).checkBlockJobStatus(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + return new KVMStoragePool[] {srcKvmPool, destKvmPool}; + } + + @Test + public void testMigrateRBDVolumeIsSuccessfulWhenTheSourceVolumeCanNotBeRemoved() throws Exception { + KVMStoragePool[] pools = prepareMigrationOfVolumeWhichIsPivoted(Storage.StoragePoolType.RBD, Storage.StoragePoolType.RBD, null); + Mockito.doThrow(new CloudRuntimeException("failed to remove volume: No such file or directory")).when(pools[0]).deletePhysicalDisk(Mockito.any(), Mockito.any()); + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.migrateRBDVolume(command, libvirtComputingResource); + + Assert.assertTrue("the Instance uses the destination volume already", answer.getResult()); + Assert.assertEquals("dest-volume", answer.getVolumePath()); + Mockito.verify(pools[0]).deletePhysicalDisk(Mockito.eq("src-volume"), Mockito.any()); + Mockito.verify(libvirtMigrateVolumeCommandWrapper, Mockito.never()).deleteDestinationVolume(Mockito.any(), Mockito.any(), Mockito.any()); + } + + @Test + public void testMigrateRBDVolumeRefusesAnEncryptedRbdDestinationOnLibvirtBefore10_1_0() throws Exception { + VolumeObjectTO srcVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(srcVolumeObjectTO).when(command).getSrcData(); + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(destVolumeObjectTO).when(command).getDestData(); + Mockito.doReturn(new byte[] {1, 2, 3}).when(destVolumeObjectTO).getPassphrase(); + PrimaryDataStoreTO destPrimaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destPrimaryDataStore).when(destVolumeObjectTO).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.RBD).when(destPrimaryDataStore).getPoolType(); + Mockito.doReturn(10000000L).when(libvirtComputingResource).getHypervisorLibvirtVersion(); // libvirt 10.0.0 + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.migrateRBDVolume(command, libvirtComputingResource); + + Assert.assertFalse(answer.getResult()); + Assert.assertTrue(answer.getDetails(), answer.getDetails().contains("Libvirt version 10.1.0 required")); + Assert.assertTrue(answer.getDetails(), answer.getDetails().contains("but version 10.0.0 detected")); + // nothing was touched: no connection to libvirt, no destination volume + Mockito.verify(libvirtComputingResource, Mockito.never()).getLibvirtUtilitiesHelper(); + Mockito.verify(libvirtMigrateVolumeCommandWrapper, Mockito.never()).createEncryptedDestinationVolume(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyLong()); + } + + @Test + public void testMigrateRBDVolumeAllowsAnEncryptedRbdDestinationOnLibvirt10_1_0() throws Exception { + prepareMigrationOfVolumeWhichIsPivoted(Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.RBD, new byte[] {1, 2, 3}); + Mockito.doReturn(10001000L).when(libvirtComputingResource).getHypervisorLibvirtVersion(); // libvirt 10.1.0 + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.migrateRBDVolume(command, libvirtComputingResource); + + Assert.assertTrue(answer.getDetails(), answer.getResult()); + } + + @Test + public void testMigrateRBDVolumeKeepsTheDestinationOfAnEncryptedVolumeWhichIsPivoted() throws Exception { + KVMStoragePool[] pools = prepareMigrationOfVolumeWhichIsPivoted(Storage.StoragePoolType.RBD, Storage.StoragePoolType.NetworkFilesystem, new byte[] {1, 2, 3}); + Mockito.doThrow(new CloudRuntimeException("failed to remove volume")).when(pools[0]).deletePhysicalDisk(Mockito.any(), Mockito.any()); + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.migrateRBDVolume(command, libvirtComputingResource); + + Assert.assertTrue(answer.getResult()); + // the Instance writes to the destination volume: it must not be removed as the one of a failed migration + Mockito.verify(libvirtMigrateVolumeCommandWrapper, Mockito.never()).deleteDestinationVolume(Mockito.any(), Mockito.any(), Mockito.any()); + } + + @Test + public void testCheckBlockJobStatusIsSuccessfulWhenTheSecretOfTheSourceVolumeCanNotBeRemoved() throws LibvirtException { + Connect conn = Mockito.mock(Connect.class); + Domain dm = Mockito.mock(Domain.class); + Mockito.doReturn(60).when(command).getWait(); + DomainBlockJobInfo blockJobInfo = Mockito.mock(DomainBlockJobInfo.class); + Mockito.doReturn(blockJobInfo).when(dm).getBlockJobInfo("vda", 0); + blockJobInfo.cur = 100; + blockJobInfo.end = 100; + Mockito.doThrow(new CloudRuntimeException("no such secret")).when(libvirtComputingResource).removeLibvirtVolumeSecret(conn, "secret-uuid"); + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.checkBlockJobStatus(command, dm, "vda", "src", "dest", libvirtComputingResource, conn, "secret-uuid"); + + Assert.assertTrue("the block copy was pivoted", answer.getResult()); + Mockito.verify(dm).blockJobAbort("vda", Domain.BlockJobAbortFlags.PIVOT); + } + + @Test + public void testMigrateRBDVolumeCreatesTheEncryptedDestinationWithTheSizeTheInstanceSees() throws Exception { + KVMStoragePool[] pools = prepareMigrationOfVolumeWhichIsPivoted(Storage.StoragePoolType.RBD, Storage.StoragePoolType.NetworkFilesystem, new byte[] {1, 2, 3}); + + MigrateVolumeAnswer answer = libvirtMigrateVolumeCommandWrapper.migrateRBDVolume(command, libvirtComputingResource); + + Assert.assertTrue(answer.getResult()); + Mockito.verify(libvirtMigrateVolumeCommandWrapper).getEncryptedVolumeSize(Mockito.eq(pools[0]), Mockito.any(), Mockito.eq("src-volume")); + Mockito.verify(libvirtMigrateVolumeCommandWrapper).createEncryptedDestinationVolume(Mockito.eq(pools[1]), Mockito.any(), Mockito.any(), Mockito.eq(ENCRYPTED_VOLUME_SIZE)); + } + + private void verifyEncryptedDestinationVolumeIsCreatedWithTheSizeTheInstanceSees(Storage.StoragePoolType destType, PhysicalDiskFormat expectedFormat) { + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + PrimaryDataStoreTO destPool = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(destType).when(destPool).getPoolType(); + VolumeObjectTO destVolumeObjectTO = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn("dest-volume").when(destVolumeObjectTO).getPath(); + byte[] passphrase = new byte[] {1, 2, 3}; + Mockito.doReturn(passphrase).when(destVolumeObjectTO).getPassphrase(); + + libvirtMigrateVolumeCommandWrapper.createEncryptedDestinationVolume(pool, destPool, destVolumeObjectTO, ENCRYPTED_VOLUME_SIZE); + + // the storage adaptor makes the room for the encryption header, so the size is not grown here + Mockito.verify(pool).createPhysicalDisk("dest-volume", expectedFormat, Storage.ProvisioningType.THIN, ENCRYPTED_VOLUME_SIZE, passphrase); + } + + @Test + public void testCreateEncryptedDestinationVolumeOnRbd() { + verifyEncryptedDestinationVolumeIsCreatedWithTheSizeTheInstanceSees(Storage.StoragePoolType.RBD, PhysicalDiskFormat.RAW); + } + + @Test + public void testCreateEncryptedDestinationVolumeOnNfs() { + verifyEncryptedDestinationVolumeIsCreatedWithTheSizeTheInstanceSees(Storage.StoragePoolType.NetworkFilesystem, PhysicalDiskFormat.QCOW2); + } + + @Test + public void testCreateEncryptedDestinationVolumeOnSharedMountPoint() { + verifyEncryptedDestinationVolumeIsCreatedWithTheSizeTheInstanceSees(Storage.StoragePoolType.SharedMountPoint, PhysicalDiskFormat.QCOW2); + } + + @Test + public void testCreateEncryptedDestinationVolumeOnLocalStorage() { + verifyEncryptedDestinationVolumeIsCreatedWithTheSizeTheInstanceSees(Storage.StoragePoolType.Filesystem, PhysicalDiskFormat.QCOW2); + } + + @Test + public void testGetEncryptedVolumeSizeOfAFileIsItsVirtualSize() { + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + PrimaryDataStoreTO dataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(dataStore).getPoolType(); + KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class); + Mockito.doReturn(disk).when(pool).getPhysicalDisk("volume"); + // a QCOW2 file keeps its encryption header apart from the data the Instance sees + Mockito.doReturn(ENCRYPTED_VOLUME_SIZE).when(disk).getVirtualSize(); + + Assert.assertEquals(ENCRYPTED_VOLUME_SIZE, libvirtMigrateVolumeCommandWrapper.getEncryptedVolumeSize(pool, dataStore, "volume")); + } } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapperTest.java index 9a98b5c99fb2..675ed466514c 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapperTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapperTest.java @@ -30,11 +30,17 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; + +import com.cloud.agent.api.Answer; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; +import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.DpdkTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.storage.Storage; import com.cloud.utils.exception.CloudRuntimeException; @RunWith(MockitoJUnitRunner.class) @@ -108,4 +114,72 @@ public void testRemoveDpdkPortForCommandInjection() { runTestRemoveDpdkPortForCommandInjection(portWithCommand); } } + + private DiskTO diskWithDestPoolTypeDetail(String destPoolType) { + DiskTO disk = Mockito.mock(DiskTO.class); + Map details = new HashMap<>(); + if (destPoolType != null) { + details.put(DiskTO.MIGRATION_DEST_POOL_TYPE, destPoolType); + } + Mockito.doReturn(details).when(disk).getDetails(); + return disk; + } + + private VolumeObjectTO volumeOnPool(Storage.StoragePoolType poolType) { + VolumeObjectTO volumeObjectTO = Mockito.mock(VolumeObjectTO.class); + PrimaryDataStoreTO dataStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(poolType).when(dataStore).getPoolType(); + Mockito.doReturn(dataStore).when(volumeObjectTO).getDataStore(); + return volumeObjectTO; + } + + @Test + public void refuseIfDestinationCannotHotplugEncryptedRbdAllowsANonRbdDestination() { + Answer answer = libvirtPrepareForMigrationCommandWrapperSpy.refuseIfDestinationCannotHotplugEncryptedRbd(prepareForMigrationCommandMock, + virtualMachineTOMock, diskWithDestPoolTypeDetail(Storage.StoragePoolType.NetworkFilesystem.toString()), + volumeOnPool(Storage.StoragePoolType.RBD), libvirtComputingResourceMock); + + Assert.assertNull(answer); + Mockito.verify(libvirtComputingResourceMock, Mockito.never()).getHypervisorLibvirtVersion(); + } + + @Test + public void refuseIfDestinationCannotHotplugEncryptedRbdAllowsAHostWithNewEnoughLibvirt() { + Mockito.doReturn(10001000L).when(libvirtComputingResourceMock).getHypervisorLibvirtVersion(); // libvirt 10.1.0 + + Answer answer = libvirtPrepareForMigrationCommandWrapperSpy.refuseIfDestinationCannotHotplugEncryptedRbd(prepareForMigrationCommandMock, + virtualMachineTOMock, diskWithDestPoolTypeDetail(Storage.StoragePoolType.RBD.toString()), volumeOnPool(Storage.StoragePoolType.RBD), + libvirtComputingResourceMock); + + Assert.assertNull(answer); + } + + @Test + public void refuseIfDestinationCannotHotplugEncryptedRbdRefusesByTheDestPoolTypeDetailWhenStorageIsMigrating() { + Mockito.doReturn("i-2-3-VM").when(virtualMachineTOMock).getName(); + Mockito.doReturn(10000000L).when(libvirtComputingResourceMock).getHypervisorLibvirtVersion(); // libvirt 10.0.0 + + // the disk's own dataStore still reports the source (NFS) pool: the migration detail is what must be trusted + Answer answer = libvirtPrepareForMigrationCommandWrapperSpy.refuseIfDestinationCannotHotplugEncryptedRbd(prepareForMigrationCommandMock, + virtualMachineTOMock, diskWithDestPoolTypeDetail(Storage.StoragePoolType.RBD.toString()), + volumeOnPool(Storage.StoragePoolType.NetworkFilesystem), libvirtComputingResourceMock); + + Assert.assertNotNull(answer); + Assert.assertFalse(((PrepareForMigrationAnswer) answer).getResult()); + Assert.assertTrue(answer.getDetails(), answer.getDetails().contains("Libvirt version 10.1.0 required")); + Assert.assertTrue(answer.getDetails(), answer.getDetails().contains("version 10.0.0 detected")); + Assert.assertTrue(answer.getDetails(), answer.getDetails().contains("i-2-3-VM")); + } + + @Test + public void refuseIfDestinationCannotHotplugEncryptedRbdFallsBackToTheDisksOwnPoolWhenStorageIsNotMigrating() { + Mockito.doReturn("i-2-3-VM").when(virtualMachineTOMock).getName(); + Mockito.doReturn(10000000L).when(libvirtComputingResourceMock).getHypervisorLibvirtVersion(); // libvirt 10.0.0 + + Answer answer = libvirtPrepareForMigrationCommandWrapperSpy.refuseIfDestinationCannotHotplugEncryptedRbd(prepareForMigrationCommandMock, + virtualMachineTOMock, diskWithDestPoolTypeDetail(null), volumeOnPool(Storage.StoragePoolType.RBD), libvirtComputingResourceMock); + + Assert.assertNotNull(answer); + Assert.assertFalse(((PrepareForMigrationAnswer) answer).getResult()); + } } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java index a85fc31224e0..0e0a6ac28796 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessorTest.java @@ -28,7 +28,14 @@ import com.cloud.hypervisor.kvm.resource.LibvirtDomainXMLParser; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef; +import com.cloud.storage.MigrationOptions; +import com.cloud.storage.ScopeType; import com.cloud.storage.Storage; +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; +import org.mockito.ArgumentCaptor; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.command.CopyCommand; +import org.apache.cloudstack.storage.command.CopyCmdAnswer; import com.cloud.storage.template.TemplateConstants; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; @@ -204,6 +211,50 @@ public void validateValidateAvailableSizeOnPoolToTakeVolumeSnapshotAvailabeSizeE storageProcessor.validateAvailableSizeOnPoolToTakeVolumeSnapshot(kvmStoragePoolMock, kvmPhysicalDiskMock); } + /** + * The destination of a full clone migration gets the declared size of the volume, whatever the pools are: the + * storage adaptor makes the room the encryption header of an encrypted volume needs, on RBD as on a file based + * pool. The source pool is not looked up, as the host creating the destination may not reach it. + */ + private void verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType srcPoolType, ScopeType srcPoolScope, PhysicalDiskFormat format, byte[] passphrase) { + long declaredSize = 1073741824L; + Mockito.doReturn(declaredSize).when(volumeObjectToMock).getSize(); + Mockito.doReturn("volumeUuid").when(volumeObjectToMock).getUuid(); + Mockito.doReturn(Storage.ProvisioningType.THIN).when(volumeObjectToMock).getProvisioningType(); + Mockito.doReturn(passphrase).when(volumeObjectToMock).getPassphrase(); + MigrationOptions migrationOptions = new MigrationOptions("srcPoolUuid", srcPoolType, "srcVolumeUuid", srcPoolScope, 1L); + + storageProcessor.createFullCloneVolume(migrationOptions, volumeObjectToMock, kvmStoragePoolMock, format); + + Mockito.verify(kvmStoragePoolMock).createPhysicalDisk("volumeUuid", format, Storage.ProvisioningType.THIN, declaredSize, passphrase); + Mockito.verify(storagePoolManager, Mockito.never()).getStoragePool(Mockito.any(), Mockito.any()); + } + + @Test + public void createFullCloneVolumeNotEncryptedUsesTheDeclaredSize() { + verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType.NetworkFilesystem, ScopeType.CLUSTER, PhysicalDiskFormat.RAW, null); + } + + @Test + public void createFullCloneVolumeEncryptedRbdToFileBasedPoolUsesTheDeclaredSize() { + verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType.RBD, ScopeType.CLUSTER, PhysicalDiskFormat.QCOW2, new byte[] {1, 2, 3}); + } + + @Test + public void createFullCloneVolumeEncryptedNfsToRbdUsesTheDeclaredSize() { + verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType.NetworkFilesystem, ScopeType.ZONE, PhysicalDiskFormat.RAW, new byte[] {1, 2, 3}); + } + + @Test + public void createFullCloneVolumeEncryptedLocalToRbdUsesTheDeclaredSize() { + verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType.Filesystem, ScopeType.HOST, PhysicalDiskFormat.RAW, new byte[] {1, 2, 3}); + } + + @Test + public void createFullCloneVolumeEncryptedSharedMountPointToRbdUsesTheDeclaredSize() { + verifyCreateFullCloneVolumeUsesTheDeclaredSize(StoragePoolType.SharedMountPoint, ScopeType.CLUSTER, PhysicalDiskFormat.RAW, new byte[] {1, 2, 3}); + } + private List createDiskDefs(int iterations, boolean duplicatePath) { List disks = new ArrayList<>(); @@ -526,7 +577,6 @@ private KVMPhysicalDisk prepareRbdSnapshotMocks(Rados radosMock, IoCTX ioCtxMock Mockito.lenient().doReturn("cloudstack").when(kvmStoragePoolMock).getAuthUserName(); Mockito.lenient().doReturn("secret").when(kvmStoragePoolMock).getAuthSecret(); - Mockito.doReturn(radosMock).when(storageProcessorSpy).radosConnect(kvmStoragePoolMock); Mockito.doReturn(ioCtxMock).when(radosMock).ioCtxCreate(RBD_POOL_NAME); Mockito.lenient().doReturn(SNAPSHOT_SIZE).when(storageProcessorSpy).getRbdSnapshotSize(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); @@ -545,8 +595,10 @@ public void takeRbdVolumeSnapshotOfStoppedVmTestCreatesSnapshotExactlyOnce() thr RbdImage rbdImageMock = Mockito.mock(RbdImage.class); KVMPhysicalDisk diskMock = prepareRbdSnapshotMocks(radosMock, ioCtxMock); - try (MockedConstruction rbd = Mockito.mockConstruction(Rbd.class, ((mock, context) -> + try (MockedStatic adaptor = Mockito.mockStatic(LibvirtStorageAdaptor.class); + MockedConstruction rbd = Mockito.mockConstruction(Rbd.class, ((mock, context) -> Mockito.doReturn(rbdImageMock).when(mock).open(RBD_IMAGE_NAME)))) { + adaptor.when(() -> LibvirtStorageAdaptor.connectToCeph(kvmStoragePoolMock)).thenReturn(radosMock); Long result = storageProcessorSpy.takeRbdVolumeSnapshotOfStoppedVm(kvmStoragePoolMock, diskMock, SNAPSHOT_NAME); @@ -569,8 +621,10 @@ public void takeRbdVolumeSnapshotOfStoppedVmTestReleasesHandlesWhenSnapshotFails KVMPhysicalDisk diskMock = prepareRbdSnapshotMocks(radosMock, ioCtxMock); Mockito.doThrow(new RbdException("Failed to create snapshot")).when(rbdImageMock).snapCreate(SNAPSHOT_NAME); - try (MockedConstruction rbd = Mockito.mockConstruction(Rbd.class, ((mock, context) -> + try (MockedStatic adaptor = Mockito.mockStatic(LibvirtStorageAdaptor.class); + MockedConstruction rbd = Mockito.mockConstruction(Rbd.class, ((mock, context) -> Mockito.doReturn(rbdImageMock).when(mock).open(RBD_IMAGE_NAME)))) { + adaptor.when(() -> LibvirtStorageAdaptor.connectToCeph(kvmStoragePoolMock)).thenReturn(radosMock); Long result = storageProcessorSpy.takeRbdVolumeSnapshotOfStoppedVm(kvmStoragePoolMock, diskMock, SNAPSHOT_NAME); @@ -751,6 +805,7 @@ public void ensureLibvirtSupportsEncryptedRbdHotplugRejectsOldLibvirt() { CloudRuntimeException ex = Assert.assertThrows(CloudRuntimeException.class, () -> storageProcessor.ensureLibvirtSupportsEncryptedRbdHotplug(StoragePoolType.RBD)); Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("Libvirt version 10.1.0 required")); + Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("but version 10.0.0 detected")); } @Test @@ -765,4 +820,61 @@ public void ensureLibvirtSupportsEncryptedRbdHotplugIgnoresNonRbd() { // version is not even consulted for them. storageProcessor.ensureLibvirtSupportsEncryptedRbdHotplug(StoragePoolType.NetworkFilesystem); } + + private String copyVolumeFromPrimaryToPrimaryTo(StoragePoolType destType, PhysicalDiskFormat destFormat, ArgumentCaptor destNameCaptor) { + CopyCommand command = Mockito.mock(CopyCommand.class); + VolumeObjectTO srcVolume = Mockito.mock(VolumeObjectTO.class); + VolumeObjectTO destVolume = Mockito.mock(VolumeObjectTO.class); + Mockito.doReturn(srcVolume).when(command).getSrcTO(); + Mockito.doReturn(destVolume).when(command).getDestTO(); + Mockito.doReturn(Storage.ImageFormat.RAW).when(srcVolume).getFormat(); + Mockito.doReturn("src-volume").when(srcVolume).getPath(); + Mockito.doReturn(Storage.ImageFormat.QCOW2).when(destVolume).getFormat(); + Mockito.doReturn(null).when(destVolume).getPath(); + + PrimaryDataStoreTO srcStore = Mockito.mock(PrimaryDataStoreTO.class); + PrimaryDataStoreTO destStore = Mockito.mock(PrimaryDataStoreTO.class); + Mockito.doReturn(srcStore).when(srcVolume).getDataStore(); + Mockito.doReturn(destStore).when(destVolume).getDataStore(); + Mockito.doReturn(StoragePoolType.NetworkFilesystem).when(srcStore).getPoolType(); + Mockito.doReturn("src-pool").when(srcStore).getUuid(); + Mockito.doReturn(destType).when(destStore).getPoolType(); + Mockito.doReturn("dest-pool").when(destStore).getUuid(); + + KVMPhysicalDisk srcDisk = Mockito.mock(KVMPhysicalDisk.class); + KVMStoragePool destPool = Mockito.mock(KVMStoragePool.class); + KVMPhysicalDisk newDisk = Mockito.mock(KVMPhysicalDisk.class); + Mockito.doReturn(destFormat).when(newDisk).getFormat(); + Mockito.doReturn(destFormat).when(destPool).getDefaultFormat(); + Mockito.doReturn(srcDisk).when(storagePoolManager).getPhysicalDisk(StoragePoolType.NetworkFilesystem, "src-pool", "src-volume"); + Mockito.doReturn(destPool).when(storagePoolManager).getStoragePool(destType, "dest-pool"); + Mockito.doReturn(newDisk).when(storagePoolManager).copyPhysicalDisk(Mockito.eq(srcDisk), destNameCaptor.capture(), Mockito.eq(destPool), Mockito.anyInt()); + + CopyCmdAnswer answer = (CopyCmdAnswer) storageProcessor.copyVolumeFromPrimaryToPrimary(command); + + Assert.assertTrue(answer.getResult()); + return ((VolumeObjectTO) answer.getNewData()).getPath(); + } + + @Test + public void testCopyVolumeFromPrimaryToPrimaryNamesAnRbdVolumeAfterItsUuidOnly() { + ArgumentCaptor destName = ArgumentCaptor.forClass(String.class); + + String path = copyVolumeFromPrimaryToPrimaryTo(StoragePoolType.RBD, PhysicalDiskFormat.RAW, destName); + + Assert.assertEquals(path, destName.getValue()); + Assert.assertTrue("a plain UUID, without the extension of a format: " + path, path.matches("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}")); + } + + @Test + public void testCopyVolumeFromPrimaryToPrimaryNamesAVolumeOfAFileBasedPoolAfterItsFormat() { + for (StoragePoolType fileBased : new StoragePoolType[] {StoragePoolType.NetworkFilesystem, StoragePoolType.SharedMountPoint, StoragePoolType.Filesystem}) { + ArgumentCaptor destName = ArgumentCaptor.forClass(String.class); + + String path = copyVolumeFromPrimaryToPrimaryTo(fileBased, PhysicalDiskFormat.QCOW2, destName); + + Assert.assertEquals(path, destName.getValue()); + Assert.assertTrue(fileBased + ": a UUID with the extension of the qcow2 format: " + path, path.matches("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.qcow2")); + } + } } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptorTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptorTest.java index 9b8e1fd2d748..761f52a51e19 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptorTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptorTest.java @@ -27,6 +27,7 @@ import java.util.UUID; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -347,4 +348,32 @@ public void testCLVMPoolDetailsSecureZeroFillDefault() { assert !secureZeroEnabled; } + + @Test + public void maskRbdKeyHidesTheCephKey() { + String message = "qemu-img: rbd:pool/image:mon_host=10.0.0.1\\:6789:auth_client_required=cephx:id=pool:key=AQCsecret==:rbd_default_format=2: error while converting raw: error rbd create: File exists"; + String masked = LibvirtStorageAdaptor.maskRbdKey(message); + Assert.assertFalse(masked.contains("AQCsecret")); + Assert.assertTrue(masked.contains("key=******:rbd_default_format=2")); + Assert.assertTrue(masked.endsWith("File exists")); + } + + @Test + public void maskRbdKeyKeepsMessagesWithoutKey() { + Assert.assertNull(LibvirtStorageAdaptor.maskRbdKey(null)); + Assert.assertEquals("timeout", LibvirtStorageAdaptor.maskRbdKey("timeout")); + } + + /** + * Measured with `rbd encryption format` (Ceph 20.2): the data of a LUKS2 encrypted image starts at 16 MiB with + * objects of 1, 4 or 8 MiB, and at 32 MiB with objects of 32 MiB. + */ + @Test + public void testGetRbdLuks2HeaderSize() { + Assert.assertEquals(16L << 20, LibvirtStorageAdaptor.getRbdLuks2HeaderSize(1L << 20)); + Assert.assertEquals(16L << 20, LibvirtStorageAdaptor.getRbdLuks2HeaderSize(4L << 20)); + Assert.assertEquals(16L << 20, LibvirtStorageAdaptor.getRbdLuks2HeaderSize(8L << 20)); + Assert.assertEquals(16L << 20, LibvirtStorageAdaptor.getRbdLuks2HeaderSize(16L << 20)); + Assert.assertEquals(32L << 20, LibvirtStorageAdaptor.getRbdLuks2HeaderSize(32L << 20)); + } } diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java index 11b24a9beef6..ef4a1cd7ba2b 100644 --- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java @@ -186,6 +186,7 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolTagsDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; @@ -305,6 +306,8 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic @Inject private PrimaryDataStoreDao _storagePoolDao; @Inject + private StoragePoolHostDao _storagePoolHostDao; + @Inject private ImageStoreDao imageStoreDao; @Inject private DiskOfferingDao _diskOfferingDao; @@ -3808,11 +3811,13 @@ public Volume migrateVolume(MigrateVolumeCmd cmd) { if (liveMigrateVolume && HypervisorType.KVM.equals(host.getHypervisorType()) && !srcStoragePoolVO.getPoolType().equals(Storage.StoragePoolType.PowerFlex)) { StoragePoolVO destinationStoragePoolVo = _storagePoolDao.findById(storagePoolId); - if (isSourceOrDestNotOnStorPool(srcStoragePoolVO, destinationStoragePoolVo)) { + if (isSourceOrDestNotOnStorPool(srcStoragePoolVO, destinationStoragePoolVo) + && !Storage.isCopiedInPlaceOnKvm(srcStoragePoolVO.getPoolType(), destinationStoragePoolVo.getPoolType())) { throw new InvalidParameterValueException("KVM does not support volume live migration due to the limited possibility to refresh VM XML domain. " + "Therefore, to live migrate a volume between storage pools, one must migrate the VM to a different host as well to force the VM XML domain update. " + "Use 'migrateVirtualMachineWithVolumes' instead."); } + checkLocalPoolsOnHostOfRunningVm(vm, srcStoragePoolVO, destinationStoragePoolVo); srcAndDestOnStorPool = isSourceAndDestOnStorPool(srcStoragePoolVO, destinationStoragePoolVo); } } @@ -3827,7 +3832,14 @@ public Volume migrateVolume(MigrateVolumeCmd cmd) { } } - if ((vol.getPassphraseId() != null || vol.getKmsKeyId() != null) && !srcAndDestOnStorPool && !srcStoragePoolVO.getPoolType().equals(Storage.StoragePoolType.PowerFlex)) { + // An encrypted (KVM) volume can be migrated between two RBD pools and between an RBD pool and a file based one, + // whether it is in use by a running Instance or not + StoragePoolVO destinationStoragePoolVO = _storagePoolDao.findById(storagePoolId); + boolean copiedInPlaceOnKvm = destinationStoragePoolVO != null && Storage.isCopiedInPlaceOnKvm(srcStoragePoolVO.getPoolType(), destinationStoragePoolVO.getPoolType()); + + if ((vol.getPassphraseId() != null || vol.getKmsKeyId() != null) && !srcAndDestOnStorPool + && !srcStoragePoolVO.getPoolType().equals(Storage.StoragePoolType.PowerFlex) + && !copiedInPlaceOnKvm) { throw new InvalidParameterValueException("Migration of encrypted volumes is unsupported"); } @@ -4008,6 +4020,22 @@ private boolean isSourceAndDestOnStorPool(StoragePoolVO storagePoolVO, StoragePo && destinationStoragePoolVo.getPoolType() == Storage.StoragePoolType.StorPool; } + /** + * A volume of a running Instance is live migrated in place on the host the Instance runs on, so a local (host scoped) + * pool involved in the migration must be the local pool of that very host. + */ + protected void checkLocalPoolsOnHostOfRunningVm(VMInstanceVO vm, StoragePoolVO srcPool, StoragePoolVO destPool) { + for (StoragePoolVO pool : new StoragePoolVO[] {srcPool, destPool}) { + if (pool == null || !Storage.StoragePoolType.Filesystem.equals(pool.getPoolType())) { + continue; + } + if (vm.getHostId() == null || _storagePoolHostDao.findByPoolHost(pool.getId(), vm.getHostId()) == null) { + throw new InvalidParameterValueException(String.format("The volume of a running Instance can only be migrated to or from the local storage pool %s " + + "of the host the Instance is running on", pool.getName())); + } + } + } + /** * Retrieves the new disk offering UUID that might be sent to replace the current one in the volume being migrated. * If no disk offering UUID is provided we return null. Otherwise, we perform the following checks. diff --git a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java index 401b12ebbf46..cafa69e7b08c 100644 --- a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java +++ b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java @@ -126,6 +126,7 @@ import com.cloud.storage.clvm.ClvmPoolManager; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolTagsDao; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VolumeDao; @@ -145,6 +146,7 @@ import com.cloud.vm.DiskProfile; import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; +import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineManager; @@ -163,6 +165,8 @@ public class VolumeApiServiceImplTest { @InjectMocks private VolumeApiServiceImpl volumeApiServiceImpl = new VolumeApiServiceImpl(); @Mock + private StoragePoolHostDao storagePoolHostDaoMock; + @Mock private SnapshotManager snapshotManagerMock; @Mock private VolumeDataStoreDao volumeDataStoreDaoMock; @@ -2971,6 +2975,65 @@ public void testResizeVolumeInternal_VMware_VMRunning_ShouldThrowStateGuardError } } + private StoragePoolVO poolOfType(long id, Storage.StoragePoolType type) { + StoragePoolVO pool = mock(StoragePoolVO.class); + lenient().when(pool.getId()).thenReturn(id); + lenient().when(pool.getName()).thenReturn("pool-" + id); + lenient().when(pool.getPoolType()).thenReturn(type); + return pool; + } + + @Test + public void checkLocalPoolsOnHostOfRunningVmAcceptsLocalPoolOfTheHostOfTheInstance() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getHostId()).thenReturn(10L); + StoragePoolVO rbd = poolOfType(1L, Storage.StoragePoolType.RBD); + StoragePoolVO local = poolOfType(2L, Storage.StoragePoolType.Filesystem); + when(storagePoolHostDaoMock.findByPoolHost(2L, 10L)).thenReturn(mock(StoragePoolHostVO.class)); + + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, rbd, local); + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, local, rbd); + } + + @Test(expected = InvalidParameterValueException.class) + public void checkLocalPoolsOnHostOfRunningVmRejectsLocalPoolOfAnotherHost() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getHostId()).thenReturn(10L); + StoragePoolVO rbd = poolOfType(1L, Storage.StoragePoolType.RBD); + StoragePoolVO local = poolOfType(2L, Storage.StoragePoolType.Filesystem); + when(storagePoolHostDaoMock.findByPoolHost(2L, 10L)).thenReturn(null); + + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, rbd, local); + } + + @Test(expected = InvalidParameterValueException.class) + public void checkLocalPoolsOnHostOfRunningVmRejectsLocalSourcePoolOfAnotherHost() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getHostId()).thenReturn(10L); + StoragePoolVO local = poolOfType(2L, Storage.StoragePoolType.Filesystem); + StoragePoolVO rbd = poolOfType(1L, Storage.StoragePoolType.RBD); + when(storagePoolHostDaoMock.findByPoolHost(2L, 10L)).thenReturn(null); + + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, local, rbd); + } + + @Test(expected = InvalidParameterValueException.class) + public void checkLocalPoolsOnHostOfRunningVmRejectsLocalPoolWithoutHostOfTheInstance() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getHostId()).thenReturn(null); + + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, poolOfType(1L, Storage.StoragePoolType.RBD), poolOfType(2L, Storage.StoragePoolType.Filesystem)); + } + + @Test + public void checkLocalPoolsOnHostOfRunningVmIgnoresPoolsWhichAreNotLocal() { + VMInstanceVO vm = mock(VMInstanceVO.class); + + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, poolOfType(1L, Storage.StoragePoolType.RBD), poolOfType(2L, Storage.StoragePoolType.NetworkFilesystem)); + volumeApiServiceImpl.checkLocalPoolsOnHostOfRunningVm(vm, poolOfType(3L, Storage.StoragePoolType.SharedMountPoint), poolOfType(1L, Storage.StoragePoolType.RBD)); + Mockito.verifyNoInteractions(storagePoolHostDaoMock); + } + private Long invokeGetDeviceId(UserVmVO vm, Long deviceId) throws Exception { java.lang.reflect.Method method = VolumeApiServiceImpl.class.getDeclaredMethod("getDeviceId", UserVmVO.class, Long.class); method.setAccessible(true); diff --git a/test/integration/smoke/test_volume_migration_rbd_nfs.py b/test/integration/smoke/test_volume_migration_rbd_nfs.py new file mode 100644 index 000000000000..f2cb33f6e713 --- /dev/null +++ b/test/integration/smoke/test_volume_migration_rbd_nfs.py @@ -0,0 +1,681 @@ +# 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. +""" BVT tests for volume migration between RBD (Ceph) and NFS primary +storage pools on KVM. + +Every combination below is covered, for plain volumes +(TestVolumeMigrationRbdNfs) as well as for encrypted volumes +(TestEncryptedVolumeMigrationRbdNfs): + +* source and destination pool: RBD -> NFS, NFS -> RBD, NFS -> NFS and + RBD -> RBD +* online (the Instance keeps running, migrateVolume with livemigrate) and + offline (the Instance is stopped, or the volume is not attached) +* ROOT and DATA volumes +* volumes with and without a backing chain: every test deploys its own + Instance on its source pool, so the first migration moves a ROOT volume + cloned from the template (a qcow2 backing file on NFS, an RBD clone on + Ceph); the DATA volume, and the ROOT volume once it was migrated, have no + chain. + +Besides the volume being on the expected pool, the data of each volume is +verified on the host after every migration, as the Instance sees it (that is, +decrypted): a pattern written to the DATA volume, and a checksum of the boot +area of the ROOT volume. For encrypted volumes the encryption the destination +pool requires is verified too: native librbd LUKS2 on RBD, qemu LUKS on NFS. + +Requirements: KVM, an RBD pool and the "nfs" primary storage of the test +data. The NFS -> NFS migrations also need the "nfs2" primary storage and the +RBD -> RBD migrations a second RBD pool; those are skipped otherwise. The +encrypted volume tests need a host with RBD volume encryption support. +""" + +import base64 +import hashlib +import re +import xml.etree.ElementTree as ET + +from marvin.cloudstackAPI import (deleteStoragePool, + detachVolume, + enableStorageMaintenance) +from marvin.cloudstackTestCase import cloudstackTestCase +from marvin.lib.base import (Account, + DiskOffering, + Host, + ServiceOffering, + StoragePool, + Template, + VirtualMachine, + Volume) +from marvin.lib.common import (get_domain, + get_pod, + get_zone, + list_clusters, + list_hosts, + list_storage_pools) +from marvin.lib.utils import random_gen +from marvin.sshClient import SshClient + +from nose.plugins.attrib import attr + +_multiprocess_shared_ = False + +# KVM copies a volume in place only between two RBD pools, or between an RBD pool and a file based +# one (Storage.isMigrationBetweenRbdOrRbdAndFileBased). A migration between two file based pools is +# refused, with this message for a live one and the next for an encrypted volume, so the tests which +# ask for one assert the refusal instead of the move. +LIVE_MIGRATION_REFUSED = "KVM does not support volume live migration" +ENCRYPTED_MIGRATION_REFUSED = "Migration of encrypted volumes is unsupported" + +# Runs on the host of an Instance to access one of its disks as the Instance sees it, i.e. decrypted: +# disk-io.sh write|read "" +# A write goes through the HMP qemu-io command of the disk device. A read goes through a read-only NBD +# export of the node of the disk, as the output of HMP qemu-io ends up (buffered) in the log of qemu. +DISK_IO_SCRIPT = r''' +dom=$1; dev=$2; mode=$3; cmd=$4 +qmp() { virsh qemu-monitor-command "$dom" "$1"; } +read qdev node <<<$(qmp '{"execute":"query-block"}' | python3 -c ' +import json, sys +for b in json.load(sys.stdin)["return"]: + q = b.get("qdev", "") + if sys.argv[1] in (q, b.get("device", "")) or q.startswith("/machine/peripheral/%s/" % sys.argv[1]): + print(q or b["device"], b["inserted"]["node-name"]) + break' "$dev") +[ -z "$node" ] && { echo "no block node found for disk $dev"; exit 1; } +if [ "$mode" = write ]; then + virsh qemu-monitor-command "$dom" --hmp "qemu-io -d $qdev \"$cmd\"" + exit $? +fi +sock=$(ls -d /var/lib/libvirt/qemu/domain-*-$dom | head -1)/volume-migration-test.sock +qmp "{\"execute\":\"nbd-server-start\",\"arguments\":{\"addr\":{\"type\":\"unix\",\"data\":{\"path\":\"$sock\"}}}}" >/dev/null +qmp "{\"execute\":\"block-export-add\",\"arguments\":{\"type\":\"nbd\",\"id\":\"volmig\",\"node-name\":\"$node\",\"writable\":false}}" >/dev/null +qemu-io -r -f raw "nbd+unix:///$node?socket=$sock" -c "$cmd" +rc=$? +qmp '{"execute":"block-export-del","arguments":{"id":"volmig"}}' >/dev/null +sleep 1 +qmp '{"execute":"nbd-server-stop"}' >/dev/null +exit $rc +''' +DISK_IO_SCRIPT_PATH = "/tmp/cs-volume-migration-test-disk-io.sh" + +DATA_PATTERN = "0xa5" +DATA_PATTERN_OFFSET = "1M" +DATA_PATTERN_LENGTH = "4M" +DATA_PATTERN_BYTES = 4 * 1024 * 1024 +# The start of a ROOT volume that the guest does not write to: the MBR and the boot loader behind it. Not further on: +# the guest updates its file systems (e.g. the mount time in the superblock of /boot) while it runs, and an encrypted +# thin RBD clone of a template reads as noise where its template is empty, once its object was written to (librbd), +# which a copy of the volume to another pool does not keep. +ROOT_CHECKSUM_LENGTH = "4k" + + +class VolumeMigrationRbdNfsBase(cloudstackTestCase): + """Set up and helpers of the volume migration tests between RBD and NFS pools on KVM""" + + # whether the ROOT and DATA volumes of the Instances are encrypted + encrypted = False + + @classmethod + def setUpClass(cls): + testClient = super(VolumeMigrationRbdNfsBase, cls).getClsTestClient() + cls.apiclient = testClient.getApiClient() + cls.dbclient = testClient.getDbConnection() + cls.services = testClient.getParsedTestDataConfig() + cls._cleanup = [] + cls.created_pools = [] + cls.saved_pool_tags = {} + cls.unsupported_reason = None + + cls.domain = get_domain(cls.apiclient) + cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) + cls.pod = get_pod(cls.apiclient, cls.zone.id) + cls.services['mode'] = cls.zone.networktype + cls.hypervisor = testClient.getHypervisorInfo() + + if cls.hypervisor.lower() != 'kvm': + cls.unsupported_reason = "requires KVM" + return + + rbd_pools = [pool for pool in list_storage_pools(cls.apiclient, zoneid=cls.zone.id) or [] + if pool.type == 'RBD' and pool.state == 'Up'] + if not rbd_pools: + cls.unsupported_reason = "requires an RBD storage pool" + return + cls.rbd_pool = rbd_pools[0] + cls.rbd_pool2 = rbd_pools[1] if len(rbd_pools) > 1 else None + + cls.cluster = None + for cluster in list_clusters(cls.apiclient, zoneid=cls.zone.id) or []: + if list_hosts(cls.apiclient, clusterid=cluster.id): + cls.cluster = cluster + break + if cls.cluster is None: + cls.unsupported_reason = "requires a cluster with hosts" + return + + cls.host_config = cls.config.__dict__["zones"][0].__dict__["pods"][0].__dict__["clusters"][0].__dict__["hosts"][0].__dict__ + + if cls.encrypted and not cls.host_with_rbd_encryption_support_exists(): + cls.unsupported_reason = "requires a host with RBD volume encryption support" + return + + cls.template = Template.register( + cls.apiclient, + cls.services["test_templates_cloud_init"][cls.hypervisor.lower()], + zoneid=cls.zone.id, + hypervisor=cls.hypervisor, + ) + cls.template.download(cls.apiclient) + + cls.services["domainid"] = cls.domain.id + cls.services["zoneid"] = cls.zone.id + cls.services["template"] = cls.template.id + + cls.account = Account.create( + cls.apiclient, + cls.services["account"], + domainid=cls.domain.id + ) + cls._cleanup.append(cls.account) + + # The offerings carry a storage tag of their own, which is put on the pool an Instance has to be + # deployed on, and on all the pools the volumes are migrated between. + cls.pool_tag = "volmig-" + random_gen(size=6).lower() + encryption_args = {"encryptroot": True} if cls.encrypted else {} + cls.service_offering = ServiceOffering.create( + cls.apiclient, + cls.services["service_offerings"]["tiny"], + tags=cls.pool_tag, + **encryption_args + ) + cls._cleanup.append(cls.service_offering) + + encryption_args = {"encrypt": True} if cls.encrypted else {} + cls.disk_offering = DiskOffering.create( + cls.apiclient, + cls.services["disk_offering"], + tags=cls.pool_tag, + **encryption_args + ) + cls._cleanup.append(cls.disk_offering) + + cls.nfs_pool = cls.create_nfs_pool(cls.services["nfs"]) + cls.nfs_pool2 = cls.create_nfs_pool(cls.services["nfs2"]) if "nfs2" in cls.services else None + + cls.pools = [pool for pool in (cls.rbd_pool, cls.rbd_pool2, cls.nfs_pool, cls.nfs_pool2) if pool is not None] + for pool in cls.pools: + cls.saved_pool_tags[pool.id] = getattr(pool, 'tags', "") or "" + + @classmethod + def create_nfs_pool(cls, services): + pool = StoragePool.create( + cls.apiclient, + services, + clusterid=cls.cluster.id, + zoneid=cls.zone.id, + podid=cls.pod.id + ) + cls.created_pools.append(pool) + return pool + + @classmethod + def host_with_rbd_encryption_support_exists(cls): + # librbd encryption support is only tracked in host_details, it is not part of the API response + hosts = Host.list(cls.apiclient, zoneid=cls.zone.id, type='Routing', hypervisor='KVM', state='Up') or [] + for host in hosts: + supported = cls.dbclient.execute( + "select hd.value from host_details hd join host h on h.id=hd.host_id " + "where h.uuid='%s' and hd.name='host.volume.encryption.rbd'" % host.id + ) + if supported and supported[0][0].lower() == 'true': + return True + return False + + @classmethod + def tag_pools(cls, pools): + """Put the storage tag of the offerings on the given pools (on top of their own tags) and remove it + from the other ones""" + for pool in cls.pools: + tags = [tag for tag in cls.saved_pool_tags[pool.id].split(",") if tag] + if pool in pools: + tags.append(cls.pool_tag) + StoragePool.update(cls.apiclient, id=pool.id, tags=",".join(tags)) + + @classmethod + def tearDownClass(cls): + try: + super(VolumeMigrationRbdNfsBase, cls).tearDownClass() + finally: + for pool in getattr(cls, 'pools', []): + try: + StoragePool.update(cls.apiclient, id=pool.id, tags=cls.saved_pool_tags[pool.id]) + except Exception as e: + cls.debug("Warning: failed to restore the tags of storage pool %s: %s" % (pool.id, e)) + for pool in cls.created_pools: + cls.delete_storage_pool(pool) + + @classmethod + def delete_storage_pool(cls, pool): + """Put the pool in maintenance and force delete it, so a volume left + behind by a failed test does not leak the pool into the next run.""" + try: + cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() + cmd.id = pool.id + cls.apiclient.enableStorageMaintenance(cmd) + cmd = deleteStoragePool.deleteStoragePoolCmd() + cmd.id = pool.id + cmd.forced = True + cls.apiclient.deleteStoragePool(cmd) + except Exception as e: + cls.debug("Warning: failed to delete storage pool %s: %s" % (pool.id, e)) + + def setUp(self): + self.apiclient = self.testClient.getApiClient() + self.cleanup = [] + if self.unsupported_reason: + self.skipTest("Skipping test: %s" % self.unsupported_reason) + + def tearDown(self): + super(VolumeMigrationRbdNfsBase, self).tearDown() + + def require_pools(self, *pools): + if None in pools: + self.skipTest("Skipping test: requires a second NFS (\"nfs2\" in the test data) or RBD storage pool") + + def require_rbd_encrypted_hotplug(self): + """libvirt < 10.1.0 cannot hot-plug or live migrate an encrypted RBD volume of a running Instance + (the agent refuses it), so the tests that do so are skipped on such hosts""" + hosts = Host.list(self.apiclient, zoneid=self.zone.id, type='Routing', hypervisor='KVM', state='Up') or [] + for host in hosts: + ssh = SshClient(host=host.ipaddress, port=22, user=self.host_config['username'], + passwd=self.host_config['password']) + out = ssh.execute("virsh version | awk '/Using library/{print $NF}'") + version = [int(v) for v in re.findall(r'\d+', (out[-1] if out else "0.0.0"))[:3]] + if version < [10, 1, 0]: + self.skipTest("Skipping test: libvirt %s on host %s cannot attach or live migrate an encrypted " + "RBD volume of a running Instance (libvirt 10.1.0 is required)" + % (".".join(map(str, version)), host.name)) + + # Instances and volumes + + def deploy_instance(self, pool): + """Deploy an Instance with a DATA volume, both volumes allocated on the given pool. The ROOT volume + is cloned from the template, so it has a backing chain (a qcow2 backing file or an RBD parent).""" + self.tag_pools([pool]) + try: + instance = VirtualMachine.create( + self.apiclient, + self.services, + accountid=self.account.name, + domainid=self.account.domainid, + serviceofferingid=self.service_offering.id, + mode=self.services["mode"] + ) + self.cleanup.append(instance) + data_volume = Volume.create( + self.apiclient, + self.services, + account=self.account.name, + domainid=self.account.domainid, + diskofferingid=self.disk_offering.id + ) + self.cleanup.append(data_volume) + instance.attach_volume(self.apiclient, data_volume) + finally: + self.tag_pools(self.pools) + + root_volume = Volume.list(self.apiclient, virtualmachineid=instance.id, type='ROOT', listall=True)[0] + for volume in (root_volume, data_volume): + self.assert_volume_on_pool(volume, pool) + # Destroying the Instance does not remove its DATA volume, which is to be detached first + self.cleanup.remove(data_volume) + self.cleanup.insert(0, _DetachedVolume(self.apiclient, data_volume)) + return instance, root_volume, data_volume + + def migrate_online(self, instance, volumes, pool): + for volume in volumes: + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=pool.id, livemigrate=True) + self.assert_instance_state(instance, 'Running') + + def hop_between_file_based_pools(self, source_pool, destination_pool): + """Whether a hop cannot be made in place: a volume is only copied between two RBD pools, or + between an RBD pool and a file based one, so two file based pools are the case to avoid.""" + return source_pool.type != 'RBD' and destination_pool.type != 'RBD' + + def assert_migration_refused(self, volume, pool, expected, livemigrate): + """Assert that migrating volume to pool is refused, and refused for the expected reason.""" + try: + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=pool.id, livemigrate=livemigrate) + except Exception as error: + self.assertIn(expected, str(error), + "Expected the migration to %s to be refused as unsupported, but it failed with: %s" + % (pool.name, error)) + else: + self.fail("Migration of volume %s to %s should have been refused" % (volume.id, pool.name)) + + def migrate_offline(self, instance, volumes, pool): + instance.stop(self.apiclient) + for volume in volumes: + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=pool.id, livemigrate=False) + instance.start(self.apiclient) + + def migrate_detached(self, instance, volume, pool): + # the Instance is stopped, as not every disk bus (e.g. IDE) supports hot unplugging + instance.stop(self.apiclient) + instance.detach_volume(self.apiclient, volume) + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=pool.id, livemigrate=False) + instance.attach_volume(self.apiclient, volume) + instance.start(self.apiclient) + + def run_migrations(self, source_pool, destination_pools, online): + """Deploy an Instance on source_pool and migrate its ROOT and DATA volumes along destination_pools, + verifying the volumes after every migration, and again after restarting the Instance.""" + instance, root_volume, data_volume = self.deploy_instance(source_pool) + disks = InstanceDisks(self, instance, root_volume, data_volume) + disks.mark() + + current_pool = source_pool + for pool in destination_pools: + if self.hop_between_file_based_pools(current_pool, pool): + if online: + # the volume is attached to a running Instance, so the live migration check + # answers the migration + self.assert_migration_refused(root_volume, pool, LIVE_MIGRATION_REFUSED, True) + continue + if self.encrypted: + # stop the Instance, as migrate_offline does, so that the encrypted volume + # check answers the migration rather than the live migration one + instance.stop(self.apiclient) + self.assert_migration_refused(root_volume, pool, ENCRYPTED_MIGRATION_REFUSED, False) + instance.start(self.apiclient) + continue + # an offline hop of a plain volume between two file based pools is allowed, + # and is made below + if online: + self.migrate_online(instance, (root_volume, data_volume), pool) + else: + self.migrate_offline(instance, (root_volume, data_volume), pool) + current_pool = pool + self.verify_volumes(instance, disks, (root_volume, data_volume), pool) + # the volumes also have to be usable when the Instance is started again + instance.stop(self.apiclient) + instance.start(self.apiclient) + self.verify_volumes(instance, disks, (root_volume, data_volume), pool) + + # Checks + + def verify_volumes(self, instance, disks, volumes, pool): + for volume in volumes: + self.assert_volume_on_pool(volume, pool) + self.assert_instance_state(instance, 'Running') + disks.verify(volumes, pool) + + def assert_volume_on_pool(self, volume, pool): + migrated_volume = Volume.list(self.apiclient, id=volume.id, listall=True)[0] + self.assertEqual( + migrated_volume.storageid, + pool.id, + "Volume %s is on storage pool %s instead of %s" % (volume.id, migrated_volume.storage, pool.name) + ) + self.assertEqual(migrated_volume.state, 'Ready', "Volume %s is not Ready after the migration" % volume.id) + + def assert_instance_state(self, instance, state): + self.assertEqual( + VirtualMachine.list(self.apiclient, id=instance.id)[0].state, + state, + "Instance %s is not %s" % (instance.id, state) + ) + + # The tests + + def online_migration_from_rbd(self): + """Online migrate a ROOT volume with a backing chain (an RBD clone of the template) and a DATA volume + from RBD to NFS, then (without chain) NFS -> NFS, NFS -> RBD and RBD -> RBD""" + self.run_migrations(self.rbd_pool, [pool for pool in (self.nfs_pool, self.nfs_pool2, self.rbd_pool, self.rbd_pool2) + if pool is not None], online=True) + + def online_migration_from_nfs(self, destination_pool): + """Online migrate a ROOT volume with a backing chain (a qcow2 file backed by the template) and a DATA + volume from NFS to destination_pool""" + self.run_migrations(self.nfs_pool, [destination_pool], online=True) + + def offline_migration_from_rbd(self): + """Offline migrate a ROOT volume with a backing chain (an RBD clone of the template) and a DATA volume + from RBD to NFS, then (without chain) NFS -> NFS, NFS -> RBD and RBD -> RBD""" + self.run_migrations(self.rbd_pool, [pool for pool in (self.nfs_pool, self.nfs_pool2, self.rbd_pool, self.rbd_pool2) + if pool is not None], online=False) + + def offline_migration_from_nfs(self, destination_pool): + """Offline migrate a ROOT volume with a backing chain (a qcow2 file backed by the template) and a DATA + volume from NFS to destination_pool""" + self.run_migrations(self.nfs_pool, [destination_pool], online=False) + + def detached_volume_migration(self): + """Migrate a DATA volume that is not attached to an Instance between all the pools""" + instance, root_volume, data_volume = self.deploy_instance(self.rbd_pool) + disks = InstanceDisks(self, instance, root_volume, data_volume) + disks.mark() + current_pool = self.rbd_pool + for pool in [pool for pool in (self.nfs_pool, self.nfs_pool2, self.rbd_pool2, self.rbd_pool) if pool is not None]: + if self.encrypted and self.hop_between_file_based_pools(current_pool, pool): + # detach the volume first, as migrate_detached does, so that the encrypted volume + # check answers the migration rather than the live migration one + instance.stop(self.apiclient) + instance.detach_volume(self.apiclient, data_volume) + self.assert_migration_refused(data_volume, pool, ENCRYPTED_MIGRATION_REFUSED, False) + instance.attach_volume(self.apiclient, data_volume) + instance.start(self.apiclient) + continue + self.migrate_detached(instance, data_volume, pool) + current_pool = pool + self.verify_volumes(instance, disks, (data_volume,), pool) + + +class _DetachedVolume: + """Cleanup wrapper that detaches a DATA volume (if it still is attached) before deleting it""" + + def __init__(self, apiclient, volume): + self.apiclient = apiclient + self.volume = volume + + def delete(self, apiclient): + volumes = Volume.list(apiclient, id=self.volume.id, listall=True) + if not volumes: + return + if getattr(volumes[0], 'virtualmachineid', None): + cmd = detachVolume.detachVolumeCmd() + cmd.id = self.volume.id + apiclient.detachVolume(cmd) + self.volume.delete(apiclient) + + +class InstanceDisks: + """Verifies the data of the ROOT and DATA volumes of an Instance on its host, as the Instance sees them + (decrypted): a pattern written to the DATA volume, and a checksum of the boot area of the ROOT volume, and that + the Instance sees the size of each volume. For encrypted volumes, the encryption of the disks in the XML domain + of the Instance is verified as well.""" + + def __init__(self, test, instance, root_volume, data_volume): + self.test = test + self.instance = instance + self.root_volume = root_volume + self.data_volume = data_volume + self.root_checksum = None + + def _host_ssh(self): + vm = VirtualMachine.list(self.test.apiclient, id=self.instance.id)[0] + host = Host.list(self.test.apiclient, id=vm.hostid)[0] + ssh = SshClient(host=host.ipaddress, port=22, user=self.test.host_config['username'], + passwd=self.test.host_config['password']) + script = base64.b64encode(DISK_IO_SCRIPT.encode()).decode() + ssh.execute("echo %s | base64 -d > %s" % (script, DISK_IO_SCRIPT_PATH)) + return ssh, vm.instancename + + def _disk(self, ssh, instance_name, volume): + """The disk element of the volume in the XML domain; its serial is the start of the volume uuid""" + domain = ET.fromstring("\n".join(ssh.execute("virsh dumpxml %s" % instance_name))) + serial = volume.id.replace("-", "")[:20] + for disk in domain.findall("./devices/disk"): + if disk.findtext("serial") == serial: + return disk + self.test.fail("Disk of volume %s not found in the XML domain of %s" % (volume.id, instance_name)) + + def _disk_io(self, volume, mode, command): + ssh, instance_name = self._host_ssh() + alias = self._disk(ssh, instance_name, volume).find("alias").get("name") + return "\n".join(ssh.execute("bash %s %s %s %s '%s' 2>&1" % (DISK_IO_SCRIPT_PATH, instance_name, alias, mode, command))) + + def _root_checksum(self): + dump = [line for line in self._disk_io(self.root_volume, "read", "read -v 0 %s" % ROOT_CHECKSUM_LENGTH).splitlines() + if re.match(r"^[0-9a-f]{8}:", line)] + return hashlib.md5("\n".join(dump).encode()).hexdigest() if dump else None + + def _data_pattern_present(self): + out = self._disk_io(self.data_volume, "read", "read -P %s %s %s" % (DATA_PATTERN, DATA_PATTERN_OFFSET, DATA_PATTERN_LENGTH)) + return "verification failed" not in out and ("read %d/%d bytes" % (DATA_PATTERN_BYTES, DATA_PATTERN_BYTES)) in out + + def mark(self): + self._disk_io(self.data_volume, "write", "write -P %s %s %s" % (DATA_PATTERN, DATA_PATTERN_OFFSET, DATA_PATTERN_LENGTH)) + self.test.assertTrue(self._data_pattern_present(), "Failed to write the test pattern to volume %s" % self.data_volume.id) + self.root_checksum = self._root_checksum() + self.test.assertIsNotNone(self.root_checksum, "Failed to read volume %s" % self.root_volume.id) + + def verify(self, volumes, pool): + for volume in volumes: + if volume.id == self.data_volume.id: + self.test.assertTrue(self._data_pattern_present(), + "The data of volume %s is not intact after the migration to %s" % (volume.id, pool.name)) + else: + self.test.assertEqual(self._root_checksum(), self.root_checksum, + "The data of volume %s is not intact after the migration to %s" % (volume.id, pool.name)) + self._verify_size(volume, pool) + if self.test.encrypted: + self._verify_encryption(volume, pool) + + def _verify_size(self, volume, pool): + """The Instance sees the size of the volume on every pool type: an encrypted volume is created with room for + its encryption header, which librbd keeps in front of the data of an RBD image""" + ssh, instance_name = self._host_ssh() + target = self._disk(ssh, instance_name, volume).find("target").get("dev") + info = "\n".join(ssh.execute("virsh domblkinfo %s %s" % (instance_name, target))) + capacity = int(re.search(r"Capacity:\s+(\d+)", info).group(1)) + size = int(Volume.list(self.test.apiclient, id=volume.id, listall=True)[0].size) + self.test.assertEqual(capacity, size, "The Instance sees %d bytes of volume %s on %s, instead of its size of %d bytes" + % (capacity, volume.id, pool.name, size)) + + def _verify_encryption(self, volume, pool): + """An RBD volume is encrypted natively by librbd (LUKS2), a volume on NFS by qemu (LUKS)""" + ssh, instance_name = self._host_ssh() + disk = self._disk(ssh, instance_name, volume) + encryption = disk.find("encryption") + if encryption is None: + encryption = disk.find("source/encryption") + self.test.assertIsNotNone(encryption, "Volume %s is not encrypted after the migration to %s" % (volume.id, pool.name)) + if pool.type == 'RBD': + self.test.assertEqual(encryption.get("format"), "luks2") + self.test.assertEqual(encryption.get("engine"), "librbd") + else: + self.test.assertEqual(encryption.get("format"), "luks") + self.test.assertNotEqual(encryption.get("engine"), "librbd") + + +class TestVolumeMigrationRbdNfs(VolumeMigrationRbdNfsBase): + """Migration of plain volumes between RBD and NFS pools on KVM""" + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_01_online_migration_from_rbd(self): + """Online migration: RBD (ROOT with chain) -> NFS -> NFS -> RBD -> RBD""" + self.online_migration_from_rbd() + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_02_online_migration_from_nfs_to_rbd(self): + """Online migration: NFS (ROOT with chain) -> RBD""" + self.online_migration_from_nfs(self.rbd_pool) + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_03_online_migration_from_nfs_to_nfs(self): + """Online migration: NFS (ROOT with chain) -> NFS is refused, as both pools are file based""" + self.require_pools(self.nfs_pool2) + self.online_migration_from_nfs(self.nfs_pool2) + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_04_offline_migration_from_rbd(self): + """Offline migration: RBD (ROOT with chain) -> NFS -> NFS -> RBD -> RBD""" + self.offline_migration_from_rbd() + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_05_offline_migration_from_nfs_to_rbd(self): + """Offline migration: NFS (ROOT with chain) -> RBD""" + self.offline_migration_from_nfs(self.rbd_pool) + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_06_offline_migration_from_nfs_to_nfs(self): + """Offline migration: NFS (ROOT with chain) -> NFS""" + self.require_pools(self.nfs_pool2) + self.offline_migration_from_nfs(self.nfs_pool2) + + @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="true") + def test_07_detached_volume_migration(self): + """Migration of a detached DATA volume: RBD -> NFS -> NFS -> RBD -> RBD""" + self.detached_volume_migration() + + +class TestEncryptedVolumeMigrationRbdNfs(VolumeMigrationRbdNfsBase): + """Migration of encrypted volumes between RBD and NFS pools on KVM""" + + encrypted = True + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_01_encrypted_online_migration_from_rbd(self): + """Online migration of encrypted volumes: RBD (ROOT with chain) -> NFS -> NFS -> RBD -> RBD""" + self.require_rbd_encrypted_hotplug() + self.online_migration_from_rbd() + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_02_encrypted_online_migration_from_nfs_to_rbd(self): + """Online migration of encrypted volumes: NFS (ROOT with chain) -> RBD""" + self.require_rbd_encrypted_hotplug() + self.online_migration_from_nfs(self.rbd_pool) + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_03_encrypted_online_migration_from_nfs_to_nfs(self): + """Online migration of encrypted volumes: NFS -> NFS is refused, as both pools are file based""" + self.require_pools(self.nfs_pool2) + self.online_migration_from_nfs(self.nfs_pool2) + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_04_encrypted_offline_migration_from_rbd(self): + """Offline migration of encrypted volumes: RBD (ROOT with chain) -> NFS -> NFS -> RBD -> RBD""" + self.require_rbd_encrypted_hotplug() + self.offline_migration_from_rbd() + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_05_encrypted_offline_migration_from_nfs_to_rbd(self): + """Offline migration of encrypted volumes: NFS (ROOT with chain) -> RBD""" + self.offline_migration_from_nfs(self.rbd_pool) + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_06_encrypted_offline_migration_from_nfs_to_nfs(self): + """Offline migration of encrypted volumes: NFS (ROOT with chain) -> NFS""" + self.require_pools(self.nfs_pool2) + self.offline_migration_from_nfs(self.nfs_pool2) + + @attr(tags=["advanced", "advancedns", "smoke", "diskencrypt"], required_hardware="true") + def test_07_encrypted_detached_volume_migration(self): + """Migration of a detached encrypted DATA volume: RBD -> NFS -> NFS -> RBD -> RBD""" + self.require_rbd_encrypted_hotplug() + self.detached_volume_migration() diff --git a/test/integration/smoke/test_volumes.py b/test/integration/smoke/test_volumes.py index f1d6461d0a47..22a07a457050 100644 --- a/test/integration/smoke/test_volumes.py +++ b/test/integration/smoke/test_volumes.py @@ -17,6 +17,7 @@ """ BVT tests for Volumes """ import os +import re import tempfile import time import math @@ -45,7 +46,7 @@ get_pod, list_storage_pools, list_disk_offering) -from marvin.lib.utils import (cleanup_resources, checkVolumeSize) +from marvin.lib.utils import (cleanup_resources, checkVolumeSize, random_gen) from marvin.lib.utils import (format_volume_to_ext3, wait_until) from marvin.sshClient import SshClient @@ -54,6 +55,9 @@ from nose.plugins.attrib import attr +# md5 of no data at all +EMPTY_MD5 = "d41d8cd98f00b204e9800998ecf8427e" + _multiprocess_shared_ = True @@ -1030,9 +1034,6 @@ def test_13_migrate_volume_and_change_offering(self): self.virtual_machine.attach_volume(self.apiclient, volume=volume) - if self.virtual_machine.hypervisor == "KVM": - self.virtual_machine.stop(self.apiclient) - pools = StoragePool.listForMigration( self.apiclient, id=volume.id @@ -1045,6 +1046,15 @@ def test_13_migrate_volume_and_change_offering(self): else: raise self.skipTest("Not enough storage pools found, skipping test") + # KVM can live migrate a volume of a running VM only between RBD pools; + # any other KVM source/destination combination needs the VM stopped first. + current_vol = Volume.list(self.apiclient, id=volume.id)[0] + source_pool = list_storage_pools(self.apiclient, id=current_vol.storageid)[0] + kvm_rbd_live_migration = source_pool.type == 'RBD' and pool.type == 'RBD' + + if self.virtual_machine.hypervisor == "KVM" and not kvm_rbd_live_migration: + self.virtual_machine.stop(self.apiclient) + if hasattr(pool, 'tags'): StoragePool.update(self.apiclient, id=pool.id, tags="") @@ -1052,6 +1062,8 @@ def test_13_migrate_volume_and_change_offering(self): livemigrate = False if self.virtual_machine.hypervisor.lower() == "vmware" or self.virtual_machine.hypervisor.lower() == 'xenserver': livemigrate = True + elif self.virtual_machine.hypervisor == "KVM" and kvm_rbd_live_migration: + livemigrate = True Volume.migrate( self.apiclient, @@ -1060,7 +1072,7 @@ def test_13_migrate_volume_and_change_offering(self): newdiskofferingid=large_offering.id, livemigrate=livemigrate ) - if self.virtual_machine.hypervisor == "KVM": + if self.virtual_machine.hypervisor == "KVM" and not kvm_rbd_live_migration: self.virtual_machine.start(self.apiclient) migrated_vol = Volume.list( self.apiclient, @@ -1122,6 +1134,18 @@ def setUpClass(cls): # RBD pools are encrypted natively by librbd (LUKS2, engine='librbd'); any other pool type # goes through qemu-native encryption (LUKS1, no engine attribute). cls.storage_pool_type = volume_pool.type + # In a zone with pools of several types, the encrypted volumes are kept on the pools of the type the tests + # check, with a storage tag of their own added to those pools (their tags are restored in tearDownClass) + cls.encryption_storage_tag = None + cls.tagged_pools = [] + if any(pool.type != cls.storage_pool_type for pool in list_volume_pool_response): + cls.encryption_storage_tag = "volenc-" + random_gen(size=6).lower() + for pool in list_volume_pool_response: + if pool.type == cls.storage_pool_type: + tags = getattr(pool, "tags", None) or "" + cls.tagged_pools.append((pool.id, tags)) + StoragePool.update(cls.apiclient, id=pool.id, tags=",".join([t for t in (tags, cls.encryption_storage_tag) if t])) + encryption_tags = {"tags": cls.encryption_storage_tag} if cls.encryption_storage_tag else {} # Get Zone and Domain cls.domain = get_domain(cls.apiclient) @@ -1167,7 +1191,8 @@ def setUpClass(cls): cls.apiclient, cls.services["service_offerings"]["small"], name="Small Encrypted Instance", - encryptroot=True + encryptroot=True, + **encryption_tags ) cls._cleanup.append(cls.service_offering_encrypt) @@ -1183,7 +1208,8 @@ def setUpClass(cls): cls.apiclient, cls.services["disk_offering"], name="Encrypted", - encrypt=True + encrypt=True, + **encryption_tags ) cls._cleanup.append(cls.disk_offering_encrypt) @@ -1193,6 +1219,9 @@ def tearDownClass(cls): cleanup_resources(cls.apiclient, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) + finally: + for pool_id, tags in getattr(cls, "tagged_pools", []): + StoragePool.update(cls.apiclient, id=pool_id, tags=tags) return def setUp(self): @@ -1352,6 +1381,7 @@ def test_02_data_volume_encryption(self): # 3. Create Data Volume using the disk offering with encrypt true # 4. Verify Data Volume """ + self.skip_if_rbd_encrypted_hotplug_unsupported() virtual_machine = VirtualMachine.create( self.apiclient, @@ -1490,6 +1520,7 @@ def test_03_root_and_data_volume_encryption(self): # Resize is folded into this test (reusing its VM and volume) rather than a separate # test, since spinning up another VM just for resize coverage would cost a lot more time. """ + self.skip_if_rbd_encrypted_hotplug_unsupported() virtual_machine = VirtualMachine.create( self.apiclient, @@ -1620,7 +1651,8 @@ def test_03_root_and_data_volume_encryption(self): self.services["disk_offering"], name="Encrypted-2GB", disksize=2, - encrypt=True + encrypt=True, + tags=self.encryption_storage_tag ) self.cleanup.append(disk_offering_encrypt_2gb) @@ -1631,13 +1663,11 @@ def test_03_root_and_data_volume_encryption(self): # CentOS 5.5 predates reliable virtio-blk live-capacity notification), so verify success # through the volume's own reported size here. Guest-visible size is verified below after # the offline resize, once the volume is freshly re-attached. + # The encryption header is not part of the size of the volume, on any pool type list_volume_response = Volume.list(self.apiclient, id=volume.id) - expected_raw_size = disk_offering_encrypt_2gb.disksize << 30 - if self.storage_pool_type == "RBD" and getattr(list_volume_response[0], "encryptformat", None): - expected_raw_size += (16 << 20) self.assertEqual( int(list_volume_response[0].size), - expected_raw_size, + disk_offering_encrypt_2gb.disksize << 30, "Check that the online resize grew the volume to the expected size" ) self.assertEqual(list_volume_response[0].state, 'Ready', "Check that the online-resized volume is Ready") @@ -1652,7 +1682,8 @@ def test_03_root_and_data_volume_encryption(self): self.services["disk_offering"], name="Encrypted-3GB", disksize=3, - encrypt=True + encrypt=True, + tags=self.encryption_storage_tag ) self.cleanup.append(disk_offering_encrypt_3gb) @@ -1677,6 +1708,126 @@ def test_03_root_and_data_volume_encryption(self): virtual_machine.detach_volume(self.apiclient, volume) time.sleep(self.services["sleep"]) + @attr(tags=["advanced", "smoke", "diskencrypt"], required_hardware="true") + def test_04_encrypted_volume_migration_between_rbd_pools(self): + """Test migration of encrypted ROOT and DATA volumes between two RBD (Ceph) pools + + # Validate the following + # 1. Create VM using the service offering with encryptroot true and a data volume using + # the disk offering with encrypt true, and write data to the data volume in the guest + # 2. Migrate both volumes online (VM running) to the other RBD pool + # 3. Migrate both volumes offline (VM stopped) back to the first RBD pool + # 4. Migrate the data volume while it is detached to the other RBD pool + # 5. After every migration, verify the volumes are on the expected pool, still encrypted + # (natively by librbd), and that the guest reads back the data it wrote + """ + self.skip_if_rbd_encrypted_hotplug_unsupported() + + if self.storage_pool_type != "RBD": + self.skipTest("Skipping test as it requires RBD storage pools") + rbd_pools = [pool for pool in list_storage_pools(self.apiclient, zoneid=self.zone.id) or [] + if pool.type == "RBD" and pool.state == "Up"] + if len(rbd_pools) < 2: + self.skipTest("Skipping test as it requires two RBD storage pools") + + virtual_machine = VirtualMachine.create( + self.apiclient, + self.services, + accountid=self.account.name, + domainid=self.account.domainid, + serviceofferingid=self.service_offering_encrypt.id, + mode=self.services["mode"] + ) + self.cleanup.append(virtual_machine) + + volume = Volume.create( + self.apiclient, + self.services, + zoneid=self.zone.id, + account=self.account.name, + domainid=self.account.domainid, + diskofferingid=self.disk_offering_encrypt.id + ) + self.cleanup.append(volume) + virtual_machine.attach_volume(self.apiclient, volume) + + root_volume = Volume.list(self.apiclient, virtualmachineid=virtual_machine.id, type='ROOT', listall=True)[0] + source_pool = [pool for pool in rbd_pools if pool.id == root_volume.storageid] + if not source_pool: + self.skipTest("Skipping test as the ROOT volume was not allocated on an RBD pool") + source_pool = source_pool[0] + other_pool = [pool for pool in rbd_pools if pool.id != source_pool.id][0] + # The VM is restarted after attaching the data volume, as not every guest detects a hot plugged disk + virtual_machine.stop(self.apiclient) + if Volume.list(self.apiclient, id=volume.id)[0].storageid != source_pool.id: + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=source_pool.id, livemigrate=False) + virtual_machine.start(self.apiclient) + + def data_disk_device(ssh): + # The data volume is found in the guest by its size: the device name may change after a migration + # or a restart, and older guests have no /dev/disk/by-id links for virtio disks + listed = Volume.list(self.apiclient, id=volume.id)[0] + size = self.get_expected_guest_visible_size(listed, listed.size) + disks = [] + for _ in range(6): + disks = ssh.execute("/sbin/fdisk -l 2>/dev/null | grep '^Disk /dev/'") + for line in disks: + if " %s bytes" % size in line: + return line.split()[1].rstrip(":") + time.sleep(10) + self.fail("No disk of %s bytes (volume %s) found in the guest: %s" % (size, volume.id, disks)) + + def read_checksum(step): + ssh = virtual_machine.get_ssh_client(reconnect=True) + device = data_disk_device(ssh) + result = ssh.execute("dd if=%s bs=1M count=8 iflag=direct 2>/dev/null | md5sum" % device)[0].split()[0] + self.assertNotEqual(result, EMPTY_MD5, "%s: nothing could be read from %s" % (step, device)) + return result + + # Write random data to the raw data disk + ssh = virtual_machine.get_ssh_client(reconnect=True) + device = data_disk_device(ssh) + ssh.execute("dd if=/dev/urandom of=/tmp/encrypted-volume-data bs=1M count=8") + written = ssh.execute("dd if=/tmp/encrypted-volume-data of=%s bs=1M oflag=direct 2>&1 && sync" % device) + self.assertTrue(any("8388608 bytes" in line for line in written), "Failed to write to %s: %s" % (device, written)) + checksum = ssh.execute("md5sum < /tmp/encrypted-volume-data")[0].split()[0] + self.assertEqual(read_checksum("before migration"), checksum, "The data written to %s can not be read back" % device) + + def verify(pool, step): + for vol in (root_volume, volume): + migrated = Volume.list(self.apiclient, id=vol.id)[0] + self.assertEqual(migrated.storageid, pool.id, "%s: volume %s is not on pool %s" % (step, vol.id, pool.name)) + self.assertEqual(migrated.state, "Ready", "%s: volume %s is not Ready" % (step, vol.id)) + self.check_volume_encryption(virtual_machine, 2) + self.assertEqual(read_checksum(step), checksum, "%s: the data of the encrypted volume is not intact" % step) + + # Online: the VM keeps running while the volumes are copied with a libvirt block copy + for vol in (root_volume, volume): + Volume.migrate(self.apiclient, volumeid=vol.id, storageid=other_pool.id, livemigrate=True) + self.assertEqual(VirtualMachine.list(self.apiclient, id=virtual_machine.id)[0].state, "Running", + "VM should stay running during the online migration") + verify(other_pool, "online migration") + + # Offline: the volumes are copied through their encryption with qemu-img + virtual_machine.stop(self.apiclient) + for vol in (root_volume, volume): + Volume.migrate(self.apiclient, volumeid=vol.id, storageid=source_pool.id, livemigrate=False) + virtual_machine.start(self.apiclient) + verify(source_pool, "offline migration") + + # Offline, with the data volume detached (the VM is stopped, as not every disk bus supports hot unplugging) + virtual_machine.stop(self.apiclient) + virtual_machine.detach_volume(self.apiclient, volume) + Volume.migrate(self.apiclient, volumeid=volume.id, storageid=other_pool.id, livemigrate=False) + virtual_machine.attach_volume(self.apiclient, volume) + virtual_machine.start(self.apiclient) + migrated = Volume.list(self.apiclient, id=volume.id)[0] + self.assertEqual(migrated.storageid, other_pool.id, "Detached volume %s is not on pool %s" % (volume.id, other_pool.name)) + self.check_volume_encryption(virtual_machine, 2) + self.assertEqual(read_checksum("detached migration"), checksum, "detached migration: the data of the encrypted volume is not intact") + + virtual_machine.detach_volume(self.apiclient, volume) + def get_expected_guest_visible_size(self, volume, vol_sz): """Some pool types/encryption mechanisms reserve overhead out of the requested size, so the guest sees fewer usable bytes than the volume's nominal size. Returns the byte count the @@ -1687,12 +1838,25 @@ def get_expected_guest_visible_size(self, volume, vol_sz): vol_sz = int(vol_sz) if volume_pool.type.lower() == "powerflex": vol_sz = vol_sz - (128 << 20) - ((vol_sz >> 30) * 200704) - elif volume_pool.type.lower() == "rbd" and getattr(volume, "encryptformat", None): - # RBD volumes are encrypted natively by librbd: the LUKS2 header/keyslots (16 MiB) are - # reserved out of the volume's own size, so the guest sees size - header. - vol_sz = vol_sz - (16 << 20) + # An encrypted volume is created with room for its encryption header on every other pool type (RBD keeps the + # LUKS2 header in the image, in front of the data), so the guest sees the size of the volume return str(vol_sz) + def skip_if_rbd_encrypted_hotplug_unsupported(self): + """libvirt < 10.1.0 cannot hot-plug an encrypted RBD volume into a running VM + (the agent refuses it), so the tests that do so are skipped on such hosts""" + if self.storage_pool_type != "RBD": + return + hosts = Host.list(self.apiclient, zoneid=self.zone.id, type='Routing', hypervisor='KVM', state='Up') or [] + for host in hosts: + ssh_client = SshClient(host=host.ipaddress, port=22, user=self.hostConfig['username'], + passwd=self.hostConfig['password']) + out = ssh_client.execute("virsh version | awk '/Using library/{print $NF}'") + version = [int(v) for v in re.findall(r'\d+', (out[-1] if out else "0.0.0"))[:3]] + if version < [10, 1, 0]: + self.skipTest("Skipping test: libvirt %s on host %s cannot attach an encrypted RBD volume " + "to a running VM (libvirt 10.1.0 is required)" % (".".join(map(str, version)), host.name)) + def does_host_with_encryption_support_exists(self): hosts = Host.list( self.apiclient,