diff --git a/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotAnswer.java b/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotAnswer.java index 7041fdedc982..badbc643c415 100644 --- a/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotAnswer.java +++ b/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotAnswer.java @@ -27,6 +27,7 @@ public class CreateDiskOnlyVmSnapshotAnswer extends Answer { protected Map mapVolumeToSnapshotSize; private String nvramSnapshotPath; + private String memorySnapshotPath; public CreateDiskOnlyVmSnapshotAnswer(Command command, boolean success, String details, Map mapVolumeToSnapshotSize) { this(command, success, details, mapVolumeToSnapshotSize, null); @@ -34,9 +35,15 @@ public CreateDiskOnlyVmSnapshotAnswer(Command command, boolean success, String d public CreateDiskOnlyVmSnapshotAnswer(Command command, boolean success, String details, Map mapVolumeToSnapshotSize, String nvramSnapshotPath) { + this(command, success, details, mapVolumeToSnapshotSize, nvramSnapshotPath, null); + } + + public CreateDiskOnlyVmSnapshotAnswer(Command command, boolean success, String details, Map mapVolumeToSnapshotSize, + String nvramSnapshotPath, String memorySnapshotPath) { super(command, success, details); this.mapVolumeToSnapshotSize = mapVolumeToSnapshotSize; this.nvramSnapshotPath = nvramSnapshotPath; + this.memorySnapshotPath = memorySnapshotPath; } public Map getMapVolumeToSnapshotSize() { @@ -46,4 +53,8 @@ public Map getMapVolumeToSnapshotSize() { public String getNvramSnapshotPath() { return nvramSnapshotPath; } + + public String getMemorySnapshotPath() { + return memorySnapshotPath; + } } diff --git a/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotCommand.java b/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotCommand.java index a41aed89a9d4..4dad7daaee28 100644 --- a/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotCommand.java +++ b/core/src/main/java/com/cloud/agent/api/storage/CreateDiskOnlyVmSnapshotCommand.java @@ -33,6 +33,7 @@ public class CreateDiskOnlyVmSnapshotCommand extends VMSnapshotBaseCommand { protected VirtualMachine.State vmState; private final String vmUuid; private final boolean uefiEnabled; + private final boolean snapshotMemory; List> volumeTosAndNewPaths; @@ -42,12 +43,18 @@ public CreateDiskOnlyVmSnapshotCommand(String vmName, VMSnapshotTO snapshot, Lis public CreateDiskOnlyVmSnapshotCommand(String vmName, String vmUuid, VMSnapshotTO snapshot, List> volumeTosAndNewPaths, String guestOSType, VirtualMachine.State vmState, boolean uefiEnabled) { + this(vmName, vmUuid, snapshot, volumeTosAndNewPaths, guestOSType, vmState, uefiEnabled, false); + } + + public CreateDiskOnlyVmSnapshotCommand(String vmName, String vmUuid, VMSnapshotTO snapshot, List> volumeTosAndNewPaths, String guestOSType, + VirtualMachine.State vmState, boolean uefiEnabled, boolean snapshotMemory) { super(vmName, snapshot, volumeTosAndNewPaths == null ? null : volumeTosAndNewPaths.stream() .map(Pair::first).collect(Collectors.toList()), guestOSType); this.vmUuid = vmUuid; this.vmState = vmState; this.volumeTosAndNewPaths = volumeTosAndNewPaths; this.uefiEnabled = uefiEnabled; + this.snapshotMemory = snapshotMemory; } public VirtualMachine.State getVmState() { @@ -65,4 +72,8 @@ public String getVmUuid() { public boolean isUefiEnabled() { return uefiEnabled; } + + public boolean isSnapshotMemory() { + return snapshotMemory; + } } diff --git a/core/src/main/java/com/cloud/agent/api/storage/DeleteDiskOnlyVmSnapshotCommand.java b/core/src/main/java/com/cloud/agent/api/storage/DeleteDiskOnlyVmSnapshotCommand.java index 1ac0a0ff719b..b725c681ddd3 100644 --- a/core/src/main/java/com/cloud/agent/api/storage/DeleteDiskOnlyVmSnapshotCommand.java +++ b/core/src/main/java/com/cloud/agent/api/storage/DeleteDiskOnlyVmSnapshotCommand.java @@ -29,6 +29,7 @@ public class DeleteDiskOnlyVmSnapshotCommand extends Command { private final List snapshots; private final String nvramSnapshotPath; private final PrimaryDataStoreTO primaryDataStore; + private final String memorySnapshotPath; public DeleteDiskOnlyVmSnapshotCommand(List snapshots) { this(snapshots, null); @@ -39,9 +40,14 @@ public DeleteDiskOnlyVmSnapshotCommand(List snapshots, String nvramSnaps } public DeleteDiskOnlyVmSnapshotCommand(List snapshots, String nvramSnapshotPath, PrimaryDataStoreTO primaryDataStore) { + this(snapshots, nvramSnapshotPath, primaryDataStore, null); + } + + public DeleteDiskOnlyVmSnapshotCommand(List snapshots, String nvramSnapshotPath, PrimaryDataStoreTO primaryDataStore, String memorySnapshotPath) { this.snapshots = snapshots; this.nvramSnapshotPath = nvramSnapshotPath; this.primaryDataStore = primaryDataStore; + this.memorySnapshotPath = memorySnapshotPath; } public List getSnapshots() { @@ -52,6 +58,10 @@ public String getNvramSnapshotPath() { return nvramSnapshotPath; } + public String getMemorySnapshotPath() { + return memorySnapshotPath; + } + public PrimaryDataStoreTO getPrimaryDataStore() { return primaryDataStore; } diff --git a/core/src/main/java/com/cloud/agent/api/storage/RevertDiskOnlyVmSnapshotCommand.java b/core/src/main/java/com/cloud/agent/api/storage/RevertDiskOnlyVmSnapshotCommand.java index 3c9859aa44af..bcad4cdc24fc 100644 --- a/core/src/main/java/com/cloud/agent/api/storage/RevertDiskOnlyVmSnapshotCommand.java +++ b/core/src/main/java/com/cloud/agent/api/storage/RevertDiskOnlyVmSnapshotCommand.java @@ -30,18 +30,25 @@ public class RevertDiskOnlyVmSnapshotCommand extends Command { private final String vmUuid; private final boolean uefiEnabled; private final String nvramSnapshotPath; + private final String memorySnapshotPath; public RevertDiskOnlyVmSnapshotCommand(List snapshotObjectTos, String vmName) { this(snapshotObjectTos, vmName, null, false, null); } public RevertDiskOnlyVmSnapshotCommand(List snapshotObjectTos, String vmName, String vmUuid, boolean uefiEnabled, String nvramSnapshotPath) { + this(snapshotObjectTos, vmName, vmUuid, uefiEnabled, nvramSnapshotPath, null); + } + + public RevertDiskOnlyVmSnapshotCommand(List snapshotObjectTos, String vmName, String vmUuid, boolean uefiEnabled, String nvramSnapshotPath, + String memorySnapshotPath) { super(); this.snapshotObjectTos = snapshotObjectTos; this.vmName = vmName; this.vmUuid = vmUuid; this.uefiEnabled = uefiEnabled; this.nvramSnapshotPath = nvramSnapshotPath; + this.memorySnapshotPath = memorySnapshotPath; } public List getSnapshotObjectTos() { @@ -64,6 +71,10 @@ public String getNvramSnapshotPath() { return nvramSnapshotPath; } + public String getMemorySnapshotPath() { + return memorySnapshotPath; + } + @Override public boolean executeInSequence() { return false; diff --git a/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java b/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java index 6831552b83db..0f79030f0d79 100644 --- a/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java +++ b/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java @@ -33,6 +33,10 @@ public interface VMSnapshotManager extends VMSnapshotService, Manager { ConfigKey VMSnapshotMax = new ConfigKey("Advanced", Integer.class, "vmsnapshot.max", "10", "Maximum VM snapshots for a single VM", true, ConfigKey.Scope.Account); + ConfigKey VMSnapshotClvmNgMemoryEnabled = new ConfigKey("Advanced", Boolean.class, "kvm.clvmng.vmsnapshot.memory.enabled", "false", + "EXPERIMENTAL: allow Instance snapshots with memory for running KVM Instances whose volumes are all on CLVM_NG storage. Each such snapshot reserves an extra LV the size " + + "of the Instance memory, and writing it is slow on busy shared storage. All KVM hosts of the zone must run an agent that supports it.", true, ConfigKey.Scope.Zone); + /** * Delete all VM snapshots belonging to one VM * @param id, VM id diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java index 665c3a4659ca..aedc247d2ac7 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java @@ -472,7 +472,7 @@ public StrategyPriority canHandle(VMSnapshot vmSnapshot) { UserVmVO vm = userVmDao.findById(vmSnapshot.getVmId()); String cantHandleLog = String.format("Default VM snapshot cannot handle VM snapshot for [%s]", vm); - if (isRunningVMVolumeOnCLVMStorage(vm, cantHandleLog)) { + if (isRunningVMVolumeOnCLVMStorage(vm, cantHandleLog) || hasVolumeOnClvmNgStorage(vm, cantHandleLog)) { return StrategyPriority.CANT_HANDLE; } @@ -501,6 +501,18 @@ public boolean deleteVMSnapshotFromDB(VMSnapshot vmSnapshot, boolean unmanage) { return vmSnapshotDao.remove(vmSnapshot.getId()); } + /** Internal snapshots grow the qcow2 file, which cannot happen on a fixed size CLVM_NG LV; those VMs are handled by the KVM file based strategy. */ + protected boolean hasVolumeOnClvmNgStorage(UserVmVO vm, String cantHandleLog) { + for (VolumeVO volume : volumeDao.findByInstance(vm.getId())) { + StoragePool pool = primaryDataStoreDao.findById(volume.getPoolId()); + if (pool != null && pool.getPoolType() == Storage.StoragePoolType.CLVM_NG) { + logger.debug("{} - the VM has a volume on CLVM_NG storage (pool: {}), which only supports external VM snapshots.", cantHandleLog, pool.getName()); + return true; + } + } + return false; + } + protected boolean isRunningVMVolumeOnCLVMStorage(UserVmVO vm, String cantHandleLog) { Long vmId = vm.getId(); if (State.Running.equals(vm.getState())) { @@ -522,7 +534,7 @@ public StrategyPriority canHandle(Long vmId, Long rootPoolId, boolean snapshotMe UserVmVO vm = userVmDao.findById(vmId); String cantHandleLog = String.format("Default VM snapshot cannot handle VM snapshot for [%s]", vm); - if (isRunningVMVolumeOnCLVMStorage(vm, cantHandleLog)) { + if (isRunningVMVolumeOnCLVMStorage(vm, cantHandleLog) || hasVolumeOnClvmNgStorage(vm, cantHandleLog)) { return StrategyPriority.CANT_HANDLE; } diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategy.java index 4cb1d0361aa9..6c8c7a2993a0 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategy.java @@ -90,13 +90,15 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.VMInstanceDetailsDao; import com.cloud.vm.snapshot.VMSnapshot; +import com.cloud.vm.snapshot.VMSnapshotManager; import com.cloud.vm.snapshot.VMSnapshotDetailsVO; import com.cloud.vm.snapshot.VMSnapshotVO; public class KvmFileBasedStorageVmSnapshotStrategy extends StorageVMSnapshotStrategy { - private static final List supportedStoragePoolTypes = List.of(Storage.StoragePoolType.Filesystem, Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint); + private static final List supportedStoragePoolTypes = List.of(Storage.StoragePoolType.Filesystem, Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint, Storage.StoragePoolType.CLVM_NG); private static final String KVM_FILE_BASED_STORAGE_SNAPSHOT_NVRAM = "kvmFileBasedStorageSnapshotNvram"; + private static final String KVM_FILE_BASED_STORAGE_SNAPSHOT_MEMORY = "kvmFileBasedStorageSnapshotMemory"; @Inject protected SnapshotDataStoreDao snapshotDataStoreDao; @@ -216,8 +218,9 @@ public boolean deleteVMSnapshot(VMSnapshot vmSnapshot) { @Override public boolean revertVMSnapshot(VMSnapshot vmSnapshot) { UserVmVO userVm = userVmDao.findById(vmSnapshot.getVmId()); - if (!VirtualMachine.State.Stopped.equals(userVm.getState())) { - throw new CloudRuntimeException("VM must be stopped to revert disk-only VM snapshot."); + boolean memorySnapshot = VMSnapshot.Type.DiskAndMemory.equals(vmSnapshot.getType()); + if (!(memorySnapshot ? VirtualMachine.State.Running : VirtualMachine.State.Stopped).equals(userVm.getState())) { + throw new CloudRuntimeException(memorySnapshot ? "VM must be running to revert a VM snapshot with memory." : "VM must be stopped to revert disk-only VM snapshot."); } VMSnapshotVO vmSnapshotBeingReverted = (VMSnapshotVO) vmSnapshot; @@ -235,7 +238,7 @@ public boolean revertVMSnapshot(VMSnapshot vmSnapshot) { RevertDiskOnlyVmSnapshotCommand revertDiskOnlyVMSnapshotCommand = new RevertDiskOnlyVmSnapshotCommand(volumeSnapshotTos, userVm.getName(), userVm.getUuid(), isUefiVm(userVm), - getNvramSnapshotPath(vmSnapshotBeingReverted)); + getNvramSnapshotPath(vmSnapshotBeingReverted), getMemorySnapshotPath(vmSnapshotBeingReverted)); Answer answer = agentMgr.easySend(hostId, revertDiskOnlyVMSnapshotCommand); if (answer == null || !answer.getResult()) { @@ -369,8 +372,9 @@ public StrategyPriority canHandle(Long vmId, Long rootPoolId, boolean snapshotMe VirtualMachine vm = userVmDao.findById(vmId); String cantHandleLog = String.format("KVM file based storage VM snapshot strategy cannot handle VM snapshot for [%s]", vm); - if (snapshotMemory) { - logger.debug("{} as a snapshot with memory was requested.", cantHandleLog); + if (snapshotMemory && !isExternalMemorySnapshotSupported(vm)) { + logger.debug("{} as a snapshot with memory was requested and it is only supported for running VMs with all volumes on CLVM_NG storage, when enabled for the zone.", + cantHandleLog); return StrategyPriority.CANT_HANDLE; } @@ -379,8 +383,8 @@ public StrategyPriority canHandle(Long vmId, Long rootPoolId, boolean snapshotMe return StrategyPriority.CANT_HANDLE; } - if (CollectionUtils.isNotEmpty(vmSnapshotDao.findByVmAndByType(vmId, VMSnapshot.Type.DiskAndMemory))) { - logger.debug("{} as there is already a VM snapshot with disk and memory.", cantHandleLog); + if (hasInternalMemorySnapshot(vmId)) { + logger.debug("{} as there is already a VM snapshot with disk and memory which is not file based.", cantHandleLog); return StrategyPriority.CANT_HANDLE; } @@ -413,6 +417,26 @@ public StrategyPriority canHandle(Long vmId, Long rootPoolId, boolean snapshotMe return StrategyPriority.HIGHEST; } + /** Memory snapshots are external only for running VMs whose volumes are all on CLVM_NG, and when enabled for the zone. */ + protected boolean isExternalMemorySnapshotSupported(VirtualMachine vm) { + if (!VirtualMachine.State.Running.equals(vm.getState()) || !VMSnapshotManager.VMSnapshotClvmNgMemoryEnabled.valueIn(vm.getDataCenterId())) { + return false; + } + List volumes = volumeDao.findByInstance(vm.getId()); + return CollectionUtils.isNotEmpty(volumes) + && volumes.stream().allMatch(volume -> Storage.StoragePoolType.CLVM_NG.equals(storagePool.findById(volume.getPoolId()).getPoolType())); + } + + /** + * Snapshots with memory taken by another strategy keep the memory inside the qcow2 files, and cannot be mixed with this one. + * Only snapshots that already exist count, as the snapshot being created has no details yet. + */ + protected boolean hasInternalMemorySnapshot(long vmId) { + return vmSnapshotDao.findByVmAndByType(vmId, VMSnapshot.Type.DiskAndMemory).stream() + .filter(vmSnapshot -> VMSnapshot.State.Ready.equals(vmSnapshot.getState()) || VMSnapshot.State.Hidden.equals(vmSnapshot.getState())) + .anyMatch(vmSnapshot -> CollectionUtils.isEmpty(vmSnapshotDetailsDao.findDetails(vmSnapshot.getId(), KVM_FILE_BASED_STORAGE_SNAPSHOT))); + } + private List deleteSnapshot(VMSnapshotVO vmSnapshotVO, Long hostId) { validateHostSupportsNvramSidecarCleanup(vmSnapshotVO, hostId, "delete"); List volumeSnapshots = vmSnapshotHelper.getVolumeSnapshotsAssociatedWithKvmDiskOnlyVmSnapshot((vmSnapshotVO.getId())); @@ -420,7 +444,7 @@ private List deleteSnapshot(VMSnapshotVO vmSnapshotVO, Long hostId) .map(snapshotDataStoreVO -> snapshotDataFactory.getSnapshot(snapshotDataStoreVO.getSnapshotId(), snapshotDataStoreVO.getDataStoreId(), DataStoreRole.Primary).getTO()) .collect(Collectors.toList()); - DeleteDiskOnlyVmSnapshotCommand deleteSnapshotCommand = new DeleteDiskOnlyVmSnapshotCommand(volumeSnapshotTOList, getNvramSnapshotPath(vmSnapshotVO)); + DeleteDiskOnlyVmSnapshotCommand deleteSnapshotCommand = new DeleteDiskOnlyVmSnapshotCommand(volumeSnapshotTOList, getNvramSnapshotPath(vmSnapshotVO), null, getMemorySnapshotPath(vmSnapshotVO)); Answer answer = agentMgr.easySend(hostId, deleteSnapshotCommand); if (answer == null || !answer.getResult()) { logger.error("Failed to delete VM snapshot [{}] due to {}.", vmSnapshotVO.getUuid(), answer != null ? answer.getDetails() : "Communication failure"); @@ -438,14 +462,15 @@ private List deleteSnapshot(VMSnapshotVO vmSnapshotVO, Long hostId) protected void deleteNvramSnapshotIfNeeded(VMSnapshotVO vmSnapshotVO, Long hostId, PrimaryDataStoreTO primaryDataStore) { String nvramSnapshotPath = getNvramSnapshotPath(vmSnapshotVO); - if (StringUtils.isBlank(nvramSnapshotPath) || primaryDataStore == null) { + String memorySnapshotPath = getMemorySnapshotPath(vmSnapshotVO); + if ((StringUtils.isBlank(nvramSnapshotPath) && StringUtils.isBlank(memorySnapshotPath)) || primaryDataStore == null) { return; } - DeleteDiskOnlyVmSnapshotCommand deleteSnapshotCommand = new DeleteDiskOnlyVmSnapshotCommand(List.of(), nvramSnapshotPath, primaryDataStore); + DeleteDiskOnlyVmSnapshotCommand deleteSnapshotCommand = new DeleteDiskOnlyVmSnapshotCommand(List.of(), nvramSnapshotPath, primaryDataStore, memorySnapshotPath); Answer answer = agentMgr.easySend(hostId, deleteSnapshotCommand); if (answer == null || !answer.getResult()) { - logger.warn("Failed to delete the NVRAM sidecar of VM snapshot [{}] due to {}.", vmSnapshotVO.getUuid(), + logger.warn("Failed to delete the NVRAM and memory sidecars of VM snapshot [{}] due to {}.", vmSnapshotVO.getUuid(), answer != null ? answer.getDetails() : "communication failure"); } } @@ -599,7 +624,8 @@ protected VMSnapshot takeVmSnapshotInternal(VMSnapshot vmSnapshot, Map requiredCapabilities = new ArrayList<>(); + if (StringUtils.isNotBlank(getNvramSnapshotPath(vmSnapshotVO))) { + requiredCapabilities.add(Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM); + } + if (requiredCapabilities.isEmpty()) { return selectedHostId; } - return pickHostWithRequiredCapabilities(userVm, selectedHostId, operation, true, List.of(Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM)); + return pickHostWithRequiredCapabilities(userVm, selectedHostId, operation, true, requiredCapabilities); } protected Long pickHostWithRequiredCapabilities(UserVm userVm, Long selectedHostId, String operation, boolean canFallbackFromSelectedHost, diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategyTest.java index 365ba3d4eb31..b6ace8d5067a 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategyTest.java @@ -135,6 +135,28 @@ public void testCanHandleRunningVMOnClvmStorageCantHandle() { StrategyPriority.CANT_HANDLE, result); } + @Test + public void testCanHandleVMOnClvmNgStorageCantHandleInAnyState() { + for (State state : List.of(State.Running, State.Stopped)) { + Long vmId = 1L; + VMSnapshot vmSnapshot = Mockito.mock(VMSnapshot.class); + Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId); + + UserVmVO vm = Mockito.mock(UserVmVO.class); + Mockito.when(vm.getId()).thenReturn(vmId); + Mockito.when(vm.getState()).thenReturn(state); + Mockito.when(userVmDao.findById(vmId)).thenReturn(vm); + VolumeVO volume = createVolume(vmId, 1L); + StoragePoolVO clvmNgPool = createStoragePool("clvm-ng-pool", Storage.StoragePoolType.CLVM_NG); + Mockito.when(volumeDao.findByInstance(vmId)).thenReturn(List.of(volume)); + Mockito.when(primaryDataStoreDao.findById(1L)).thenReturn(clvmNgPool); + + Assert.assertEquals("Internal snapshots must not be taken on CLVM_NG for a " + state + " VM", + StrategyPriority.CANT_HANDLE, defaultVMSnapshotStrategy.canHandle(vmSnapshot)); + Assert.assertEquals(StrategyPriority.CANT_HANDLE, defaultVMSnapshotStrategy.canHandle(vmId, null, true)); + } + } + @Test public void testCanHandleStoppedVMOnClvmStorageCanHandle() { Long vmId = 1L; diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategyTest.java index 7107f38dffc9..dca4444e037b 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/vmsnapshot/KvmFileBasedStorageVmSnapshotStrategyTest.java @@ -19,6 +19,9 @@ package org.apache.cloudstack.storage.vmsnapshot; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; @@ -147,6 +150,94 @@ public void testProcessCreateVmSnapshotAnswerPersistsNvramPath() throws Exceptio verify(vmSnapshotDetailsDao).addDetail(42L, "kvmFileBasedStorageSnapshotNvram", "nvram/42.fd", false); } + @Test + public void testProcessCreateVmSnapshotAnswerPersistsMemoryPath() throws Exception { + VMSnapshot vmSnapshot = mock(VMSnapshot.class); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + UserVm userVm = mock(UserVm.class); + VMSnapshotVO vmSnapshotVO = mock(VMSnapshotVO.class); + + when(vmSnapshot.getId()).thenReturn(42L); + when(vmSnapshot.getUuid()).thenReturn("vm-snapshot"); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Collections.emptyMap()); + when(answer.getMemorySnapshotPath()).thenReturn("memory/42.img"); + + Method method = KvmFileBasedStorageVmSnapshotStrategy.class.getDeclaredMethod("processCreateVmSnapshotAnswer", VMSnapshot.class, java.util.Map.class, + CreateDiskOnlyVmSnapshotAnswer.class, UserVm.class, VMSnapshotVO.class, long.class, VMSnapshotVO.class); + method.setAccessible(true); + method.invoke(strategy, vmSnapshot, Collections.emptyMap(), answer, userVm, vmSnapshotVO, 0L, null); + + verify(vmSnapshotDetailsDao).addDetail(42L, "kvmFileBasedStorageSnapshotMemory", "memory/42.img", false); + } + + @Test + public void testRevertVMSnapshotWithMemoryFailsForStoppedVm() { + UserVmVO userVm = mock(UserVmVO.class); + VMSnapshotVO vmSnapshot = mock(VMSnapshotVO.class); + + when(vmSnapshot.getVmId()).thenReturn(10L); + when(vmSnapshot.getType()).thenReturn(VMSnapshot.Type.DiskAndMemory); + when(userVm.getState()).thenReturn(VirtualMachine.State.Stopped); + when(strategy.userVmDao.findById(10L)).thenReturn(userVm); + + try { + strategy.revertVMSnapshot(vmSnapshot); + fail("Expected the revert to be refused."); + } catch (CloudRuntimeException e) { + assertEquals("VM must be running to revert a VM snapshot with memory.", e.getMessage()); + } + } + + @Test + public void testDeleteSidecarsIfNeededPassesMemoryPathToAgentCommand() { + long hostId = 40L; + + VMSnapshotVO vmSnapshot = mock(VMSnapshotVO.class); + VMSnapshotDetailsVO memoryDetail = new VMSnapshotDetailsVO(20L, "kvmFileBasedStorageSnapshotMemory", "memory/20.img", false); + PrimaryDataStoreTO primaryDataStore = mock(PrimaryDataStoreTO.class); + + when(vmSnapshot.getId()).thenReturn(20L); + when(vmSnapshot.getUuid()).thenReturn("vm-snapshot"); + when(vmSnapshotDetailsDao.findDetail(20L, "kvmFileBasedStorageSnapshotMemory")).thenReturn(memoryDetail); + when(agentMgr.easySend(eq(hostId), any())).thenReturn(new Answer(null, true, null)); + + strategy.deleteNvramSnapshotIfNeeded(vmSnapshot, hostId, primaryDataStore); + + verify(agentMgr).easySend(eq(hostId), argThat(command -> command instanceof DeleteDiskOnlyVmSnapshotCommand + && "memory/20.img".equals(((DeleteDiskOnlyVmSnapshotCommand) command).getMemorySnapshotPath()) + && ((DeleteDiskOnlyVmSnapshotCommand) command).getNvramSnapshotPath() == null)); + } + + @Test + public void testHasInternalMemorySnapshotIgnoresFileBasedMemorySnapshots() { + VMSnapshotVO fileBased = mock(VMSnapshotVO.class); + VMSnapshotVO internal = mock(VMSnapshotVO.class); + VMSnapshotVO beingCreated = mock(VMSnapshotVO.class); + when(fileBased.getId()).thenReturn(1L); + when(internal.getId()).thenReturn(2L); + when(beingCreated.getId()).thenReturn(3L); + when(fileBased.getState()).thenReturn(VMSnapshot.State.Ready); + when(internal.getState()).thenReturn(VMSnapshot.State.Ready); + when(beingCreated.getState()).thenReturn(VMSnapshot.State.Allocated); + when(vmSnapshotDetailsDao.findDetails(3L, "kvmFileBasedStorageSnapshot")).thenReturn(Collections.emptyList()); + when(vmSnapshotDetailsDao.findDetails(1L, "kvmFileBasedStorageSnapshot")).thenReturn(List.of(new VMSnapshotDetailsVO(1L, "kvmFileBasedStorageSnapshot", "1", true))); + when(vmSnapshotDetailsDao.findDetails(2L, "kvmFileBasedStorageSnapshot")).thenReturn(Collections.emptyList()); + + when(vmSnapshotDao.findByVmAndByType(10L, VMSnapshot.Type.DiskAndMemory)).thenReturn(List.of(fileBased, beingCreated)); + assertFalse(strategy.hasInternalMemorySnapshot(10L)); + + when(vmSnapshotDao.findByVmAndByType(10L, VMSnapshot.Type.DiskAndMemory)).thenReturn(List.of(fileBased, internal)); + assertTrue(strategy.hasInternalMemorySnapshot(10L)); + } + + @Test + public void testIsExternalMemorySnapshotSupportedRequiresARunningVmAndTheZoneSetting() { + VirtualMachine stopped = mock(VirtualMachine.class); + when(stopped.getState()).thenReturn(VirtualMachine.State.Stopped); + + assertFalse(strategy.isExternalMemorySnapshotSupported(stopped)); + } + @Test public void testRevertVMSnapshotPassesNvramPathToAgentCommand() { long vmId = 10L; 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..5ef4c758fa78 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 @@ -236,6 +236,7 @@ import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceServiceExecutor; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper; +import com.cloud.hypervisor.kvm.storage.clvm.ClvmBackingChain; import com.cloud.hypervisor.kvm.storage.IscsiStorageCleanupMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; @@ -444,10 +445,22 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv " \n" + ""; + private static final String SNAPSHOT_XML_EXTERNAL_MEMORY = "\n" + + "%s\n" + + "\n" + + " \n" + + "%s" + + " \n" + + ""; + private static final String TAG_DISK_SNAPSHOT = "\n" + "\n" + "\n"; + private static final String TAG_DISK_SNAPSHOT_BLOCK = "\n" + + "\n" + + "\n"; + protected int qcow2DeltaMergeTimeout; private String modifyVlanPath; @@ -7029,7 +7042,8 @@ protected Boolean isLibvirtEventsEnabled() { * */ protected void mergeSnapshotIntoBaseFileWithEventsAndConfigurableTimeout(Domain vm, String diskLabel, String baseFilePath, String topFilePath, boolean active, String snapshotName, VolumeObjectTO volume, Connect conn) throws LibvirtException { - boolean isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit = LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(conn); + boolean isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit = LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(conn) + && !isBlockDeltaPool(volume); String vmName = vm.getName(); int commitFlags = 0; @@ -7066,7 +7080,7 @@ protected void mergeSnapshotIntoBaseFileWithEventsAndConfigurableTimeout(Domain logger.info("Completed block commit of snapshot [{}] of VM [{}].", snapshotName, vmName); - manuallyDeleteUnusedSnapshotFile(isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit, topFilePath != null ? topFilePath : getSnapshotTemporaryPath(baseFilePath, snapshotName)); + deleteMergedDelta(volume, isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit, topFilePath != null ? topFilePath : getSnapshotTemporaryPath(baseFilePath, snapshotName)); } /** @@ -7078,14 +7092,15 @@ protected void mergeSnapshotIntoBaseFileWithEventsAndConfigurableTimeout(Domain * @throws LibvirtException */ protected void mergeSnapshotIntoBaseFileWithoutEvents(Domain vm, String diskLabel, String baseFilePath, String topFilePath, boolean active, String snapshotName, VolumeObjectTO volume, Connect conn) throws LibvirtException { - boolean isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit = LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(conn); + boolean isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit = LibvirtUtilitiesHelper.isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit(conn) + && !isBlockDeltaPool(volume); String vmName = vm.getName(); String mergeCommand = buildMergeCommand(vmName, diskLabel, baseFilePath, topFilePath, active, isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit); String mergeResult = Script.runSimpleBashScript(mergeCommand); if (mergeResult == null) { logger.debug("Successfully merged snapshot [{}] into VM [{}] {} base file.", snapshotName, vmName, volume); - manuallyDeleteUnusedSnapshotFile(isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit, getSnapshotTemporaryPath(baseFilePath, snapshotName)); + deleteMergedDelta(volume, isLibvirtSupportingFlagDeleteOnCommandVirshBlockcommit, getSnapshotTemporaryPath(baseFilePath, snapshotName)); return; } @@ -7159,6 +7174,44 @@ protected void checkBlockCommitProgress(Domain vm, String diskLabel, String vmNa logger.warn("Block commit {} has timed out after waiting at least {} seconds. The progress of the operation was [{}] of [{}].", partialLog, qcow2DeltaMergeTimeout, lastCommittedBytes, endBytes); } + protected void ensureDeltaParentIsExclusive(KVMStoragePool pool, String parentPath) { + if (pool == null || !getStoragePoolMgr().usesBlockVmSnapshotDeltas(pool)) { + return; + } + try { + activateExclusively(parentPath); + } catch (CloudRuntimeException e) { + throw new CloudRuntimeException(String.format("Cannot merge into snapshot layer [%s] because it could not be activated exclusively on this host, probably as it is still " + + "active on another host. Deactivate it there (lvchange -an %s) and retry. Cause: %s", parentPath, parentPath, e.getMessage()), e); + } + } + + protected void activateExclusively(String lvPath) { + activateClvmVolumeExclusive(lvPath); + } + + protected boolean isBlockDeltaPool(VolumeObjectTO volume) { + if (volume == null || !(volume.getDataStore() instanceof PrimaryDataStoreTO)) { + return false; + } + PrimaryDataStoreTO dataStore = (PrimaryDataStoreTO) volume.getDataStore(); + KVMStoragePool pool = getStoragePoolMgr().getStoragePool(dataStore.getPoolType(), dataStore.getUuid()); + return pool != null && getStoragePoolMgr().usesBlockVmSnapshotDeltas(pool); + } + + protected void deleteMergedDelta(VolumeObjectTO volume, boolean libvirtDeletesFile, String deltaPath) { + if (!isBlockDeltaPool(volume)) { + manuallyDeleteUnusedSnapshotFile(libvirtDeletesFile, deltaPath); + return; + } + PrimaryDataStoreTO dataStore = (PrimaryDataStoreTO) volume.getDataStore(); + try { + getStoragePoolMgr().deleteVmSnapshotDelta(getStoragePoolMgr().getStoragePool(dataStore.getPoolType(), dataStore.getUuid()), Paths.get(deltaPath).getFileName().toString()); + } catch (IOException ex) { + throw new CloudRuntimeException(String.format("Unable to delete merged delta [%s] due to [%s].", deltaPath, ex.getMessage())); + } + } + /** * Manually deletes the unused snapshot file.
* This method is necessary due to Libvirt created the tag '--delete' on command 'virsh blockcommit' on version 1.2.9, however it was only implemented on version @@ -7352,16 +7405,24 @@ public static void modifyClvmVolumesStateForMigration(List disks, Virtu for (DiskDef disk : disks) { if (isClvmVolume(disk, vmSpec)) { String volumePath = disk.getDiskPath(); - try { - modifyClvmVolumeState(volumePath, state.getLvchangeFlag(), state.getDescription(), state.getLogMessage()); - } catch (Exception e) { - LOGGER.error("[CLVM Migration] Exception while setting volume [{}] to {} state: {}", - volumePath, state.getDescription(), e.getMessage(), e); + List layerPaths = ClvmBackingChain.getSnapshotLayerLvPaths(volumePath); + modifyClvmVolumeStateQuietly(volumePath, state); + for (String layerPath : layerPaths) { + modifyClvmVolumeStateQuietly(layerPath, state); } } } } + private static void modifyClvmVolumeStateQuietly(String volumePath, ClvmVolumeState state) { + try { + modifyClvmVolumeState(volumePath, state.getLvchangeFlag(), state.getDescription(), state.getLogMessage()); + } catch (Exception e) { + LOGGER.error("[CLVM Migration] Exception while setting volume [{}] to {} state: {}", + volumePath, state.getDescription(), e.getMessage(), e); + } + } + private static void modifyClvmVolumeState(String volumePath, String lvchangeFlag, String stateDescription, String logMessage) { try { @@ -7658,6 +7719,7 @@ public void mergeDeltaForStoppedVm(DeltaMergeTreeTO deltaMergeTreeTO) throws Qem QemuImgFile parent = new QemuImgFile(storagePool.getLocalPathFor(parentTo.getPath()), QemuImg.PhysicalDiskFormat.QCOW2); QemuImgFile child = new QemuImgFile(childLocalPath, QemuImg.PhysicalDiskFormat.QCOW2); + ensureDeltaParentIsExclusive(storagePool, storagePool.getLocalPathFor(parentTo.getPath())); logger.debug("Committing child delta [{}] into parent delta [{}].", parentTo, deltaMergeTreeTO.getChild()); qemuImg.commit(child, parent, true); @@ -7672,7 +7734,7 @@ public void mergeDeltaForStoppedVm(DeltaMergeTreeTO deltaMergeTreeTO) throws Qem logger.debug("Deleting child at [{}] as it is useless.", childLocalPath); - Files.deleteIfExists(Path.of(childLocalPath)); + storagePoolManager.deleteVmSnapshotDelta(storagePool, deltaMergeTreeTO.getChild().getPath()); } public void mergeDeltaForRunningVm(DeltaMergeTreeTO mergeTreeTO, String vmName, VolumeObjectTO volumeObjectTO) throws LibvirtException, QemuImgException { @@ -7694,6 +7756,7 @@ public void mergeDeltaForRunningVm(DeltaMergeTreeTO mergeTreeTO, String vmName, logger.debug("Found label [{}] for [{}]. Will merge delta at [{}] into delta at [{}].", label, volumeObjectTO, parentSnapshotLocalPath, childDeltaPath); + ensureDeltaParentIsExclusive(storagePool, parentSnapshotLocalPath); mergeDeltaIntoBaseFile(domain, label, parentSnapshotLocalPath, childDeltaPath, active, childTO.getPath(), volumeObjectTO, conn); QemuImgFile parent = new QemuImgFile(parentSnapshotLocalPath, QemuImg.PhysicalDiskFormat.QCOW2); @@ -7724,25 +7787,32 @@ public int getFlagsToUseForRunningVmSnapshotCreation(boolean quiesceVm) { } public Pair> createSnapshotXmlAndNewVolumePathMap(List> volumeTosAndNewPaths, List disks, String snapshotName) { + return createSnapshotXmlAndNewVolumePathMap(volumeTosAndNewPaths, disks, snapshotName, null); + } + + public Pair> createSnapshotXmlAndNewVolumePathMap(List> volumeTosAndNewPaths, List disks, String snapshotName, + String memoryFilePath) { StringBuilder stringBuilder = new StringBuilder(); Map volumeObjectToNewPathMap = new HashMap<>(); for (Pair volumeObjectTOAndPath : volumeTosAndNewPaths) { LibvirtVMDef.DiskDef diskdef = getDiskWithPathOfVolumeObjectTO(disks, volumeObjectTOAndPath.first()); String newPath = volumeObjectTOAndPath.second(); - stringBuilder.append(String.format(TAG_DISK_SNAPSHOT, diskdef.getDiskLabel(), getSnapshotTemporaryPath(diskdef.getDiskPath(), newPath))); + String tag = LibvirtVMDef.DiskDef.DiskType.BLOCK.equals(diskdef.getDiskType()) ? TAG_DISK_SNAPSHOT_BLOCK : TAG_DISK_SNAPSHOT; + stringBuilder.append(String.format(tag, diskdef.getDiskLabel(), getSnapshotTemporaryPath(diskdef.getDiskPath(), newPath))); long snapSize = getFileSize(diskdef.getDiskPath()); volumeObjectToNewPathMap.put(volumeObjectTOAndPath.first().getUuid(), snapSize); } - String snapshotXml = String.format(SNAPSHOT_XML, snapshotName, stringBuilder); + String snapshotXml = memoryFilePath == null ? String.format(SNAPSHOT_XML, snapshotName, stringBuilder) + : String.format(SNAPSHOT_XML_EXTERNAL_MEMORY, snapshotName, memoryFilePath, stringBuilder); return new Pair<>(snapshotXml, volumeObjectToNewPathMap); } public long getFileSize(String path) { - return new File(path).length(); + return ClvmBackingChain.getFileSize(path); } public boolean pullVolumeBackingFile(VolumeObjectTO volumeObjectTO, String vmName) throws LibvirtException { diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapper.java index 18c4324addf5..a1465c3b7b1e 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapper.java @@ -17,11 +17,15 @@ package com.cloud.hypervisor.kvm.resource.wrapper; +import java.util.Collections; +import java.util.List; + import com.cloud.agent.api.Answer; import org.apache.cloudstack.storage.clvm.command.ClvmLockTransferCommand; import org.apache.cloudstack.storage.clvm.command.ClvmLockTransferAnswer; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.resource.CommandWrapper; +import com.cloud.hypervisor.kvm.storage.clvm.ClvmBackingChain; import com.cloud.resource.ResourceWrapper; import com.cloud.utils.script.Script; import com.cloud.utils.script.OutputInterpreter; @@ -64,6 +68,9 @@ public Answer execute(ClvmLockTransferCommand cmd, LibvirtComputingResource serv return new ClvmLockTransferAnswer(cmd, false, "Unknown operation: " + operation); } + List snapshotLayerPaths = operation == ClvmLockTransferCommand.Operation.DEACTIVATE + ? ClvmBackingChain.getSnapshotLayerLvPaths(lvPath) : Collections.emptyList(); + Script script = new Script("/usr/sbin/lvchange", 60000, logger); script.add(lvchangeOpt); script.add(lvPath); @@ -79,6 +86,7 @@ public Answer execute(ClvmLockTransferCommand cmd, LibvirtComputingResource serv logger.info("Successfully executed CLVM lock transfer: {} {} for volume {}", lvchangeOpt, lvPath, volumeUuid); + releaseSnapshotLayers(snapshotLayerPaths, volumeUuid); return new ClvmLockTransferAnswer(cmd, true, String.format("Successfully %s CLVM volume %s", operationDesc, volumeUuid)); @@ -90,6 +98,17 @@ public Answer execute(ClvmLockTransferCommand cmd, LibvirtComputingResource serv } } + private void releaseSnapshotLayers(List snapshotLayerPaths, String volumeUuid) { + for (String layerPath : snapshotLayerPaths) { + Script deactivateLayer = new Script("/usr/sbin/lvchange", 60000, logger); + deactivateLayer.add("-an", layerPath); + String layerResult = deactivateLayer.execute(); + if (layerResult != null) { + logger.warn("Could not deactivate snapshot layer {} of volume {}: {}", layerPath, volumeUuid, layerResult); + } + } + } + /** * Query whether this host currently has the CLVM LV activated locally. * Executes: lvs -o lv_attr,lv_host,lv_active --noheadings diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateDiskOnlyVMSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateDiskOnlyVMSnapshotCommandWrapper.java index e6edf8e6e398..04533f20237f 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateDiskOnlyVMSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateDiskOnlyVMSnapshotCommandWrapper.java @@ -25,6 +25,7 @@ import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotCommand; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef; +import com.cloud.hypervisor.kvm.storage.clvm.ClvmBackingChain; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.resource.CommandWrapper; @@ -34,9 +35,7 @@ import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.qemu.QemuCommand; -import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImgException; -import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.commons.lang3.StringUtils; import org.libvirt.Connect; import org.libvirt.Domain; @@ -45,11 +44,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardCopyOption; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -59,6 +56,8 @@ @ResourceWrapper(handles = CreateDiskOnlyVmSnapshotCommand.class) public class LibvirtCreateDiskOnlyVMSnapshotCommandWrapper extends CommandWrapper { protected static final String NVRAM_SNAPSHOT_DIR = ".cloudstack-vm-snapshot-nvram"; + protected static final String MEMORY_SNAPSHOT_DIR = ".cloudstack-vm-snapshot-memory"; + private static final long MEMORY_SNAPSHOT_OVERHEAD_BYTES = 128L * 1024 * 1024; private static final String SNAPSHOT_XML = "\n" + "%s\n" + @@ -89,10 +88,12 @@ protected Answer takeDiskOnlyVmSnapshotOfRunningVm(CreateDiskOnlyVmSnapshotComma Domain dm = null; String nvramSnapshotPath = null; + String memorySnapshotPath = null; boolean suspendedByThisWrapper = false; boolean filesystemsFrozenByThisWrapper = false; CreateDiskOnlyVmSnapshotAnswer answer = null; String postSnapshotCleanupIssue = null; + Map blockDeltaVolumesAndPools = new HashMap<>(); try { LibvirtUtilitiesHelper libvirtUtilitiesHelper = resource.getLibvirtUtilitiesHelper(); Connect conn = libvirtUtilitiesHelper.getConnection(); @@ -108,8 +109,14 @@ protected Answer takeDiskOnlyVmSnapshotOfRunningVm(CreateDiskOnlyVmSnapshotComma } VMSnapshotTO target = cmd.getTarget(); + blockDeltaVolumesAndPools = createBlockDeltas(cmd, resource, disks); + String memoryDevicePath = null; + if (cmd.isSnapshotMemory()) { + memorySnapshotPath = getMemorySnapshotRelativePath(target.getId()); + memoryDevicePath = resource.getStoragePoolMgr().createVmSnapshotMemoryFile(getRootVolumePool(cmd, resource), memorySnapshotPath, getMemorySnapshotSize(dm)); + } Pair> snapshotXmlAndVolumeToNewPathMap = resource.createSnapshotXmlAndNewVolumePathMap(cmd.getVolumeTosAndNewPaths(), disks, - target.getSnapshotName()); + target.getSnapshotName(), memoryDevicePath); if (shouldFreezeVmFilesystemsForSnapshot(cmd)) { // The guest-agent freeze flushes guest filesystems; suspend below prevents concurrent UEFI NVRAM writes. freezeVmFilesystems(dm, vmName); @@ -121,17 +128,23 @@ protected Answer takeDiskOnlyVmSnapshotOfRunningVm(CreateDiskOnlyVmSnapshotComma } nvramSnapshotPath = backupNvramIfNeeded(cmd, resource); - dm.snapshotCreateXML(snapshotXmlAndVolumeToNewPathMap.first(), getFlagsToUseForRunningVmSnapshotCreation(target, filesystemsFrozenByThisWrapper)); + dm.snapshotCreateXML(snapshotXmlAndVolumeToNewPathMap.first(), + getFlagsToUseForRunningVmSnapshotCreation(target, filesystemsFrozenByThisWrapper, !blockDeltaVolumesAndPools.isEmpty(), cmd.isSnapshotMemory())); + if (cmd.isSnapshotMemory()) { + resource.getStoragePoolMgr().releaseVmSnapshotMemoryFile(getRootVolumePool(cmd, resource), memorySnapshotPath); + } postSnapshotCleanupIssue = recoverVmAfterSnapshot(dm, vmName, suspendedByThisWrapper, filesystemsFrozenByThisWrapper, postSnapshotCleanupIssue); filesystemsFrozenByThisWrapper = false; suspendedByThisWrapper = false; - answer = new CreateDiskOnlyVmSnapshotAnswer(cmd, true, null, snapshotXmlAndVolumeToNewPathMap.second(), nvramSnapshotPath); - } catch (LibvirtException | IOException e) { + answer = new CreateDiskOnlyVmSnapshotAnswer(cmd, true, null, snapshotXmlAndVolumeToNewPathMap.second(), nvramSnapshotPath, memorySnapshotPath); + } catch (LibvirtException | IOException | QemuImgException e) { String errorMsg = String.format("Creation of disk-only VM snapshot for VM [%s] failed due to %s.", vmName, e.getMessage()); logger.error(errorMsg, e); cleanupNvramSnapshotIfNeeded(cmd, resource, nvramSnapshotPath); + cleanupMemorySnapshotIfNeeded(cmd, resource, memorySnapshotPath); + deleteBlockDeltas(cmd, resource, blockDeltaVolumesAndPools); if (StringUtils.contains(e.getMessage(), "QEMU guest agent is not connected")) { errorMsg = "QEMU guest agent is not connected. If the VM has been recently started, it might connect soon. Otherwise the VM does not have the" + " guest agent installed; thus the QuiesceVM parameter is not supported."; @@ -152,7 +165,8 @@ protected Answer takeDiskOnlyVmSnapshotOfRunningVm(CreateDiskOnlyVmSnapshotComma if (answer != null && StringUtils.isNotBlank(postSnapshotCleanupIssue)) { answer = new CreateDiskOnlyVmSnapshotAnswer(cmd, answer.getResult(), - appendSnapshotOperationIssue(answer.getDetails(), postSnapshotCleanupIssue), answer.getMapVolumeToSnapshotSize(), answer.getNvramSnapshotPath()); + appendSnapshotOperationIssue(answer.getDetails(), postSnapshotCleanupIssue), answer.getMapVolumeToSnapshotSize(), answer.getNvramSnapshotPath(), + answer.getMemorySnapshotPath()); } return answer; } @@ -173,17 +187,10 @@ protected Answer takeDiskOnlyVmSnapshotOfStoppedVm(CreateDiskOnlyVmSnapshotComma PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) volumeObjectTO.getDataStore(); KVMStoragePool kvmStoragePool = storagePoolMgr.getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); - String snapshotPath = volumeObjectTOAndNewPath.second(); - String snapshotFullPath = kvmStoragePool.getLocalPathFor(snapshotPath); - QemuImgFile newDelta = new QemuImgFile(snapshotFullPath, QemuImg.PhysicalDiskFormat.QCOW2); - String currentDeltaFullPath = kvmStoragePool.getLocalPathFor(volumeObjectTO.getPath()); - QemuImgFile currentDelta = new QemuImgFile(currentDeltaFullPath, QemuImg.PhysicalDiskFormat.QCOW2); - - QemuImg qemuImg = new QemuImg(0); logger.debug("Creating new delta for volume [{}] as part of the disk-only VM snapshot process for VM [{}].", volumeObjectTO.getUuid(), vmName); - qemuImg.create(newDelta, currentDelta); + storagePoolMgr.createVmSnapshotDelta(kvmStoragePool, volumeObjectTOAndNewPath.second(), currentDeltaFullPath); mapVolumeToSnapshotSize.put(volumeObjectTO.getUuid(), getFileSize(currentDeltaFullPath)); } @@ -195,7 +202,7 @@ protected Answer takeDiskOnlyVmSnapshotOfStoppedVm(CreateDiskOnlyVmSnapshotComma KVMStoragePool kvmStoragePool = storagePoolMgr.getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); try { - Files.deleteIfExists(Path.of(kvmStoragePool.getLocalPathFor(volumeObjectTOAndNewPath.second()))); + storagePoolMgr.deleteVmSnapshotDelta(kvmStoragePool, volumeObjectTOAndNewPath.second()); } catch (IOException ex) { logger.warn("Tried to delete leftover snapshot at [{}] failed.", volumeObjectTOAndNewPath.second(), ex); } @@ -207,16 +214,49 @@ protected Answer takeDiskOnlyVmSnapshotOfStoppedVm(CreateDiskOnlyVmSnapshotComma return new CreateDiskOnlyVmSnapshotAnswer(cmd, true, null, mapVolumeToSnapshotSize, nvramSnapshotPath); } - protected int getFlagsToUseForRunningVmSnapshotCreation(VMSnapshotTO target, boolean filesystemsFrozenByThisWrapper) { - int flags = target.getQuiescevm() && !filesystemsFrozenByThisWrapper ? Domain.SnapshotCreateFlags.QUIESCE : 0; - flags += Domain.SnapshotCreateFlags.DISK_ONLY + - Domain.SnapshotCreateFlags.ATOMIC + + protected Map createBlockDeltas(CreateDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource, List disks) + throws QemuImgException, LibvirtException { + Map created = new HashMap<>(); + KVMStoragePoolManager storagePoolMgr = resource.getStoragePoolMgr(); + try { + for (Pair volumeAndNewPath : cmd.getVolumeTosAndNewPaths()) { + PrimaryDataStoreTO dataStore = (PrimaryDataStoreTO) volumeAndNewPath.first().getDataStore(); + KVMStoragePool pool = storagePoolMgr.getStoragePool(dataStore.getPoolType(), dataStore.getUuid()); + if (!storagePoolMgr.usesBlockVmSnapshotDeltas(pool)) { + continue; + } + String backingPath = resource.getDiskWithPathOfVolumeObjectTO(disks, volumeAndNewPath.first()).getDiskPath(); + storagePoolMgr.createVmSnapshotDelta(pool, volumeAndNewPath.second(), backingPath); + created.put(volumeAndNewPath.second(), pool); + } + } catch (QemuImgException | LibvirtException | RuntimeException e) { + deleteBlockDeltas(cmd, resource, created); + throw e; + } + return created; + } + + protected void deleteBlockDeltas(CreateDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource, Map deltasAndPools) { + for (Map.Entry deltaAndPool : deltasAndPools.entrySet()) { + try { + resource.getStoragePoolMgr().deleteVmSnapshotDelta(deltaAndPool.getValue(), deltaAndPool.getKey()); + } catch (IOException | RuntimeException e) { + logger.warn("Failed to delete leftover delta [{}] of VM [{}].", deltaAndPool.getKey(), cmd.getVmName(), e); + } + } + } + + protected int getFlagsToUseForRunningVmSnapshotCreation(VMSnapshotTO target, boolean filesystemsFrozenByThisWrapper, boolean reuseExternal, boolean snapshotMemory) { + int flags = target.getQuiescevm() && !filesystemsFrozenByThisWrapper && !snapshotMemory ? Domain.SnapshotCreateFlags.QUIESCE : 0; + flags += reuseExternal ? Domain.SnapshotCreateFlags.REUSE_EXT : 0; + flags += snapshotMemory ? 0 : Domain.SnapshotCreateFlags.DISK_ONLY; + flags += Domain.SnapshotCreateFlags.ATOMIC + Domain.SnapshotCreateFlags.NO_METADATA; return flags; } protected long getFileSize(String path) { - return new File(path).length(); + return ClvmBackingChain.getFileSize(path); } protected String backupNvramIfNeeded(CreateDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource) throws IOException, LibvirtException { @@ -229,14 +269,8 @@ protected String backupNvramIfNeeded(CreateDiskOnlyVmSnapshotCommand cmd, Libvir throw new IOException(String.format("Unable to find the active UEFI NVRAM file for VM [%s].", cmd.getVmName())); } - VolumeObjectTO rootVolume = getRootVolume(cmd.getVolumeTOs()); - PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) rootVolume.getDataStore(); - KVMStoragePool storagePool = resource.getStoragePoolMgr().getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); - String nvramSnapshotPath = getNvramSnapshotRelativePath(cmd.getTarget().getId()); - Path targetPath = Path.of(storagePool.getLocalPathFor(nvramSnapshotPath)); - Files.createDirectories(targetPath.getParent()); - Files.copy(Path.of(activeNvramPath), targetPath, StandardCopyOption.REPLACE_EXISTING); + resource.getStoragePoolMgr().saveVmSnapshotSidecar(getRootVolumePool(cmd, resource), nvramSnapshotPath, Path.of(activeNvramPath)); return nvramSnapshotPath; } @@ -246,15 +280,37 @@ protected void cleanupNvramSnapshotIfNeeded(CreateDiskOnlyVmSnapshotCommand cmd, } try { - VolumeObjectTO rootVolume = getRootVolume(cmd.getVolumeTOs()); - PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) rootVolume.getDataStore(); - KVMStoragePool storagePool = resource.getStoragePoolMgr().getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); - Files.deleteIfExists(Path.of(storagePool.getLocalPathFor(nvramSnapshotPath))); + resource.getStoragePoolMgr().deleteVmSnapshotSidecar(getRootVolumePool(cmd, resource), nvramSnapshotPath); } catch (Exception e) { logger.warn("Failed to clean up temporary NVRAM snapshot [{}] for VM [{}].", nvramSnapshotPath, cmd.getVmName(), e); } } + protected void cleanupMemorySnapshotIfNeeded(CreateDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource, String memorySnapshotPath) { + if (StringUtils.isBlank(memorySnapshotPath)) { + return; + } + + try { + resource.getStoragePoolMgr().deleteVmSnapshotSidecar(getRootVolumePool(cmd, resource), memorySnapshotPath); + } catch (Exception e) { + logger.warn("Failed to clean up temporary memory snapshot [{}] for VM [{}].", memorySnapshotPath, cmd.getVmName(), e); + } + } + + protected KVMStoragePool getRootVolumePool(CreateDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource) { + PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) getRootVolume(cmd.getVolumeTOs()).getDataStore(); + return resource.getStoragePoolMgr().getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); + } + + protected long getMemorySnapshotSize(Domain dm) throws LibvirtException { + return dm.getInfo().maxMem * 1024 + MEMORY_SNAPSHOT_OVERHEAD_BYTES; + } + + protected String getMemorySnapshotRelativePath(Long vmSnapshotId) { + return String.format("%s/%s.img", MEMORY_SNAPSHOT_DIR, vmSnapshotId); + } + protected String getNvramSnapshotRelativePath(Long vmSnapshotId) { return String.format("%s/%s.fd", NVRAM_SNAPSHOT_DIR, vmSnapshotId); } @@ -267,11 +323,11 @@ protected VolumeObjectTO getRootVolume(List volumeObjectTos) { } protected boolean shouldSuspendVmForSnapshot(CreateDiskOnlyVmSnapshotCommand cmd) { - return cmd.isUefiEnabled(); + return cmd.isUefiEnabled() && !cmd.isSnapshotMemory(); } protected boolean shouldFreezeVmFilesystemsForSnapshot(CreateDiskOnlyVmSnapshotCommand cmd) { - return cmd.isUefiEnabled() && cmd.getTarget().getQuiescevm(); + return cmd.isUefiEnabled() && cmd.getTarget().getQuiescevm() && !cmd.isSnapshotMemory(); } protected boolean suspendVmIfNeeded(Domain domain) throws LibvirtException { diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteDiskOnlyVMSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteDiskOnlyVMSnapshotCommandWrapper.java index 62c7c5013374..a1c0599f3ac7 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteDiskOnlyVMSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteDiskOnlyVMSnapshotCommandWrapper.java @@ -31,8 +31,6 @@ import org.apache.commons.lang3.StringUtils; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import com.cloud.storage.Volume; @@ -52,19 +50,30 @@ public Answer execute(DeleteDiskOnlyVmSnapshotCommand command, LibvirtComputingR try { String path = kvmStoragePool.getLocalPathFor(snapshot.getPath()); logger.debug("Deleting snapshot [{}] file [{}] as part of VM snapshot deletion.", snapshot.getId(), path); - Files.deleteIfExists(Path.of(path)); + storagePoolMgr.deleteVmSnapshotDelta(kvmStoragePool, snapshot.getPath()); } catch (IOException e) { return new Answer(command, e); } } deleteNvramSnapshotIfNeeded(command, resource, storagePoolMgr, snapshotsToDelete); + deleteMemorySnapshotIfNeeded(command, resource, storagePoolMgr, snapshotsToDelete); return new Answer(command, true, null); } protected void deleteNvramSnapshotIfNeeded(DeleteDiskOnlyVmSnapshotCommand command, LibvirtComputingResource resource, KVMStoragePoolManager storagePoolMgr, List snapshotsToDelete) { - if (StringUtils.isBlank(command.getNvramSnapshotPath())) { + deleteSidecarIfNeeded(command.getNvramSnapshotPath(), "UEFI NVRAM snapshot", command, resource, storagePoolMgr, snapshotsToDelete); + } + + protected void deleteMemorySnapshotIfNeeded(DeleteDiskOnlyVmSnapshotCommand command, LibvirtComputingResource resource, KVMStoragePoolManager storagePoolMgr, + List snapshotsToDelete) { + deleteSidecarIfNeeded(command.getMemorySnapshotPath(), "memory snapshot", command, resource, storagePoolMgr, snapshotsToDelete); + } + + private void deleteSidecarIfNeeded(String sidecarPath, String description, DeleteDiskOnlyVmSnapshotCommand command, LibvirtComputingResource resource, + KVMStoragePoolManager storagePoolMgr, List snapshotsToDelete) { + if (StringUtils.isBlank(sidecarPath)) { return; } @@ -81,16 +90,16 @@ protected void deleteNvramSnapshotIfNeeded(DeleteDiskOnlyVmSnapshotCommand comma .orElse(null); if (rootVolumeSnapshot == null) { - logger.warn("Unable to locate the root volume snapshot while deleting NVRAM snapshot [{}].", command.getNvramSnapshotPath()); + logger.warn("Unable to locate the root volume snapshot while deleting the {} [{}].", description, sidecarPath); return; } storagePool = resource.getLibvirtUtilitiesHelper().getPrimaryPoolFromDataTo(rootVolumeSnapshot, storagePoolMgr); } - Files.deleteIfExists(Path.of(storagePool.getLocalPathFor(command.getNvramSnapshotPath()))); + storagePoolMgr.deleteVmSnapshotSidecar(storagePool, sidecarPath); } catch (Exception e) { - logger.warn("Failed to delete the UEFI NVRAM snapshot [{}]. It will be left behind on storage.", command.getNvramSnapshotPath(), e); + logger.warn("Failed to delete the {} [{}]. It will be left behind on storage.", description, sidecarPath, e); } } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertDiskOnlyVMSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertDiskOnlyVMSnapshotCommandWrapper.java index e4cd527331bd..9bb4cc9eed90 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertDiskOnlyVMSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRevertDiskOnlyVMSnapshotCommandWrapper.java @@ -28,10 +28,9 @@ import com.cloud.resource.ResourceWrapper; import org.apache.cloudstack.storage.to.SnapshotObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; -import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImgException; -import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.commons.lang3.StringUtils; +import org.libvirt.Domain; import org.libvirt.LibvirtException; import java.io.IOException; @@ -42,8 +41,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import com.cloud.storage.Volume; +import com.cloud.utils.script.OutputInterpreter; +import com.cloud.utils.script.Script; @ResourceWrapper(handles = RevertDiskOnlyVmSnapshotCommand.class) public class LibvirtRevertDiskOnlyVMSnapshotCommandWrapper extends CommandWrapper { @@ -66,19 +68,14 @@ public Answer execute(RevertDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResou KVMStoragePool kvmStoragePool = libvirtUtilitiesHelper.getPrimaryPoolFromDataTo(snapshotObjectTo, storagePoolMgr); String deltaPath = libvirtUtilitiesHelper.generateUUIDName(); - String deltaFullPath = kvmStoragePool.getLocalPathFor(deltaPath); - QemuImgFile newDelta = new QemuImgFile(deltaFullPath, QemuImg.PhysicalDiskFormat.QCOW2); - String snapshotFullPath = kvmStoragePool.getLocalPathFor(snapshotObjectTo.getPath()); - QemuImgFile currentDelta = new QemuImgFile(snapshotFullPath, QemuImg.PhysicalDiskFormat.QCOW2); - - QemuImg qemuImg = new QemuImg(0); logger.debug("Creating new delta for volume [{}] as part of the disk-only VM snapshot revert process for VM [{}].", snapshotObjectTo.getVolume().getUuid(), vmName); - qemuImg.create(newDelta, currentDelta); + storagePoolMgr.createVmSnapshotDelta(kvmStoragePool, deltaPath, snapshotFullPath); snapshotToNewDeltaPath.put(snapshotObjectTo, deltaPath); } restoreNvramIfNeeded(cmd, resource, rootVolumeSnapshot, storagePoolMgr); + restoreMemoryStateIfNeeded(cmd, resource, snapshotToNewDeltaPath, rootVolumeSnapshot, storagePoolMgr); } catch (LibvirtException | QemuImgException | IOException e) { logger.error("Exception while reverting disk-only VM snapshot for VM [{}]. Deleting leftover deltas.", vmName, e); for (SnapshotObjectTO snapshotObjectTo : snapshotObjectTos) { @@ -90,7 +87,7 @@ public Answer execute(RevertDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResou KVMStoragePool kvmStoragePool = libvirtUtilitiesHelper.getPrimaryPoolFromDataTo(snapshotObjectTo, storagePoolMgr); try { - Files.deleteIfExists(Path.of(kvmStoragePool.getLocalPathFor(newPath))); + storagePoolMgr.deleteVmSnapshotDelta(kvmStoragePool, newPath); } catch (IOException ex) { logger.warn("Tried to delete leftover snapshot at [{}] failed.", newPath, ex); } @@ -105,7 +102,7 @@ public Answer execute(RevertDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResou KVMStoragePool kvmStoragePool = libvirtUtilitiesHelper.getPrimaryPoolFromDataTo(snapshotObjectTo, storagePoolMgr); try { - Files.deleteIfExists(Path.of(kvmStoragePool.getLocalPathFor(volumeObjectTo.getPath()))); + storagePoolMgr.deleteVmSnapshotDelta(kvmStoragePool, volumeObjectTo.getPath()); } catch (IOException ex) { logger.warn("Got an error while trying to delete old volume delta [{}], there might be trash on storage [{}].", volumeObjectTo.getPath(), kvmStoragePool.getUuid()); @@ -117,6 +114,79 @@ public Answer execute(RevertDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResou return new RevertDiskOnlyVmSnapshotAnswer(cmd, volumeObjectTos); } + /** + * Brings a running VM back to the memory snapshot: the domain is stopped and restored from the memory image, with its disks pointed at the new deltas. + */ + protected void restoreMemoryStateIfNeeded(RevertDiskOnlyVmSnapshotCommand cmd, LibvirtComputingResource resource, Map snapshotToNewDeltaPath, + SnapshotObjectTO rootVolumeSnapshot, KVMStoragePoolManager storagePoolMgr) throws IOException, LibvirtException { + if (StringUtils.isBlank(cmd.getMemorySnapshotPath())) { + return; + } + + KVMStoragePool rootPool = resource.getLibvirtUtilitiesHelper().getPrimaryPoolFromDataTo(rootVolumeSnapshot, storagePoolMgr); + String memoryDevicePath = storagePoolMgr.activateVmSnapshotMemoryFile(rootPool, cmd.getMemorySnapshotPath()); + try { + String domainXml = readSavedImageXml(memoryDevicePath); + for (Map.Entry snapshotAndNewDelta : snapshotToNewDeltaPath.entrySet()) { + KVMStoragePool pool = resource.getLibvirtUtilitiesHelper().getPrimaryPoolFromDataTo(snapshotAndNewDelta.getKey(), storagePoolMgr); + domainXml = replaceDiskPath(domainXml, pool.getLocalPathFor(snapshotAndNewDelta.getKey().getPath()), pool.getLocalPathFor(snapshotAndNewDelta.getValue())); + } + Path domainXmlFile = Files.createTempFile("vm-snapshot-restore-", ".xml"); + try { + Files.writeString(domainXmlFile, domainXml); + destroyDomainIfRunning(resource, cmd.getVmName()); + restoreDomain(memoryDevicePath, domainXmlFile); + } finally { + Files.deleteIfExists(domainXmlFile); + } + } finally { + try { + storagePoolMgr.releaseVmSnapshotMemoryFile(rootPool, cmd.getMemorySnapshotPath()); + } catch (IOException | RuntimeException e) { + logger.warn("Could not deactivate the memory image [{}] after restoring VM [{}].", cmd.getMemorySnapshotPath(), cmd.getVmName(), e); + } + } + } + + protected String readSavedImageXml(String memoryDevicePath) throws IOException { + Script dumpXml = new Script("virsh", 60000, logger); + dumpXml.add("save-image-dumpxml", memoryDevicePath); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = dumpXml.execute(parser); + if (result != null || StringUtils.isBlank(parser.getLines())) { + throw new IOException(String.format("Unable to read the domain definition of the memory image [%s]: %s", memoryDevicePath, result)); + } + return parser.getLines(); + } + + protected String replaceDiskPath(String domainXml, String snapshotLayerPath, String newDeltaPath) throws IOException { + if (!domainXml.contains(snapshotLayerPath)) { + throw new IOException(String.format("The memory image does not reference the snapshot layer [%s]; it does not belong to this snapshot.", snapshotLayerPath)); + } + return domainXml.replace(snapshotLayerPath, newDeltaPath); + } + + protected void destroyDomainIfRunning(LibvirtComputingResource resource, String vmName) throws LibvirtException { + Domain domain = resource.getDomain(resource.getLibvirtUtilitiesHelper().getConnection(), vmName); + if (domain == null) { + return; + } + try { + domain.destroy(); + } finally { + domain.free(); + } + } + + protected void restoreDomain(String memoryDevicePath, Path domainXmlFile) throws IOException { + Script restore = new Script("virsh", 300000, logger); + restore.add("restore", memoryDevicePath, "--xml", domainXmlFile.toString()); + String result = restore.execute(); + if (result != null) { + throw new IOException(String.format("Unable to restore the VM from the memory image [%s]: %s", memoryDevicePath, result)); + } + } + protected SnapshotObjectTO getRootVolumeSnapshot(List snapshotObjectTos) { return snapshotObjectTos.stream() .filter(snapshotObjectTO -> Volume.Type.ROOT.equals(snapshotObjectTO.getVolume().getVolumeType())) @@ -161,7 +231,11 @@ protected void restoreNvramIfNeeded(RevertDiskOnlyVmSnapshotCommand cmd, Libvirt throw new IOException(String.format("Unable to find the UEFI NVRAM snapshot [%s] for VM [%s].", cmd.getNvramSnapshotPath(), cmd.getVmName())); } - replaceNvramAtomically(snapshotNvramPath, Path.of(activeNvramPath)); + try { + replaceNvramAtomically(snapshotNvramPath, Path.of(activeNvramPath)); + } finally { + storagePoolMgr.releaseVmSnapshotSidecarPath(resource.getLibvirtUtilitiesHelper().getPrimaryPoolFromDataTo(rootVolumeSnapshot, storagePoolMgr), snapshotNvramPath); + } } protected void replaceNvramAtomically(Path snapshotNvramPath, Path activeNvramPath) throws IOException { @@ -198,6 +272,6 @@ protected Path getNvramSnapshotAbsolutePath(String nvramSnapshotPath, SnapshotOb } KVMStoragePool storagePool = resource.getLibvirtUtilitiesHelper().getPrimaryPoolFromDataTo(rootVolumeSnapshot, storagePoolMgr); - return Path.of(storagePool.getLocalPathFor(nvramSnapshotPath)); + return storagePoolMgr.getVmSnapshotSidecarPath(storagePool, nvramSnapshotPath); } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ClvmStorageAdaptor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ClvmStorageAdaptor.java index 2effaff23cfb..f27697f70579 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ClvmStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ClvmStorageAdaptor.java @@ -19,14 +19,17 @@ import static com.cloud.utils.NumbersUtil.toHumanReadableSize; import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtConnection; import com.cloud.hypervisor.kvm.resource.LibvirtStoragePoolDef; +import com.cloud.hypervisor.kvm.storage.clvm.ClvmBackingChain; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; @@ -49,6 +52,11 @@ * using direct LVM commands instead of libvirt for volume operations. */ public class ClvmStorageAdaptor extends LibvirtStorageAdaptor { + private static final long LOCK_RETRY_TIMEOUT_MILLIS = 180000L; + private static final long LOCK_RETRY_INTERVAL_MILLIS = 10000L; + private static final String LOCKED_BY_OTHER_HOST = "locked by other host"; + private static final String SIDECAR_LV_PREFIX = "vmsnapshot-"; + private static final String SIDECAR_SIZE_TAG_PREFIX = "sidecarsize_"; public ClvmStorageAdaptor(StorageLayer storage) { super(storage); @@ -644,45 +652,10 @@ private KVMPhysicalDisk createPhysicalDiskFromClvmLv(String lvPath, String volum */ private void ensureClvmNgBackingFileAccessible(String volumeName, KVMStoragePool pool) { try { - String vgName = getVgName(pool.getLocalPath()); - String volumePath = "/dev/" + vgName + "/" + volumeName; - - logger.debug("Checking if CLVM_NG volume {} has a backing file that needs activation", volumePath); - - Script qemuImgInfo = new Script("qemu-img", Duration.millis(10000), logger); - qemuImgInfo.add("info"); - qemuImgInfo.add("--output=json"); - qemuImgInfo.add(volumePath); - - OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); - String result = qemuImgInfo.execute(parser); - - if (result == null && parser.getLines() != null && !parser.getLines().isEmpty()) { - String jsonOutput = parser.getLines(); - - if (jsonOutput.contains("\"backing-filename\"")) { - int backingStart = jsonOutput.indexOf("\"backing-filename\""); - if (backingStart > 0) { - int valueStart = jsonOutput.indexOf(":", backingStart); - if (valueStart > 0) { - valueStart = jsonOutput.indexOf("\"", valueStart) + 1; - int valueEnd = jsonOutput.indexOf("\"", valueStart); - - if (valueEnd > valueStart) { - String backingFile = jsonOutput.substring(valueStart, valueEnd).trim(); - if (!backingFile.isEmpty() && backingFile.startsWith("/dev/")) { - logger.info("Volume {} has backing file: {}. Ensuring backing file is in shared mode.", volumePath, backingFile); - ensureTemplateLvInSharedMode(backingFile, false); - } - } - } - } - } else { - logger.debug("Volume {} does not have a backing file (full clone)", volumePath); - } - } + String volumePath = "/dev/" + getVgName(pool.getLocalPath()) + "/" + volumeName; + ClvmBackingChain.walkBackingLvPaths(volumePath, backingPath -> ensureTemplateLvInSharedMode(backingPath, false)); } catch (Exception e) { - logger.warn("Failed to check/activate backing file for volume {}: {}. VM deployment may fail if template is not accessible.", + logger.warn("Failed to check/activate backing files for volume {}: {}. VM deployment may fail if they are not accessible.", volumeName, e.getMessage()); } } @@ -729,7 +702,7 @@ private void ensureTemplateLvInSharedMode(String templatePath, boolean throwOnFa if (!isShared || !isActive) { logger.info("Template LV {} is not in shared mode (attr: {}). Activating in shared mode.", templatePath, lvAttr); - LibvirtComputingResource.setClvmVolumeToSharedMode(templatePath); + activateSharedWithRetry(templatePath); } else { logger.debug("Template LV {} is already in shared mode (attr: {})", templatePath, lvAttr); } @@ -927,6 +900,177 @@ private KVMPhysicalDisk createClvmNgDiskWithBacking(String volumeUuid, int timeo return disk; } + @Override + public boolean usesBlockVmSnapshotDeltas(KVMStoragePool pool) { + return StoragePoolType.CLVM_NG.equals(pool.getType()); + } + + @Override + public KVMPhysicalDisk createVmSnapshotDelta(String deltaName, String backingPath, KVMStoragePool pool) { + activateLvIfInactive(backingPath); + long virtualSize = getQcow2VirtualSize(backingPath); + return createClvmNgDiskWithBacking(deltaName, 0, virtualSize, backingPath, pool, Storage.ProvisioningType.THIN); + } + + @Override + public void saveVmSnapshotSidecar(KVMStoragePool pool, String relativePath, Path source) throws IOException { + String vgName = getVgName(pool.getLocalPath()); + String lvName = getSidecarLvName(relativePath); + String lvPath = "/dev/" + vgName + "/" + lvName; + + long sidecarSize = Files.size(source); + Script lvcreate = new Script("lvcreate", Duration.millis(60000), logger); + lvcreate.add("-n", lvName, "-L", sidecarSize + "B", "--addtag", SIDECAR_SIZE_TAG_PREFIX + sidecarSize, "--yes", vgName); + runSidecarCommand(lvcreate, "create sidecar LV " + lvPath); + try { + Script dd = new Script("dd", Duration.millis(60000), logger); + dd.add("if=" + source, "of=" + lvPath, "conv=fsync"); + runSidecarCommand(dd, "write sidecar LV " + lvPath); + Script deactivate = new Script("lvchange", Duration.millis(60000), logger); + deactivate.add("-an", lvPath); + runSidecarCommand(deactivate, "deactivate sidecar LV " + lvPath); + } catch (IOException | RuntimeException e) { + removeLvOnFailure(lvPath, 60000); + throw e; + } + } + + @Override + public Path materializeVmSnapshotSidecar(KVMStoragePool pool, String relativePath) throws IOException { + String lvPath = "/dev/" + getVgName(pool.getLocalPath()) + "/" + getSidecarLvName(relativePath); + Script activate = new Script("lvchange", Duration.millis(60000), logger); + activate.add("-asy", lvPath); + runSidecarCommand(activate, "activate sidecar LV " + lvPath); + try { + Path target = Path.of(System.getProperty("java.io.tmpdir"), getSidecarLvName(relativePath) + ".fd"); + Script dd = new Script("dd", Duration.millis(60000), logger); + dd.add("if=" + lvPath, "of=" + target, "iflag=count_bytes", "count=" + getSidecarSize(lvPath)); + runSidecarCommand(dd, "read sidecar LV " + lvPath); + return target; + } finally { + Script deactivate = new Script("lvchange", Duration.millis(60000), logger); + deactivate.add("-an", lvPath); + deactivate.execute(); + } + } + + @Override + public void deleteVmSnapshotSidecar(KVMStoragePool pool, String relativePath) { + deletePhysicalDisk(getSidecarLvName(relativePath), pool, Storage.ImageFormat.RAW); + } + + private String getSidecarLvName(String relativePath) { + Path path = Path.of(relativePath); + String fileName = path.getFileName().toString(); + int extension = fileName.lastIndexOf('.'); + String id = extension > 0 ? fileName.substring(0, extension) : fileName; + String kind = path.getParent() == null ? "" : path.getParent().getFileName().toString().replaceFirst("^\\.", "").replaceFirst("^cloudstack-vm-snapshot-", "") + .replaceAll("[^A-Za-z0-9_+.-]", "-") + "-"; + return SIDECAR_LV_PREFIX + kind + id; + } + + @Override + public String createVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath, long size) throws IOException { + String vgName = getVgName(pool.getLocalPath()); + String lvName = getSidecarLvName(relativePath); + Script lvcreate = new Script("lvcreate", Duration.millis(60000), logger); + lvcreate.add("-n", lvName, "-L", size + "B", "--yes", vgName); + runSidecarCommand(lvcreate, "create memory LV " + lvName); + return "/dev/" + vgName + "/" + lvName; + } + + @Override + public String activateVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath) throws IOException { + String lvPath = "/dev/" + getVgName(pool.getLocalPath()) + "/" + getSidecarLvName(relativePath); + Script activate = new Script("lvchange", Duration.millis(60000), logger); + activate.add("-asy", lvPath); + runSidecarCommand(activate, "activate memory LV " + lvPath); + return lvPath; + } + + @Override + public void releaseVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath) throws IOException { + String lvPath = "/dev/" + getVgName(pool.getLocalPath()) + "/" + getSidecarLvName(relativePath); + Script deactivate = new Script("lvchange", Duration.millis(60000), logger); + deactivate.add("-an", lvPath); + runSidecarCommand(deactivate, "deactivate memory LV " + lvPath); + } + + private long getSidecarSize(String lvPath) throws IOException { + Script lvs = new Script("lvs", Duration.millis(30000), logger); + lvs.add("--noheadings", "-o", "lv_tags", lvPath); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + runSidecarCommand(lvs, "read tags of sidecar LV " + lvPath, parser); + for (String tag : parser.getLines().trim().split(",")) { + if (tag.startsWith(SIDECAR_SIZE_TAG_PREFIX)) { + return Long.parseLong(tag.substring(SIDECAR_SIZE_TAG_PREFIX.length())); + } + } + throw new IOException("Sidecar LV " + lvPath + " has no size tag."); + } + + private void runSidecarCommand(Script command, String description) throws IOException { + runSidecarCommand(command, description, null); + } + + private void runSidecarCommand(Script command, String description, OutputInterpreter parser) throws IOException { + String result = parser == null ? command.execute() : command.execute(parser); + if (result != null) { + throw new IOException("Failed to " + description + ": " + result); + } + } + + private void activateLvIfInactive(String lvPath) { + Script lvs = new Script("lvs", Duration.millis(30000), logger); + lvs.add("--noheadings"); + lvs.add("-o", "lv_attr"); + lvs.add(lvPath); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = lvs.execute(parser); + if (result != null) { + throw new CloudRuntimeException("Failed to read LV attributes of " + lvPath + ": " + result); + } + String attr = parser.getLines() == null ? "" : parser.getLines().trim(); + if (attr.indexOf('a') < 0) { + logger.info("LV {} is inactive, activating it in shared mode so it can back a VM snapshot delta.", lvPath); + activateSharedWithRetry(lvPath); + } + } + + /** + * Activates the LV in shared mode. While another host holds its lock, which also happens after a host failure until the lease of that host expires, + * the activation is retried for the same time the management server retries the lock of a volume. + */ + protected void activateSharedWithRetry(String lvPath) { + long deadline = System.currentTimeMillis() + LOCK_RETRY_TIMEOUT_MILLIS; + while (true) { + Script activate = new Script("lvchange", Duration.millis(60000), logger); + activate.add("-asy", lvPath); + String result = activate.execute(); + if (result == null) { + return; + } + if (!result.contains(LOCKED_BY_OTHER_HOST) || System.currentTimeMillis() >= deadline) { + logger.warn("Failed to activate LV {} in shared mode: {}", lvPath, result); + return; + } + logger.info("LV {} is locked by another host, retrying its activation in {} s.", lvPath, LOCK_RETRY_INTERVAL_MILLIS / 1000); + if (!sleepBeforeLockRetry()) { + return; + } + } + } + + protected boolean sleepBeforeLockRetry() { + try { + Thread.sleep(LOCK_RETRY_INTERVAL_MILLIS); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + private boolean lvExists(String lvPath) { Script checkLv = new Script("lvs", Duration.millis(30000), logger); checkLv.add("--noheadings"); 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..edfdcefd1eb7 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 @@ -16,10 +16,14 @@ // under the License. package com.cloud.hypervisor.kvm.storage; +import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -30,10 +34,14 @@ import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.cloudstack.utils.qemu.QemuImg; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; +import org.apache.cloudstack.utils.qemu.QemuImgException; +import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.commons.collections.MapUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.libvirt.LibvirtException; import org.reflections.Reflections; import com.cloud.agent.api.to.DiskTO; @@ -569,6 +577,75 @@ public void createTemplateOnClvmNg(String templatePath, String templateUuid, int adaptor.createTemplate(templatePath, templateUuid, timeout, pool); } + public boolean usesBlockVmSnapshotDeltas(KVMStoragePool pool) { + return getStorageAdaptor(pool.getType()).usesBlockVmSnapshotDeltas(pool); + } + + public void createVmSnapshotDelta(KVMStoragePool pool, String deltaName, String backingPath) throws QemuImgException, LibvirtException { + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); + if (adaptor.usesBlockVmSnapshotDeltas(pool)) { + adaptor.createVmSnapshotDelta(deltaName, backingPath, pool); + return; + } + new QemuImg(0).create(new QemuImgFile(pool.getLocalPathFor(deltaName), QemuImg.PhysicalDiskFormat.QCOW2), + new QemuImgFile(backingPath, QemuImg.PhysicalDiskFormat.QCOW2)); + } + + public void deleteVmSnapshotDelta(KVMStoragePool pool, String deltaName) throws IOException { + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); + if (adaptor.usesBlockVmSnapshotDeltas(pool)) { + adaptor.deletePhysicalDisk(deltaName, pool, Storage.ImageFormat.QCOW2); + return; + } + Files.deleteIfExists(Path.of(pool.getLocalPathFor(deltaName))); + } + + public void saveVmSnapshotSidecar(KVMStoragePool pool, String relativePath, Path source) throws IOException { + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); + if (adaptor.usesBlockVmSnapshotDeltas(pool)) { + adaptor.saveVmSnapshotSidecar(pool, relativePath, source); + return; + } + Path target = Path.of(pool.getLocalPathFor(relativePath)); + Files.createDirectories(target.getParent()); + Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); + } + + public Path getVmSnapshotSidecarPath(KVMStoragePool pool, String relativePath) throws IOException { + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); + if (adaptor.usesBlockVmSnapshotDeltas(pool)) { + return adaptor.materializeVmSnapshotSidecar(pool, relativePath); + } + return Path.of(pool.getLocalPathFor(relativePath)); + } + + public void releaseVmSnapshotSidecarPath(KVMStoragePool pool, Path sidecarPath) throws IOException { + if (usesBlockVmSnapshotDeltas(pool)) { + Files.deleteIfExists(sidecarPath); + } + } + + public String createVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath, long size) throws IOException { + return getStorageAdaptor(pool.getType()).createVmSnapshotMemoryFile(pool, relativePath, size); + } + + public String activateVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath) throws IOException { + return getStorageAdaptor(pool.getType()).activateVmSnapshotMemoryFile(pool, relativePath); + } + + public void releaseVmSnapshotMemoryFile(KVMStoragePool pool, String relativePath) throws IOException { + getStorageAdaptor(pool.getType()).releaseVmSnapshotMemoryFile(pool, relativePath); + } + + public void deleteVmSnapshotSidecar(KVMStoragePool pool, String relativePath) throws IOException { + StorageAdaptor adaptor = getStorageAdaptor(pool.getType()); + if (adaptor.usesBlockVmSnapshotDeltas(pool)) { + adaptor.deleteVmSnapshotSidecar(pool, relativePath); + return; + } + Files.deleteIfExists(Path.of(pool.getLocalPathFor(relativePath))); + } + public Ternary, String> prepareStorageClient(StoragePoolType type, String uuid, Map details) { StorageAdaptor adaptor = getStorageAdaptor(type); return adaptor.prepareStorageClient(uuid, details); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java index fb474a6bc7d3..81943af321f7 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.hypervisor.kvm.storage; +import java.io.IOException; +import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -152,4 +154,36 @@ default Pair unprepareStorageClient(String uuid, Map getBackingLvPaths(String lvPath) { + List backingPaths = new ArrayList<>(); + walkBackingLvPaths(lvPath, backingPaths::add); + return backingPaths; + } + + /** Visits each backing LV, nearest first; the visitor may activate it, as the next backing file is only readable afterwards. */ + public static void walkBackingLvPaths(String lvPath, Consumer visitor) { + String current = lvPath; + for (int depth = 0; depth < MAX_CHAIN_DEPTH; depth++) { + String backingPath = getDirectBackingLvPath(current); + if (backingPath == null) { + return; + } + visitor.accept(backingPath); + current = backingPath; + } + LOGGER.warn("Backing chain of {} is deeper than {}; stopped walking it.", lvPath, MAX_CHAIN_DEPTH); + } + + private static String getDirectBackingLvPath(String lvPath) { + Script qemuImgInfo = new Script("qemu-img", Duration.millis(30000), LOGGER); + qemuImgInfo.add("info", "--output=json", "-U", lvPath); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + String result = qemuImgInfo.execute(parser); + if (result != null || parser.getLines() == null || parser.getLines().isEmpty()) { + LOGGER.warn("Unable to read the backing file of {}: {}", lvPath, result); + return null; + } + JsonElement backingFile = JsonParser.parseString(parser.getLines()).getAsJsonObject().get("backing-filename"); + if (backingFile == null || !backingFile.getAsString().startsWith("/dev/")) { + return null; + } + return backingFile.getAsString(); + } + + /** Backing LVs that belong to the volume's own chain (VM snapshot layers), i.e. not shared templates. */ + public static List getSnapshotLayerLvPaths(String lvPath) { + List layers = new ArrayList<>(); + for (String backingPath : getBackingLvPaths(lvPath)) { + if (!backingPath.substring(backingPath.lastIndexOf(File.separator) + 1).startsWith(TEMPLATE_LV_PREFIX)) { + layers.add(backingPath); + } + } + return layers; + } + + /** Bytes used by the file, or by the qcow2 data of a block device, whose own length is its LV size. */ + public static long getFileSize(String path) { + if (!path.startsWith("/dev/")) { + return new File(path).length(); + } + Script qemuImgCheck = new Script("qemu-img", Duration.millis(60000), LOGGER); + qemuImgCheck.add("check", "--output=json", "-U", path); + OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); + qemuImgCheck.execute(parser); + if (parser.getLines() == null || parser.getLines().isEmpty()) { + LOGGER.warn("Unable to read the used size of {}.", path); + return 0; + } + try { + JsonElement imageEnd = JsonParser.parseString(parser.getLines()).getAsJsonObject().get("image-end-offset"); + return imageEnd == null ? 0 : imageEnd.getAsLong(); + } catch (JsonParseException | IllegalStateException e) { + LOGGER.warn("Unable to read the used size of {}: {}", path, parser.getLines()); + return 0; + } + } +} diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java index 49ac50a9f599..f6b27a4f76ce 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java @@ -6923,6 +6923,48 @@ public void mergeSnapshotIntoBaseFileTestMergeFailsThrowException() throws Excep } } + @Test + public void ensureDeltaParentIsExclusiveActivatesParentOnBlockPools() { + KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class); + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + Mockito.doReturn(storagePoolManager).when(libvirtComputingResourceSpy).getStoragePoolMgr(); + Mockito.when(storagePoolManager.usesBlockVmSnapshotDeltas(pool)).thenReturn(true); + Mockito.doNothing().when(libvirtComputingResourceSpy).activateExclusively("/dev/vg/parent"); + + libvirtComputingResourceSpy.ensureDeltaParentIsExclusive(pool, "/dev/vg/parent"); + + Mockito.verify(libvirtComputingResourceSpy).activateExclusively("/dev/vg/parent"); + } + + @Test + public void ensureDeltaParentIsExclusiveFailsWithClearErrorWhenParentIsHeldElsewhere() { + KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class); + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + Mockito.doReturn(storagePoolManager).when(libvirtComputingResourceSpy).getStoragePoolMgr(); + Mockito.when(storagePoolManager.usesBlockVmSnapshotDeltas(pool)).thenReturn(true); + Mockito.doThrow(new CloudRuntimeException("lock held")).when(libvirtComputingResourceSpy).activateExclusively("/dev/vg/parent"); + + try { + libvirtComputingResourceSpy.ensureDeltaParentIsExclusive(pool, "/dev/vg/parent"); + Assert.fail("Expected the merge to be refused."); + } catch (CloudRuntimeException e) { + Assert.assertTrue(e.getMessage().contains("lvchange -an /dev/vg/parent")); + Assert.assertTrue(e.getMessage().contains("lock held")); + } + } + + @Test + public void ensureDeltaParentIsExclusiveDoesNothingOnFilePools() { + KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class); + KVMStoragePool pool = Mockito.mock(KVMStoragePool.class); + Mockito.doReturn(storagePoolManager).when(libvirtComputingResourceSpy).getStoragePoolMgr(); + Mockito.when(storagePoolManager.usesBlockVmSnapshotDeltas(pool)).thenReturn(false); + + libvirtComputingResourceSpy.ensureDeltaParentIsExclusive(pool, "/dev/vg/parent"); + + Mockito.verify(libvirtComputingResourceSpy, Mockito.never()).activateExclusively(Mockito.anyString()); + } + @Test (expected = CloudRuntimeException.class) public void manuallyDeleteUnusedSnapshotFileTestLibvirtDoesNotSupportsFlagDeleteExceptionOnFileDeletionThrowsException() throws IOException { try (MockedStatic filesMockedStatic = Mockito.mockStatic(Files.class)) { diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapperTest.java index 5d11cf209a45..54d14db1dfe3 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapperTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtClvmLockTransferCommandWrapperTest.java @@ -25,16 +25,20 @@ import static org.mockito.Mockito.when; import org.apache.cloudstack.storage.clvm.command.ClvmLockTransferCommand; +import java.util.Collections; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import com.cloud.agent.api.Answer; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.hypervisor.kvm.storage.clvm.ClvmBackingChain; import com.cloud.utils.script.Script; /** @@ -77,13 +81,36 @@ public void testExecute_DeactivateSuccess() { assertTrue(answer.getDetails().contains(TEST_VOLUME_UUID)); // Verify script was constructed with correct parameters - assertEquals(1, scriptMock.constructed().size()); - Script script = scriptMock.constructed().get(0); + assertEquals(2, scriptMock.constructed().size()); + Script script = scriptMock.constructed().get(1); verify(script).add("-an"); verify(script).add(TEST_LV_PATH); } } + @Test + public void testExecute_DeactivateAlsoDeactivatesSnapshotLayers() { + ClvmLockTransferCommand cmd = new ClvmLockTransferCommand( + ClvmLockTransferCommand.Operation.DEACTIVATE, + TEST_LV_PATH, + TEST_VOLUME_UUID + ); + + try (MockedStatic chain = Mockito.mockStatic(ClvmBackingChain.class); + MockedConstruction