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 79e2a9722039..bb6767eb443a 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 @@ -85,7 +85,8 @@ public class KvmFileBasedStorageVmSnapshotStrategy extends StorageVMSnapshotStrategy { private static final List supportedStoragePoolTypes = List.of(Storage.StoragePoolType.Filesystem, Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint); - private static final String KVM_FILE_BASED_STORAGE_SNAPSHOT_NVRAM = "kvmFileBasedStorageSnapshotNvram"; + protected static final String KVM_FILE_BASED_STORAGE_SNAPSHOT_NVRAM = "kvmFileBasedStorageSnapshotNvram"; + protected static final String KVM_FILE_BASED_STORAGE_SNAPSHOT_STRATEGY = "kvmFileBasedStorageSnapshotStrategy"; @Inject protected SnapshotDataStoreDao snapshotDataStoreDao; @@ -133,8 +134,12 @@ public VMSnapshot takeVMSnapshot(VMSnapshot vmSnapshot) { @Override public boolean deleteVMSnapshot(VMSnapshot vmSnapshot) { logger.info("Starting VM snapshot delete process for snapshot [{}].", vmSnapshot.getUuid()); - UserVmVO userVm = userVmDao.findById(vmSnapshot.getVmId()); VMSnapshotVO vmSnapshotBeingDeleted = (VMSnapshotVO) vmSnapshot; + if (!hasRelevantVmSnapshotDetails(vmSnapshotBeingDeleted)) { + return deleteVMSnapshotMetadataOnly(vmSnapshotBeingDeleted); + } + + UserVmVO userVm = userVmDao.findById(vmSnapshot.getVmId()); Long hostId = pickHostForNvramSidecarCleanup(vmSnapshotBeingDeleted, userVm, "delete"); validateHostSupportsNvramSidecarCleanup(vmSnapshotBeingDeleted, hostId, "delete"); long virtualSize = 0; @@ -322,16 +327,41 @@ private void mergeOldSiblingWithOldParentIfOldParentIsDead(VMSnapshotVO oldParen transitStateWithoutThrow(oldParent, VMSnapshot.Event.OperationSucceeded); } + protected boolean deleteVMSnapshotMetadataOnly(VMSnapshotVO vmSnapshot) { + logger.info("VM snapshot [{}] has no volume snapshots or NVRAM sidecar on primary storage; removing only its metadata.", vmSnapshot.getUuid()); + + transitStateWithoutThrow(vmSnapshot, VMSnapshot.Event.ExpungeRequested); + transitStateWithoutThrow(vmSnapshot, VMSnapshot.Event.OperationSucceeded); + + vmSnapshotDetailsDao.removeDetails(vmSnapshot.getId()); + + vmSnapshot.setRemoved(DateUtil.now()); + vmSnapshotDao.update(vmSnapshot.getId(), vmSnapshot); + + return true; + } + + protected boolean hasKVMFileBasedStorageSnapshotDetailInVmSnapshotDetails(VMSnapshot vmSnapshot) { + return CollectionUtils.isNotEmpty(vmSnapshotDetailsDao.findDetails(vmSnapshot.getId(), KVM_FILE_BASED_STORAGE_SNAPSHOT)); + } + + protected boolean hasRelevantVmSnapshotDetails(VMSnapshotVO vmSnapshot) { + return hasKVMFileBasedStorageSnapshotDetailInVmSnapshotDetails(vmSnapshot) || StringUtils.isNotBlank(getNvramSnapshotPath(vmSnapshot)); + } + + protected boolean isCreatedByThisStrategy(VMSnapshot vmSnapshot) { + return vmSnapshotDetailsDao.findDetail(vmSnapshot.getId(), KVM_FILE_BASED_STORAGE_SNAPSHOT_STRATEGY) != null; + } + @Override public StrategyPriority canHandle(VMSnapshot vmSnapshot) { if (!VMSnapshot.State.Allocated.equals(vmSnapshot.getState())) { - List vmSnapshotDetails = vmSnapshotDetailsDao.findDetails(vmSnapshot.getId(), KVM_FILE_BASED_STORAGE_SNAPSHOT); - if (CollectionUtils.isEmpty(vmSnapshotDetails)) { - logger.debug("KVM file based storage VM snapshot strategy cannot handle [{}] as it is not a KVM file based storage VM snapshot.", - vmSnapshot.getUuid()); - return StrategyPriority.CANT_HANDLE; + if (hasKVMFileBasedStorageSnapshotDetailInVmSnapshotDetails(vmSnapshot) || isCreatedByThisStrategy(vmSnapshot)) { + return StrategyPriority.HIGHEST; } - return StrategyPriority.HIGHEST; + logger.debug("KVM file based storage VM snapshot strategy cannot handle [{}] as it is not a KVM file based storage VM snapshot.", + vmSnapshot.getUuid()); + return StrategyPriority.CANT_HANDLE; } long vmId = vmSnapshot.getVmId(); @@ -523,6 +553,7 @@ protected VMSnapshot takeVmSnapshotInternal(VMSnapshot vmSnapshot, Map command instanceof DeleteDiskOnlyVmSnapshotCommand + && ((DeleteDiskOnlyVmSnapshotCommand) command).getSnapshots().isEmpty() + && "nvram/42.fd".equals(((DeleteDiskOnlyVmSnapshotCommand) command).getNvramSnapshotPath()) + && ((DeleteDiskOnlyVmSnapshotCommand) command).getPrimaryDataStore() == null)); + verify(agentMgr).easySend(eq(hostId), argThat(command -> command instanceof DeleteDiskOnlyVmSnapshotCommand + && "nvram/42.fd".equals(((DeleteDiskOnlyVmSnapshotCommand) command).getNvramSnapshotPath()) + && ((DeleteDiskOnlyVmSnapshotCommand) command).getPrimaryDataStore() == primaryDataStore)); + verify(vmSnapshotDetailsDao).removeDetails(vmSnapshotId); + verify(vmSnapshotDao).update(vmSnapshotId, vmSnapshot); + } + + private VMSnapshotVO mockVmSnapshotForCanHandle(VMSnapshot.State state) { + VMSnapshotVO vmSnapshot = mock(VMSnapshotVO.class); + when(vmSnapshot.getId()).thenReturn(20L); + when(vmSnapshot.getVmId()).thenReturn(10L); + when(vmSnapshot.getUuid()).thenReturn("vm-snapshot"); + when(vmSnapshot.getState()).thenReturn(state); + when(vmSnapshot.getType()).thenReturn(VMSnapshot.Type.Disk); + return vmSnapshot; + } + private void mockCandidateHostScope(long vmId, long hostId) { long poolId = 50L; long clusterId = 60L; diff --git a/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java index e6a641763104..60fec3c6e21a 100644 --- a/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java @@ -511,6 +511,19 @@ private VMSnapshotStrategy findVMSnapshotStrategy(VMSnapshot vmSnapshot) { return snapshotStrategy; } + protected boolean deleteVMSnapshotUsingStrategy(VMSnapshot vmSnapshot) { + VMSnapshotStrategy strategy = storageStrategyFactory.getVmSnapshotStrategy(vmSnapshot); + if (strategy != null) { + return strategy.deleteVMSnapshot(vmSnapshot); + } + if (!VMSnapshot.State.Error.equals(vmSnapshot.getState())) { + throw new CloudRuntimeException(String.format("Can't find Instance Snapshot strategy for vmsnapshot: %s", vmSnapshot)); + } + logger.warn("No Instance Snapshot strategy can handle {} in Error state; removing only its metadata.", vmSnapshot); + _vmSnapshotDetailsDao.removeDetails(vmSnapshot.getId()); + return _vmSnapshotDao.remove(vmSnapshot.getId()); + } + @Override @ActionEvent(eventType = EventTypes.EVENT_VM_SNAPSHOT_CREATE, eventDescription = "Creating Instance Snapshot", async = true) public VMSnapshot createVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm) { @@ -717,8 +730,7 @@ private boolean orchestrateDeleteVMSnapshot(Long vmSnapshotId) { return _vmSnapshotDao.remove(vmSnapshot.getId()); } else { try { - VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshot); - return strategy.deleteVMSnapshot(vmSnapshot); + return deleteVMSnapshotUsingStrategy(vmSnapshot); } catch (Exception e) { logger.debug("Failed to delete Instance Snapshot: {}", vmSnapshot, e); return false; @@ -1112,8 +1124,7 @@ private boolean orchestrateDeleteAllVMSnapshots(long vmId, VMSnapshot.Type type) VMSnapshotVO target = _vmSnapshotDao.findById(snapshot.getId()); if (type != null && target.getType() != type) continue; - VMSnapshotStrategy strategy = findVMSnapshotStrategy(target); - if (!strategy.deleteVMSnapshot(target)) { + if (!deleteVMSnapshotUsingStrategy(target)) { result = false; break; } diff --git a/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java b/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java index c6a420d01d8e..a1a45b845852 100644 --- a/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java +++ b/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java @@ -60,6 +60,8 @@ import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ResourceDetail; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageStrategyFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VMSnapshotStrategy; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; @@ -154,6 +156,10 @@ public class VMSnapshotManagerTest { private static final String VM_SNAPSHOT_DESCRIPTION = "Vm-Snapshot-Desc"; private static final String VM_SNAPSHOT_DISPLAY_NAME = "Vm-Snapshot-Display-Name"; @Mock + StorageStrategyFactory storageStrategyFactory; + @Mock + VMSnapshotStrategy vmSnapshotStrategy; + @Mock UserVmVO vmMock; @Mock VolumeVO volumeMock; @@ -202,6 +208,7 @@ public void setup() { _vmSnapshotMgr._vmInstanceDetailsDao = _vmInstanceDetailsDao; _vmSnapshotMgr._vmSnapshotDetailsDao = _vmSnapshotDetailsDao; _vmSnapshotMgr._userVmManager = _userVmManager; + _vmSnapshotMgr.storageStrategyFactory = storageStrategyFactory; when(_userVMDao.findById(anyLong())).thenReturn(vmMock); when(_vmSnapshotDao.findByName(anyLong(), anyString())).thenReturn(null); @@ -430,6 +437,42 @@ public void testUpgradeUserVmServiceOffering() throws ConcurrentOperationExcepti verify(_userVmManager).upgradeVirtualMachine(TEST_VM_ID, SERVICE_OFFERING_ID, details); } + @Test + public void testDeleteVMSnapshotUsingStrategyDelegatesToTheStrategyThatHandlesTheSnapshot() { + when(storageStrategyFactory.getVmSnapshotStrategy(vmSnapshotVO)).thenReturn(vmSnapshotStrategy); + when(vmSnapshotStrategy.deleteVMSnapshot(vmSnapshotVO)).thenReturn(true); + + assertTrue(_vmSnapshotMgr.deleteVMSnapshotUsingStrategy(vmSnapshotVO)); + + verify(vmSnapshotStrategy).deleteVMSnapshot(vmSnapshotVO); + verify(_vmSnapshotDao, never()).remove(anyLong()); + } + + @Test + public void testDeleteVMSnapshotUsingStrategyRemovesMetadataOfErrorSnapshotNoStrategyHandles() { + when(storageStrategyFactory.getVmSnapshotStrategy(vmSnapshotVO)).thenReturn(null); + when(vmSnapshotVO.getState()).thenReturn(VMSnapshot.State.Error); + when(_vmSnapshotDao.remove(VM_SNAPSHOT_ID)).thenReturn(true); + + assertTrue(_vmSnapshotMgr.deleteVMSnapshotUsingStrategy(vmSnapshotVO)); + + verify(_vmSnapshotDetailsDao).removeDetails(VM_SNAPSHOT_ID); + verify(_vmSnapshotDao).remove(VM_SNAPSHOT_ID); + } + + @Test(expected = CloudRuntimeException.class) + public void testDeleteVMSnapshotUsingStrategyFailsForReadySnapshotNoStrategyHandles() { + when(storageStrategyFactory.getVmSnapshotStrategy(vmSnapshotVO)).thenReturn(null); + when(vmSnapshotVO.getState()).thenReturn(VMSnapshot.State.Ready); + + try { + _vmSnapshotMgr.deleteVMSnapshotUsingStrategy(vmSnapshotVO); + } finally { + verify(_vmSnapshotDetailsDao, never()).removeDetails(anyLong()); + verify(_vmSnapshotDao, never()).remove(anyLong()); + } + } + @Test public void testRevertUserVmDetailsFromVmSnapshotNotDynamicServiceOffering() { _vmSnapshotMgr.revertCustomServiceOfferingDetailsFromVmSnapshot(vmMock, vmSnapshotVO);