From 2bdc31cee54477781f8b5fb325de6609fed0aa16 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:14:09 +0000 Subject: [PATCH 01/12] KVM: opt-in no-copy volume snapshots on file-based primary storage Adds the storage-pool setting kvm.file.based.volume.snapshot.no.copy (default false). When it is enabled, volume snapshots of KVM QCOW2 volumes on NFS, SharedMountPoint and Filesystem pools that are kept only on primary storage are taken in the backing chain of the volume instead of as full copies. Taking and reverting such a snapshot no longer copies the volume, and deleting it merges it with its child. - New KvmFileBasedNoCopySnapshotStrategy, reusing the disk-only Instance snapshot agent commands for one volume. - KVM agent: disk-only snapshot XML lists every other disk of the domain with snapshot='no', so that Libvirt does not implicitly move the volumes that are not snapshotted. Advertised as host.kvm.diskonlysnapshot.singlevolume; running Instances only get no-copy snapshots on hosts that advertise it. - Only the latest no-copy snapshot of a volume can be reverted, so its snapshots stay a single chain. - While a volume has no-copy snapshots, volume and Instance storage migration, Instance snapshots and reverting regular snapshots are refused, and the no-copy snapshots cannot be archived, copied or used to create volumes, templates or Instances. Co-Authored-By: Claude Opus 5.5 --- api/src/main/java/com/cloud/host/Host.java | 4 + .../cloud/agent/manager/AgentManagerImpl.java | 6 +- .../agent/manager/AgentManagerImplTest.java | 20 + .../KvmFileBasedNoCopySnapshotStrategy.java | 637 +++++++++++++++++ ...ngine-storage-snapshot-storage-context.xml | 3 + ...vmFileBasedNoCopySnapshotStrategyTest.java | 649 ++++++++++++++++++ .../resource/LibvirtComputingResource.java | 26 + .../wrapper/LibvirtReadyCommandWrapper.java | 1 + .../LibvirtComputingResourceTest.java | 48 ++ .../cloud/storage/VolumeApiServiceImpl.java | 4 + .../storage/snapshot/SnapshotManager.java | 36 + .../storage/snapshot/SnapshotManagerImpl.java | 43 +- .../cloud/template/TemplateManagerImpl.java | 3 + .../java/com/cloud/vm/UserVmManagerImpl.java | 14 + .../vm/snapshot/VMSnapshotManagerImpl.java | 8 + .../snapshot/SnapshotManagerImplTest.java | 75 ++ .../storage/snapshot/SnapshotManagerTest.java | 3 + .../template/TemplateManagerImplTest.java | 4 + .../com/cloud/vm/UserVmManagerImplTest.java | 4 + .../vm/snapshot/VMSnapshotManagerTest.java | 15 + 20 files changed, 1600 insertions(+), 3 deletions(-) create mode 100644 engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java create mode 100644 engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java diff --git a/api/src/main/java/com/cloud/host/Host.java b/api/src/main/java/com/cloud/host/Host.java index 3a0dc1c14d4a..0012127cac4f 100644 --- a/api/src/main/java/com/cloud/host/Host.java +++ b/api/src/main/java/com/cloud/host/Host.java @@ -56,6 +56,10 @@ public static String[] toStrings(Host.Type... types) { String HOST_UEFI_ENABLE = "host.uefi.enable"; String HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM = "host.kvm.diskonlyvmsnapshot.nvram"; + /** + * The KVM agent excludes the disks that are not being snapshotted from disk-only snapshots of running Instances, so a single volume can be snapshotted. + */ + String HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME = "host.kvm.diskonlysnapshot.singlevolume"; String HOST_VOLUME_ENCRYPTION = "host.volume.encryption"; String HOST_RBD_VOLUME_ENCRYPTION = "host.volume.encryption.rbd"; String HOST_INSTANCE_CONVERSION = "host.instance.conversion"; diff --git a/engine/orchestration/src/main/java/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/main/java/com/cloud/agent/manager/AgentManagerImpl.java index e6b547ef9dcf..90e579e7b377 100644 --- a/engine/orchestration/src/main/java/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/main/java/com/cloud/agent/manager/AgentManagerImpl.java @@ -812,6 +812,7 @@ protected AgentAttache notifyMonitorsOfConnection(final AgentAttache attache, fi } String uefiEnabled = detailsMap.get(Host.HOST_UEFI_ENABLE); String diskOnlyVmSnapshotNvramSupport = detailsMap.get(Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM); + String diskOnlySnapshotSingleVolumeSupport = detailsMap.get(Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME); String virtv2vVersion = detailsMap.get(Host.HOST_VIRTV2V_VERSION); String ovftoolVersion = detailsMap.get(Host.HOST_OVFTOOL_VERSION); String vddkSupport = detailsMap.get(Host.HOST_VDDK_SUPPORT); @@ -831,7 +832,7 @@ protected AgentAttache notifyMonitorsOfConnection(final AgentAttache attache, fi String qemuImgRbdSupport = detailsMap.get(Host.HOST_QEMU_RBD_SUPPORT); String vddkRbdDirectImportSupport = detailsMap.get(Host.HOST_VDDK_RBD_DIRECT_IMPORT_SUPPORT); logger.debug("Got HOST_UEFI_ENABLE [{}] for host [{}]:", uefiEnabled, host); - if (ObjectUtils.anyNotNull(uefiEnabled, diskOnlyVmSnapshotNvramSupport, virtv2vVersion, ovftoolVersion, vddkSupport, vddkLibDir, vddkVersion, + if (ObjectUtils.anyNotNull(uefiEnabled, diskOnlyVmSnapshotNvramSupport, diskOnlySnapshotSingleVolumeSupport, virtv2vVersion, ovftoolVersion, vddkSupport, vddkLibDir, vddkVersion, vlanFilteringEnabled, guestBridgeStpEnabled, vlanTrunkXmlSupported, vmwareCbtSupport, vmwareCbtInPlaceFinalizationSupport, vmwareCbtRbdSupport, qemuImgVersion, qemuNbdVersion, qemuIoVersion, virtV2vInPlaceVersion, virtv2vInPlaceSupport, qemuImgRbdSupport, vddkRbdDirectImportSupport)) { @@ -843,6 +844,9 @@ protected AgentAttache notifyMonitorsOfConnection(final AgentAttache attache, fi if (syncBooleanHostCapability(host, Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM, diskOnlyVmSnapshotNvramSupport)) { updateNeeded = true; } + if (syncBooleanHostCapability(host, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, diskOnlySnapshotSingleVolumeSupport)) { + updateNeeded = true; + } if (StringUtils.isNotBlank(virtv2vVersion) && !virtv2vVersion.equals(host.getDetails().get(Host.HOST_VIRTV2V_VERSION))) { host.getDetails().put(Host.HOST_VIRTV2V_VERSION, virtv2vVersion); updateNeeded = true; diff --git a/engine/orchestration/src/test/java/com/cloud/agent/manager/AgentManagerImplTest.java b/engine/orchestration/src/test/java/com/cloud/agent/manager/AgentManagerImplTest.java index 2377bbaefbc8..d69b71b9c5ea 100644 --- a/engine/orchestration/src/test/java/com/cloud/agent/manager/AgentManagerImplTest.java +++ b/engine/orchestration/src/test/java/com/cloud/agent/manager/AgentManagerImplTest.java @@ -121,6 +121,26 @@ public void testNotifyMonitorsOfConnectionClearsStaleNvramCapabilityOnReconnect( Mockito.verify(hostDao).saveDetails(host); } + @Test + public void testNotifyMonitorsOfConnectionStoresSingleVolumeDiskOnlySnapshotCapability() throws ConnectionException { + ReadyAnswer readyAnswer = Mockito.mock(ReadyAnswer.class); + host.setDetails(new HashMap<>()); + + Mockito.when(hostDao.findById(Mockito.anyLong())).thenReturn(host); + Mockito.doNothing().when(hostDao).loadDetails(host); + Mockito.doNothing().when(storagePoolMonitor).processConnect(Mockito.eq(host), Mockito.eq(cmds[0]), Mockito.eq(false)); + Mockito.when(readyAnswer.getResult()).thenReturn(true); + Mockito.when(readyAnswer.getDetailsMap()).thenReturn(Map.of(Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, Boolean.TRUE.toString())); + Mockito.doReturn(readyAnswer).when(mgr).easySend(Mockito.anyLong(), Mockito.any(ReadyCommand.class)); + Mockito.doReturn(true).when(mgr).agentStatusTransitTo(Mockito.eq(host), Mockito.eq(Status.Event.Ready), Mockito.anyLong()); + + final AgentAttache agentAttache = mgr.notifyMonitorsOfConnection(attache, cmds, false); + + Assert.assertTrue(agentAttache.isReady()); + Assert.assertEquals(Boolean.TRUE.toString(), host.getDetails().get(Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME)); + Mockito.verify(hostDao).saveDetails(host); + } + @Test public void testGetTimeoutWithPositiveTimeout() { Commands commands = Mockito.mock(Commands.class); diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java new file mode 100644 index 000000000000..b4725e9617ed --- /dev/null +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -0,0 +1,637 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.snapshot; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import javax.inject.Inject; + +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.storage.command.CreateObjectAnswer; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.to.DeltaMergeTreeTO; +import org.apache.cloudstack.storage.to.SnapshotObjectTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.apache.commons.collections.CollectionUtils; + +import com.cloud.agent.AgentManager; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.VMSnapshotTO; +import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotAnswer; +import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.MergeDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; +import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.to.DataTO; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.DetailVO; +import com.cloud.host.Host; +import com.cloud.host.dao.HostDetailsDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.storage.CreateSnapshotPayload; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.Storage; +import com.cloud.storage.Volume; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotZoneDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.snapshot.SnapshotManager; +import com.cloud.utils.Pair; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.fsm.NoTransitionException; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.snapshot.VMSnapshot; +import com.cloud.vm.snapshot.dao.VMSnapshotDao; + +/** + * Volume snapshots of KVM QCOW2 volumes on file-based primary storage that do not copy the volume (see {@link SnapshotManager#KvmFileBasedVolumeSnapshotNoCopy}). + *

+ * Taking a snapshot freezes the current file of the volume, which becomes the snapshot, and moves the volume onto a new, empty QCOW2 delta on top of it. Reverting + * the snapshot replaces the current delta of the volume with a new, empty delta on top of the snapshot. Deleting the snapshot merges its child (the next snapshot of + * the volume, or the current delta of the volume) into it. The agent side reuses the commands of the KVM disk-only Instance snapshots + * ({@link org.apache.cloudstack.storage.vmsnapshot.KvmFileBasedStorageVmSnapshotStrategy}) for a single volume. + *

+ * The snapshots of a volume always form a single chain ordered by creation: only the most recent snapshot of a volume can be reverted, so no tree of deltas is ever + * created. + */ +public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { + + protected static final Set SUPPORTED_POOL_TYPES = Set.of(Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint, + Storage.StoragePoolType.Filesystem); + + @Inject + protected SnapshotDao snapshotDao; + + @Inject + protected SnapshotDataStoreDao snapshotStoreDao; + + @Inject + protected SnapshotDetailsDao snapshotDetailsDao; + + @Inject + protected SnapshotZoneDao snapshotZoneDao; + + @Inject + protected SnapshotDataFactory snapshotDataFactory; + + @Inject + protected VolumeDao volumeDao; + + @Inject + protected VolumeDataFactory volumeDataFactory; + + @Inject + protected VMInstanceDao vmInstanceDao; + + @Inject + protected VMSnapshotDao vmSnapshotDao; + + @Inject + protected PrimaryDataStoreDao storagePoolDao; + + @Inject + protected SnapshotManager snapshotManager; + + @Inject + protected EndPointSelector endPointSelector; + + @Inject + protected AgentManager agentManager; + + @Inject + protected HostDetailsDao hostDetailsDao; + + @Override + public StrategyPriority canHandle(Snapshot snapshot, Long zoneId, SnapshotOperation op) { + if (SnapshotOperation.TAKE.equals(op)) { + return canTakeNoCopySnapshot(snapshot) ? StrategyPriority.HIGHEST : StrategyPriority.CANT_HANDLE; + } + + if (!snapshotManager.isKvmFileBasedNoCopySnapshot(snapshot.getId())) { + return StrategyPriority.CANT_HANDLE; + } + + if (SnapshotOperation.COPY.equals(op)) { + logger.debug("Snapshot [{}] is a KVM file-based no-copy snapshot, which cannot be copied.", snapshot.getUuid()); + return StrategyPriority.CANT_HANDLE; + } + + // A no-copy snapshot is part of the backing chain of its volume: no other strategy may delete, revert or back it up. + return StrategyPriority.HIGHEST; + } + + /** + * Checks whether the snapshot can be taken as a KVM file-based no-copy snapshot. Any other snapshot is left to the other strategies, so the behaviour only + * changes for the storage pools where {@link SnapshotManager#KvmFileBasedVolumeSnapshotNoCopy} is enabled. + */ + protected boolean canTakeNoCopySnapshot(Snapshot snapshot) { + SnapshotVO snapshotVO = snapshotDao.findById(snapshot.getId()); + if (snapshotVO == null || Snapshot.Type.GROUP.name().equals(snapshotVO.getTypeDescription())) { + return false; + } + + if (!Hypervisor.HypervisorType.KVM.equals(snapshot.getHypervisorType())) { + return false; + } + + VolumeVO volume = volumeDao.findById(snapshot.getVolumeId()); + if (volume == null || volume.getPoolId() == null) { + return false; + } + + StoragePoolVO storagePool = storagePoolDao.findById(volume.getPoolId()); + if (storagePool == null || storagePool.isManaged() || !SUPPORTED_POOL_TYPES.contains(storagePool.getPoolType())) { + return false; + } + + if (!isNoCopySnapshotEnabledForStoragePool(storagePool.getId())) { + return false; + } + + String cantHandleLog = String.format("KVM file-based no-copy snapshot strategy cannot take snapshot [%s] of volume [%s], although [%s] is enabled for storage pool [%s],", + snapshot.getUuid(), volume.getUuid(), SnapshotManager.KvmFileBasedVolumeSnapshotNoCopy.key(), storagePool.getUuid()); + + if (!Storage.ImageFormat.QCOW2.equals(volume.getFormat())) { + logger.debug("{} as the volume format is [{}] and not QCOW2.", cantHandleLog, volume.getFormat()); + return false; + } + + if (volume.getPassphraseId() != null || volume.getKmsKeyId() != null) { + logger.debug("{} as the volume is encrypted.", cantHandleLog); + return false; + } + + if (snapshotManager.isBackupSnapshotToSecondaryForZone(volume.getDataCenterId())) { + logger.debug("{} as snapshots are backed up to secondary storage in the zone of the volume ([{}] is true).", cantHandleLog, + SnapshotInfo.BackupSnapshotAfterTakingSnapshot.key()); + return false; + } + + if (!isPayloadSupported(snapshot, cantHandleLog)) { + return false; + } + + if (volume.getInstanceId() == null) { + return true; + } + + VMInstanceVO vm = vmInstanceDao.findById(volume.getInstanceId()); + if (vm == null) { + return true; + } + + if (!VirtualMachine.State.Running.equals(vm.getState()) && !VirtualMachine.State.Stopped.equals(vm.getState())) { + logger.debug("{} as its Instance [{}] is in state [{}] and not Running or Stopped.", cantHandleLog, vm.getUuid(), vm.getState()); + return false; + } + + if (CollectionUtils.isNotEmpty(vmSnapshotDao.findByVm(vm.getId()))) { + logger.debug("{} as its Instance [{}] has Instance snapshots, which also change the backing chain of the volume.", cantHandleLog, vm.getUuid()); + return false; + } + + if (vm.getBackupOfferingId() != null) { + logger.debug("{} as its Instance [{}] has a backup offering, whose backups may also change the backing chain of the volume.", cantHandleLog, vm.getUuid()); + return false; + } + + if (VirtualMachine.State.Running.equals(vm.getState()) && !hostSupportsSingleVolumeDiskOnlySnapshots(vm.getHostId())) { + logger.info("{} as the host [{}] of its running Instance [{}] does not advertise [{}]; the KVM agent must be upgraded. Taking a regular snapshot instead.", + cantHandleLog, vm.getHostId(), vm.getUuid(), Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME); + return false; + } + + return true; + } + + /** + * Older KVM agents also take an external snapshot of the disks that are not listed in the snapshot XML, which would move the other volumes of the Instance onto + * files unknown to CloudStack. + */ + protected boolean hostSupportsSingleVolumeDiskOnlySnapshots(Long hostId) { + if (hostId == null) { + return false; + } + DetailVO capability = hostDetailsDao.findDetail(hostId, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME); + return capability != null && Boolean.parseBoolean(capability.getValue()); + } + + protected boolean isNoCopySnapshotEnabledForStoragePool(long storagePoolId) { + return Boolean.TRUE.equals(SnapshotManager.KvmFileBasedVolumeSnapshotNoCopy.valueIn(storagePoolId)); + } + + protected boolean isPayloadSupported(Snapshot snapshot, String cantHandleLog) { + if (!(snapshot instanceof SnapshotInfo) || !(((SnapshotInfo) snapshot).getPayload() instanceof CreateSnapshotPayload)) { + logger.debug("{} as there is no snapshot payload to validate.", cantHandleLog); + return false; + } + + CreateSnapshotPayload payload = (CreateSnapshotPayload) ((SnapshotInfo) snapshot).getPayload(); + if (payload.isKvmIncrementalSnapshot()) { + logger.debug("{} as KVM incremental snapshots are enabled ([{}] is true).", cantHandleLog, SnapshotManager.kvmIncrementalSnapshot.key()); + return false; + } + + if (CollectionUtils.isNotEmpty(payload.getZoneIds()) || CollectionUtils.isNotEmpty(payload.getStoragePoolIds())) { + logger.debug("{} as it would have to be copied to other zones or storage pools.", cantHandleLog); + return false; + } + + if (payload.getQuiescevm()) { + logger.debug("{} as quiescing the Instance was requested.", cantHandleLog); + return false; + } + return true; + } + + @Override + public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { + SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId()); + if (snapshotVO == null) { + throw new CloudRuntimeException(String.format("Failed to get lock on snapshot [%s].", snapshot.getUuid())); + } + + try { + return takeSnapshotInternal(snapshot); + } finally { + snapshotDao.releaseFromLockTable(snapshot.getId()); + } + } + + protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { + VolumeInfo volumeInfo = snapshot.getBaseVolume(); + VMInstanceVO vm = getAttachedVm(volumeInfo); + boolean vmRunning = isVmRunning(vm); + + logger.info("Taking KVM file-based no-copy snapshot [{}] of volume [{}].", snapshot.getUuid(), volumeInfo.getUuid()); + + volumeInfo.stateTransit(Volume.Event.SnapshotRequested); + + SnapshotObject snapshotOnPrimary = null; + boolean succeeded = false; + try { + snapshotOnPrimary = createSnapshotOnPrimary(snapshot); + VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); + String oldVolumePath = volumeTO.getPath(); + String newVolumePath = UUID.randomUUID().toString(); + + VMSnapshotTO target = new VMSnapshotTO(snapshot.getId(), snapshot.getUuid(), VMSnapshot.Type.Disk, null, null, false, null, false); + CreateDiskOnlyVmSnapshotCommand command = new CreateDiskOnlyVmSnapshotCommand(vm != null ? vm.getInstanceName() : null, vm != null ? vm.getUuid() : null, target, + List.of(new Pair<>(volumeTO, newVolumePath)), null, vmRunning ? VirtualMachine.State.Running : VirtualMachine.State.Stopped, false); + + Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + if (!(answer instanceof CreateDiskOnlyVmSnapshotAnswer) || !answer.getResult()) { + throw new CloudRuntimeException(String.format("Failed to take KVM file-based no-copy snapshot [%s] of volume [%s] due to [%s].", snapshot.getUuid(), + volumeInfo.getUuid(), getAnswerDetails(answer))); + } + + // The volume is now on the new delta: record it first, so that a later failure can never leave the volume pointing to the frozen file. If updating the + // snapshot metadata fails afterwards, the snapshot ends in Error and the frozen file simply stays in the backing chain of the volume. + VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); + volumeVO.setPath(newVolumePath); + volumeDao.update(volumeVO.getId(), volumeVO); + + Long frozenFileSize = ((CreateDiskOnlyVmSnapshotAnswer) answer).getMapVolumeToSnapshotSize().get(volumeInfo.getUuid()); + + SnapshotObjectTO snapshotTO = new SnapshotObjectTO(); + snapshotTO.setPath(oldVolumePath); + snapshotTO.setPhysicalSize(frozenFileSize); + snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.OperationSucceeded, new CreateObjectAnswer(snapshotTO)); + snapshotOnPrimary.processEvent(Snapshot.Event.OperationSucceeded); + + snapshotDetailsDao.addDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, Boolean.TRUE.toString(), false); + + logger.info("Took KVM file-based no-copy snapshot [{}] of volume [{}]: the snapshot is [{}] and the volume is now on [{}].", snapshot.getUuid(), + volumeInfo.getUuid(), oldVolumePath, newVolumePath); + succeeded = true; + return snapshotOnPrimary; + } catch (NoTransitionException e) { + throw new CloudRuntimeException(String.format("Failed to update the state of snapshot [%s].", snapshot.getUuid()), e); + } finally { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + if (!succeeded && snapshotOnPrimary != null) { + markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); + } + } + } + + protected SnapshotObject createSnapshotOnPrimary(SnapshotInfo snapshot) { + try { + SnapshotObject snapshotOnPrimary = (SnapshotObject) snapshot.getDataStore().create(snapshot); + snapshotOnPrimary.processEvent(Snapshot.Event.CreateRequested); + snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.CreateOnlyRequested); + return snapshotOnPrimary; + } catch (NoTransitionException e) { + throw new CloudRuntimeException(String.format("Failed to update the state of snapshot [%s].", snapshot.getUuid()), e); + } + } + + protected void markSnapshotOnPrimaryAsFailed(SnapshotObject snapshotOnPrimary) { + try { + snapshotOnPrimary.processEvent(Snapshot.Event.OperationFailed); + } catch (NoTransitionException e) { + logger.warn("Failed to mark snapshot [{}] as failed.", snapshotOnPrimary.getUuid(), e); + } + snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + + @Override + public boolean revertSnapshot(SnapshotInfo snapshot) { + SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId()); + if (snapshotVO == null) { + throw new CloudRuntimeException(String.format("Failed to get lock on snapshot [%s].", snapshot.getUuid())); + } + + try { + return revertSnapshotInternal(snapshotVO); + } finally { + snapshotDao.releaseFromLockTable(snapshot.getId()); + } + } + + protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { + VolumeInfo volumeInfo = volumeDataFactory.getVolume(snapshotVO.getVolumeId()); + if (volumeInfo == null) { + throw new CloudRuntimeException(String.format("Unable to find the volume of snapshot [%s].", snapshotVO.getUuid())); + } + + List chain = listNoCopySnapshotsOfVolume(volumeInfo.getId()); + if (chain.isEmpty() || chain.get(chain.size() - 1).getId() != snapshotVO.getId()) { + throw new InvalidParameterValueException(String.format("Only the most recent KVM file-based no-copy snapshot of volume [%s] can be reverted. Delete the snapshots " + + "taken after snapshot [%s] before reverting it.", volumeInfo.getUuid(), snapshotVO.getUuid())); + } + + VMInstanceVO vm = getAttachedVm(volumeInfo); + if (isVmRunning(vm)) { + throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s].", vm.getUuid(), + volumeInfo.getUuid(), snapshotVO.getUuid())); + } + + logger.info("Reverting volume [{}] to KVM file-based no-copy snapshot [{}].", volumeInfo.getUuid(), snapshotVO.getUuid()); + + SnapshotObjectTO snapshotTO = getSnapshotObjectTO(snapshotVO, volumeInfo); + volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested); + + boolean succeeded = false; + try { + RevertDiskOnlyVmSnapshotCommand command = new RevertDiskOnlyVmSnapshotCommand(List.of(snapshotTO), vm != null ? vm.getInstanceName() : null, + vm != null ? vm.getUuid() : null, false, null); + + Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + if (!(answer instanceof RevertDiskOnlyVmSnapshotAnswer) || !answer.getResult() || + CollectionUtils.isEmpty(((RevertDiskOnlyVmSnapshotAnswer) answer).getVolumeObjectTos())) { + throw new CloudRuntimeException(String.format("Failed to revert volume [%s] to snapshot [%s] due to [%s].", volumeInfo.getUuid(), snapshotVO.getUuid(), + getAnswerDetails(answer))); + } + + String newVolumePath = ((RevertDiskOnlyVmSnapshotAnswer) answer).getVolumeObjectTos().get(0).getPath(); + VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); + volumeVO.setPath(newVolumePath); + // The size of the volume and the primary storage resource count are updated by SnapshotManagerImpl#revertSnapshot. + volumeDao.update(volumeVO.getId(), volumeVO); + + logger.info("Reverted volume [{}] to KVM file-based no-copy snapshot [{}]: the volume is now on [{}].", volumeInfo.getUuid(), snapshotVO.getUuid(), newVolumePath); + succeeded = true; + return true; + } finally { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + } + } + + @Override + public boolean deleteSnapshot(Long snapshotId, Long zoneId) { + SnapshotVO snapshotVO = snapshotDao.findById(snapshotId); + if (snapshotVO == null || Snapshot.State.Destroyed.equals(snapshotVO.getState())) { + return true; + } + + if (zoneId != null && zoneId != snapshotVO.getDataCenterId()) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] is a KVM file-based no-copy snapshot, which only exists on the primary storage of its volume " + + "in zone [%s].", snapshotVO.getUuid(), snapshotVO.getDataCenterId())); + } + + switch (snapshotVO.getState()) { + case Allocated: + snapshotDao.remove(snapshotId); + return true; + case Error: + removeSnapshotMetadata(snapshotVO); + return true; + case CreatedOnPrimary: + case BackedUp: + break; + default: + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while it is in state [%s].", snapshotVO.getUuid(), snapshotVO.getState())); + } + + snapshotVO = snapshotDao.acquireInLockTable(snapshotId); + if (snapshotVO == null) { + throw new CloudRuntimeException(String.format("Failed to get lock on snapshot [%s].", snapshotId)); + } + + try { + return deleteSnapshotInternal(snapshotVO); + } finally { + snapshotDao.releaseFromLockTable(snapshotId); + } + } + + protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { + VolumeVO volumeVO = volumeDao.findByIdIncludingRemoved(snapshotVO.getVolumeId()); + SnapshotDataStoreVO snapshotStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); + + if (volumeVO == null || volumeVO.getRemoved() != null || snapshotStoreRef == null) { + logger.debug("The volume of KVM file-based no-copy snapshot [{}] was removed, together with its backing chain; only the snapshot metadata will be removed.", + snapshotVO.getUuid()); + removeSnapshotMetadata(snapshotVO); + return true; + } + + VolumeInfo volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); + if (!Volume.State.Ready.equals(volumeInfo.getState())) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while its volume [%s] is in state [%s].", snapshotVO.getUuid(), + volumeVO.getUuid(), volumeInfo.getState())); + } + + VMInstanceVO vm = getAttachedVm(volumeInfo); + if (vm != null && !VirtualMachine.State.Running.equals(vm.getState()) && !VirtualMachine.State.Stopped.equals(vm.getState())) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while the Instance [%s] of its volume is in state [%s].", + snapshotVO.getUuid(), vm.getUuid(), vm.getState())); + } + boolean vmRunning = isVmRunning(vm); + + List chain = listNoCopySnapshotsOfVolume(volumeVO.getId()); + int index = chain.stream().map(SnapshotVO::getId).collect(Collectors.toList()).indexOf(snapshotVO.getId()); + if (index < 0) { + throw new CloudRuntimeException(String.format("Unable to find snapshot [%s] in the backing chain of volume [%s].", snapshotVO.getUuid(), volumeVO.getUuid())); + } + + VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); + SnapshotObjectTO parentTO = getSnapshotObjectTO(snapshotVO, volumeInfo); + SnapshotVO childSnapshot = index + 1 < chain.size() ? chain.get(index + 1) : null; + DeltaMergeTreeTO deltaMergeTree = createDeltaMergeTree(chain, index, volumeInfo, volumeTO, parentTO); + + logger.info("Deleting KVM file-based no-copy snapshot [{}] of volume [{}] by merging [{}] into it.", snapshotVO.getUuid(), volumeVO.getUuid(), + deltaMergeTree.getChild().getPath()); + + volumeInfo.stateTransit(Volume.Event.SnapshotRequested); + boolean succeeded = false; + try { + MergeDiskOnlyVmSnapshotCommand command = new MergeDiskOnlyVmSnapshotCommand(List.of(deltaMergeTree), vmRunning, vm != null ? vm.getInstanceName() : null); + Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + if (answer == null || !answer.getResult()) { + throw new CloudRuntimeException(String.format("Failed to delete KVM file-based no-copy snapshot [%s] of volume [%s] due to [%s].", snapshotVO.getUuid(), + volumeVO.getUuid(), getAnswerDetails(answer))); + } + + updateMetadataAfterMerge(snapshotVO, snapshotStoreRef, childSnapshot, volumeVO); + succeeded = true; + return true; + } finally { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + } + } + + /** + * The child of the snapshot is the next snapshot of the volume or, for the most recent snapshot, the current delta of the volume. The child is committed into the + * snapshot, and the file on top of the child (the grandchild) is rebased onto the snapshot. + */ + protected DeltaMergeTreeTO createDeltaMergeTree(List chain, int index, VolumeInfo volumeInfo, VolumeObjectTO volumeTO, SnapshotObjectTO parentTO) { + if (index + 1 >= chain.size()) { + return new DeltaMergeTreeTO(volumeTO, parentTO, volumeTO, new ArrayList<>()); + } + + DataTO childTO = getSnapshotObjectTO(chain.get(index + 1), volumeInfo); + List grandChildren = new ArrayList<>(); + grandChildren.add(index + 2 < chain.size() ? getSnapshotObjectTO(chain.get(index + 2), volumeInfo) : volumeTO); + return new DeltaMergeTreeTO(volumeTO, parentTO, childTO, grandChildren); + } + + /** + * After the merge, the file of the deleted snapshot holds the data of its child: the child (the next snapshot, or the volume itself) now points to that file. + */ + protected void updateMetadataAfterMerge(SnapshotVO snapshotVO, SnapshotDataStoreVO snapshotStoreRef, SnapshotVO childSnapshot, VolumeVO volumeVO) { + String mergedPath = snapshotStoreRef.getInstallPath(); + if (childSnapshot == null) { + logger.debug("Volume [{}] is now on [{}].", volumeVO.getUuid(), mergedPath); + volumeVO.setPath(mergedPath); + volumeDao.update(volumeVO.getId(), volumeVO); + } else { + SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(childSnapshot.getId(), DataStoreRole.Primary); + logger.debug("Snapshot [{}] is now on [{}].", childSnapshot.getUuid(), mergedPath); + childStoreRef.setInstallPath(mergedPath); + childStoreRef.setPhysicalSize(childStoreRef.getPhysicalSize() + snapshotStoreRef.getPhysicalSize()); + snapshotStoreDao.update(childStoreRef.getId(), childStoreRef); + } + removeSnapshotMetadata(snapshotVO); + } + + protected void removeSnapshotMetadata(SnapshotVO snapshotVO) { + List storeRefs = snapshotStoreDao.findBySnapshotId(snapshotVO.getId()); + for (SnapshotDataStoreVO storeRef : storeRefs) { + snapshotStoreDao.expunge(storeRef.getId()); + } + snapshotZoneDao.removeSnapshotFromZones(snapshotVO.getId()); + snapshotVO.setState(Snapshot.State.Destroyed); + snapshotDao.update(snapshotVO.getId(), snapshotVO); + } + + @Override + public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) { + throw new CloudRuntimeException(String.format("Snapshot [%s] is a KVM file-based no-copy snapshot, which cannot be backed up to secondary storage.", + snapshot.getUuid())); + } + + @Override + public void postSnapshotCreation(SnapshotInfo snapshot) { + } + + /** + * @return the KVM file-based no-copy snapshots of the volume that are part of its backing chain, from the oldest (the bottom of the chain) to the most recent. + */ + protected List listNoCopySnapshotsOfVolume(long volumeId) { + return snapshotDao.listByVolumeId(volumeId).stream() + .filter(snapshot -> Snapshot.State.BackedUp.equals(snapshot.getState()) || Snapshot.State.CreatedOnPrimary.equals(snapshot.getState())) + .filter(snapshot -> snapshotManager.isKvmFileBasedNoCopySnapshot(snapshot.getId())) + .sorted(Comparator.comparingLong(SnapshotVO::getId)) + .collect(Collectors.toList()); + } + + protected SnapshotObjectTO getSnapshotObjectTO(SnapshotVO snapshotVO, VolumeInfo volumeInfo) { + SnapshotInfo snapshotInfo = snapshotDataFactory.getSnapshot(snapshotVO.getId(), volumeInfo.getPoolId(), DataStoreRole.Primary); + if (snapshotInfo == null) { + throw new CloudRuntimeException(String.format("Unable to find snapshot [%s] on the primary storage of volume [%s].", snapshotVO.getUuid(), volumeInfo.getUuid())); + } + SnapshotObjectTO snapshotObjectTO = (SnapshotObjectTO) snapshotInfo.getTO(); + snapshotObjectTO.setVolume((VolumeObjectTO) volumeInfo.getTO()); + return snapshotObjectTO; + } + + protected VMInstanceVO getAttachedVm(VolumeInfo volumeInfo) { + return volumeInfo.getInstanceId() == null ? null : vmInstanceDao.findById(volumeInfo.getInstanceId()); + } + + protected boolean isVmRunning(VMInstanceVO vm) { + return vm != null && VirtualMachine.State.Running.equals(vm.getState()); + } + + /** + * A running Instance is snapshotted and merged by the host it runs on; otherwise, any host with access to the storage pool of the volume is used. + */ + protected long getHostIdForOperation(VolumeInfo volumeInfo, VMInstanceVO vm) { + if (isVmRunning(vm) && vm.getHostId() != null) { + return vm.getHostId(); + } + + EndPoint endPoint = endPointSelector.select(volumeInfo); + if (endPoint == null) { + throw new CloudRuntimeException(String.format("Unable to find a host with access to the storage pool of volume [%s].", volumeInfo.getUuid())); + } + return endPoint.getId(); + } + + protected Answer sendToHost(long hostId, com.cloud.agent.api.Command command) { + return agentManager.easySend(hostId, command); + } + + protected String getAnswerDetails(Answer answer) { + return answer == null ? "no answer from the host" : answer.getDetails(); + } +} diff --git a/engine/storage/snapshot/src/main/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml b/engine/storage/snapshot/src/main/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml index 32ac6e9fc8b7..97632e01e14b 100644 --- a/engine/storage/snapshot/src/main/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml +++ b/engine/storage/snapshot/src/main/resources/META-INF/cloudstack/storage/spring-engine-storage-snapshot-storage-context.xml @@ -39,6 +39,9 @@ + + diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java new file mode 100644 index 000000000000..381d47ad556d --- /dev/null +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -0,0 +1,649 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.storage.snapshot; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy.SnapshotOperation; +import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.storage.command.CreateObjectAnswer; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.to.DeltaMergeTreeTO; +import org.apache.cloudstack.storage.to.SnapshotObjectTO; +import org.apache.cloudstack.storage.to.VolumeObjectTO; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.Command; +import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotAnswer; +import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.MergeDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; +import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.DetailVO; +import com.cloud.host.Host; +import com.cloud.host.dao.HostDetailsDao; +import com.cloud.hypervisor.Hypervisor; +import com.cloud.storage.CreateSnapshotPayload; +import com.cloud.storage.DataStoreRole; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.Storage; +import com.cloud.storage.Volume; +import com.cloud.storage.VolumeVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotZoneDao; +import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.snapshot.SnapshotManager; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.vm.snapshot.VMSnapshotVO; +import com.cloud.vm.snapshot.dao.VMSnapshotDao; + +public class KvmFileBasedNoCopySnapshotStrategyTest { + + private static final long SNAPSHOT_ID = 10L; + private static final long VOLUME_ID = 20L; + private static final long POOL_ID = 30L; + private static final long VM_ID = 40L; + private static final long HOST_ID = 50L; + private static final long ZONE_ID = 60L; + private static final String VOLUME_UUID = "volume-uuid"; + private static final String VOLUME_PATH = "current-delta"; + + private KvmFileBasedNoCopySnapshotStrategy strategy; + private SnapshotDao snapshotDao; + private SnapshotDataStoreDao snapshotStoreDao; + private SnapshotDetailsDao snapshotDetailsDao; + private SnapshotDataFactory snapshotDataFactory; + private VolumeDao volumeDao; + private VolumeDataFactory volumeDataFactory; + private VMInstanceDao vmInstanceDao; + private VMSnapshotDao vmSnapshotDao; + private PrimaryDataStoreDao storagePoolDao; + private SnapshotManager snapshotManager; + private HostDetailsDao hostDetailsDao; + + private SnapshotInfo snapshotInfo; + private SnapshotVO snapshotVO; + private VolumeVO volumeVO; + private VolumeInfo volumeInfo; + private VolumeObjectTO volumeTO; + private StoragePoolVO storagePool; + private CreateSnapshotPayload payload; + private VMInstanceVO vm; + + @Before + public void setup() { + strategy = Mockito.spy(new KvmFileBasedNoCopySnapshotStrategy()); + snapshotDao = mock(SnapshotDao.class); + snapshotStoreDao = mock(SnapshotDataStoreDao.class); + snapshotDetailsDao = mock(SnapshotDetailsDao.class); + snapshotDataFactory = mock(SnapshotDataFactory.class); + volumeDao = mock(VolumeDao.class); + volumeDataFactory = mock(VolumeDataFactory.class); + vmInstanceDao = mock(VMInstanceDao.class); + vmSnapshotDao = mock(VMSnapshotDao.class); + storagePoolDao = mock(PrimaryDataStoreDao.class); + snapshotManager = mock(SnapshotManager.class); + + strategy.snapshotDao = snapshotDao; + strategy.snapshotStoreDao = snapshotStoreDao; + strategy.snapshotDetailsDao = snapshotDetailsDao; + strategy.snapshotZoneDao = mock(SnapshotZoneDao.class); + strategy.snapshotDataFactory = snapshotDataFactory; + strategy.volumeDao = volumeDao; + strategy.volumeDataFactory = volumeDataFactory; + strategy.vmInstanceDao = vmInstanceDao; + strategy.vmSnapshotDao = vmSnapshotDao; + strategy.storagePoolDao = storagePoolDao; + strategy.snapshotManager = snapshotManager; + + snapshotVO = mockSnapshotVO(SNAPSHOT_ID, Snapshot.State.BackedUp); + when(snapshotVO.getTypeDescription()).thenReturn(Snapshot.Type.MANUAL.name()); + when(snapshotDao.acquireInLockTable(SNAPSHOT_ID)).thenReturn(snapshotVO); + + payload = mock(CreateSnapshotPayload.class); + snapshotInfo = mock(SnapshotInfo.class); + when(snapshotInfo.getId()).thenReturn(SNAPSHOT_ID); + when(snapshotInfo.getUuid()).thenReturn("snapshot-uuid"); + when(snapshotInfo.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshotInfo.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(snapshotInfo.getPayload()).thenReturn(payload); + + volumeVO = mock(VolumeVO.class); + when(volumeVO.getId()).thenReturn(VOLUME_ID); + when(volumeVO.getUuid()).thenReturn(VOLUME_UUID); + when(volumeVO.getPoolId()).thenReturn(POOL_ID); + when(volumeVO.getDataCenterId()).thenReturn(ZONE_ID); + when(volumeVO.getFormat()).thenReturn(Storage.ImageFormat.QCOW2); + when(volumeVO.getPassphraseId()).thenReturn(null); + when(volumeVO.getKmsKeyId()).thenReturn(null); + when(volumeVO.getInstanceId()).thenReturn(null); + when(volumeDao.findById(VOLUME_ID)).thenReturn(volumeVO); + when(volumeDao.findByIdIncludingRemoved(VOLUME_ID)).thenReturn(volumeVO); + + storagePool = mock(StoragePoolVO.class); + when(storagePool.getId()).thenReturn(POOL_ID); + when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); + when(storagePoolDao.findById(POOL_ID)).thenReturn(storagePool); + doReturn(true).when(strategy).isNoCopySnapshotEnabledForStoragePool(POOL_ID); + + volumeTO = new VolumeObjectTO(); + volumeTO.setPath(VOLUME_PATH); + volumeTO.setUuid(VOLUME_UUID); + volumeInfo = mock(VolumeInfo.class); + when(volumeInfo.getId()).thenReturn(VOLUME_ID); + when(volumeInfo.getUuid()).thenReturn(VOLUME_UUID); + when(volumeInfo.getPoolId()).thenReturn(POOL_ID); + when(volumeInfo.getState()).thenReturn(Volume.State.Ready); + when(volumeInfo.getTO()).thenReturn(volumeTO); + when(volumeInfo.getInstanceId()).thenReturn(null); + when(snapshotInfo.getBaseVolume()).thenReturn(volumeInfo); + when(volumeDataFactory.getVolume(VOLUME_ID)).thenReturn(volumeInfo); + + vm = mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(VM_ID); + when(vm.getUuid()).thenReturn("vm-uuid"); + when(vm.getInstanceName()).thenReturn("i-2-40-VM"); + when(vm.getHostId()).thenReturn(HOST_ID); + when(vm.getState()).thenReturn(VirtualMachine.State.Running); + when(vm.getBackupOfferingId()).thenReturn(null); + when(vmInstanceDao.findById(VM_ID)).thenReturn(vm); + + doReturn(HOST_ID).when(strategy).getHostIdForOperation(any(), any()); + hostDetailsDao = mock(HostDetailsDao.class); + strategy.hostDetailsDao = hostDetailsDao; + when(hostDetailsDao.findDetail(HOST_ID, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME)).thenReturn(new DetailVO(HOST_ID, + Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, "true")); + } + + private SnapshotVO mockSnapshotVO(long id, Snapshot.State state) { + SnapshotVO snapshot = mock(SnapshotVO.class); + when(snapshot.getId()).thenReturn(id); + when(snapshot.getUuid()).thenReturn("snapshot-" + id); + when(snapshot.getVolumeId()).thenReturn(VOLUME_ID); + when(snapshot.getDataCenterId()).thenReturn(ZONE_ID); + when(snapshot.getState()).thenReturn(state); + when(snapshotDao.findById(id)).thenReturn(snapshot); + return snapshot; + } + + private void attachVolumeToVm() { + when(volumeVO.getInstanceId()).thenReturn(VM_ID); + when(volumeInfo.getInstanceId()).thenReturn(VM_ID); + } + + /** + * Mocks a chain of no-copy snapshots of the volume (oldest first) and returns them. + */ + private List mockChain(long... ids) { + List chain = new ArrayList<>(); + for (long id : ids) { + SnapshotVO snapshot = id == SNAPSHOT_ID ? snapshotVO : mockSnapshotVO(id, Snapshot.State.BackedUp); + when(snapshotManager.isKvmFileBasedNoCopySnapshot(id)).thenReturn(true); + + SnapshotObjectTO snapshotTO = new SnapshotObjectTO(); + snapshotTO.setPath("frozen-" + id); + SnapshotInfo info = mock(SnapshotInfo.class); + when(info.getTO()).thenReturn(snapshotTO); + when(snapshotDataFactory.getSnapshot(id, POOL_ID, DataStoreRole.Primary)).thenReturn(info); + + SnapshotDataStoreVO storeRef = mock(SnapshotDataStoreVO.class); + when(storeRef.getInstallPath()).thenReturn("frozen-" + id); + when(storeRef.getPhysicalSize()).thenReturn(100L); + when(snapshotStoreDao.findOneBySnapshotAndDatastoreRole(id, DataStoreRole.Primary)).thenReturn(storeRef); + chain.add(snapshot); + } + when(snapshotDao.listByVolumeId(VOLUME_ID)).thenReturn(chain); + return chain; + } + + // canHandle + + @Test + public void canHandleTakeEligibleDetachedVolume() { + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeEligibleRunningVm() { + attachVolumeToVm(); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeWhenDisabledForStoragePool() { + doReturn(false).when(strategy).isNoCopySnapshotEnabledForStoragePool(POOL_ID); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeNotKvm() { + when(snapshotInfo.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.VMware); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeGroupSnapshot() { + when(snapshotVO.getTypeDescription()).thenReturn(Snapshot.Type.GROUP.name()); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeUnsupportedPoolType() { + when(storagePool.getPoolType()).thenReturn(Storage.StoragePoolType.RBD); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeManagedPool() { + when(storagePool.isManaged()).thenReturn(true); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeRawVolume() { + when(volumeVO.getFormat()).thenReturn(Storage.ImageFormat.RAW); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeEncryptedVolume() { + when(volumeVO.getPassphraseId()).thenReturn(1L); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeWhenBackedUpToSecondary() { + when(snapshotManager.isBackupSnapshotToSecondaryForZone(ZONE_ID)).thenReturn(true); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeWithoutPayload() { + when(snapshotInfo.getPayload()).thenReturn(null); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeIncrementalSnapshot() { + when(payload.isKvmIncrementalSnapshot()).thenReturn(true); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeCopyToOtherZones() { + when(payload.getZoneIds()).thenReturn(List.of(2L)); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeQuiesce() { + when(payload.getQuiescevm()).thenReturn(true); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeVmWithVmSnapshots() { + attachVolumeToVm(); + when(vmSnapshotDao.findByVm(VM_ID)).thenReturn(List.of(mock(VMSnapshotVO.class))); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeVmWithBackupOffering() { + attachVolumeToVm(); + when(vm.getBackupOfferingId()).thenReturn(1L); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeVmMigrating() { + attachVolumeToVm(); + when(vm.getState()).thenReturn(VirtualMachine.State.Migrating); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeRunningVmOnHostWithoutSingleVolumeCapability() { + attachVolumeToVm(); + when(hostDetailsDao.findDetail(HOST_ID, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME)).thenReturn(null); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleTakeStoppedVmDoesNotNeedSingleVolumeCapability() { + attachVolumeToVm(); + when(vm.getState()).thenReturn(VirtualMachine.State.Stopped); + when(hostDetailsDao.findDetail(HOST_ID, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME)).thenReturn(null); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotInfo, null, SnapshotOperation.TAKE)); + } + + @Test + public void canHandleOtherOperationsOfNoCopySnapshot() { + when(snapshotManager.isKvmFileBasedNoCopySnapshot(SNAPSHOT_ID)).thenReturn(true); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotVO, null, SnapshotOperation.DELETE)); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotVO, ZONE_ID, SnapshotOperation.DELETE)); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotVO, null, SnapshotOperation.REVERT)); + assertEquals(StrategyPriority.HIGHEST, strategy.canHandle(snapshotVO, null, SnapshotOperation.BACKUP)); + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotVO, null, SnapshotOperation.COPY)); + } + + @Test + public void canHandleOtherOperationsOfRegularSnapshot() { + when(snapshotManager.isKvmFileBasedNoCopySnapshot(SNAPSHOT_ID)).thenReturn(false); + for (SnapshotOperation op : List.of(SnapshotOperation.DELETE, SnapshotOperation.REVERT, SnapshotOperation.BACKUP, SnapshotOperation.COPY)) { + assertEquals(StrategyPriority.CANT_HANDLE, strategy.canHandle(snapshotVO, null, op)); + } + } + + // take + + private SnapshotObject mockSnapshotOnPrimary() { + SnapshotObject snapshotOnPrimary = mock(SnapshotObject.class); + doReturn(snapshotOnPrimary).when(strategy).createSnapshotOnPrimary(snapshotInfo); + return snapshotOnPrimary; + } + + @Test + public void takeSnapshotOfRunningVmMovesVolumeOntoNewDelta() throws Exception { + attachVolumeToVm(); + SnapshotObject snapshotOnPrimary = mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Map.of(VOLUME_UUID, 1234L)); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + + assertSame(snapshotOnPrimary, strategy.takeSnapshot(snapshotInfo)); + + CreateDiskOnlyVmSnapshotCommand command = (CreateDiskOnlyVmSnapshotCommand) commandCaptor.getValue(); + assertEquals(VirtualMachine.State.Running, command.getVmState()); + assertEquals("i-2-40-VM", command.getVmName()); + assertEquals(1, command.getVolumeTosAndNewPaths().size()); + String newPath = command.getVolumeTosAndNewPaths().get(0).second(); + assertNotEquals(VOLUME_PATH, newPath); + assertTrue(!command.isUefiEnabled() && !command.getTarget().getQuiescevm()); + + verify(volumeVO).setPath(newPath); + verify(volumeDao).update(VOLUME_ID, volumeVO); + ArgumentCaptor answerCaptor = ArgumentCaptor.forClass(CreateObjectAnswer.class); + verify(snapshotOnPrimary).processEvent(eq(ObjectInDataStoreStateMachine.Event.OperationSucceeded), answerCaptor.capture()); + SnapshotObjectTO snapshotTO = (SnapshotObjectTO) answerCaptor.getValue().getData(); + assertEquals(VOLUME_PATH, snapshotTO.getPath()); + assertEquals(Long.valueOf(1234L), snapshotTO.getPhysicalSize()); + verify(snapshotOnPrimary).processEvent(Snapshot.Event.OperationSucceeded); + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, "true", false); + verify(volumeInfo).stateTransit(Volume.Event.SnapshotRequested); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); + } + + @Test + public void takeSnapshotOfDetachedVolumeUsesStoppedPath() { + mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Map.of(VOLUME_UUID, 1L)); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + + strategy.takeSnapshot(snapshotInfo); + + assertEquals(VirtualMachine.State.Stopped, ((CreateDiskOnlyVmSnapshotCommand) commandCaptor.getValue()).getVmState()); + } + + @Test + public void takeSnapshotFailureKeepsVolumePath() throws Exception { + SnapshotObject snapshotOnPrimary = mockSnapshotOnPrimary(); + Answer answer = new Answer(null, false, "qemu-img failed"); + doReturn(answer).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeVO, never()).setPath(any()); + verify(snapshotDetailsDao, never()).addDetail(anyLong(), any(), any(), Mockito.anyBoolean()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + verify(snapshotOnPrimary).processEvent(Snapshot.Event.OperationFailed); + verify(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); + } + + // revert + + @Test + public void revertLatestSnapshotPutsVolumeOnNewDelta() { + mockChain(5L, SNAPSHOT_ID); + RevertDiskOnlyVmSnapshotAnswer answer = mock(RevertDiskOnlyVmSnapshotAnswer.class); + VolumeObjectTO reverted = new VolumeObjectTO(); + reverted.setPath("new-delta"); + when(answer.getResult()).thenReturn(true); + when(answer.getVolumeObjectTos()).thenReturn(List.of(reverted)); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + + assertTrue(strategy.revertSnapshot(snapshotInfo)); + + RevertDiskOnlyVmSnapshotCommand command = (RevertDiskOnlyVmSnapshotCommand) commandCaptor.getValue(); + assertEquals(1, command.getSnapshotObjectTos().size()); + assertEquals("frozen-" + SNAPSHOT_ID, command.getSnapshotObjectTos().get(0).getPath()); + assertEquals(VOLUME_PATH, command.getSnapshotObjectTos().get(0).getVolume().getPath()); + verify(volumeVO).setPath("new-delta"); + verify(volumeInfo).stateTransit(Volume.Event.RevertSnapshotRequested); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void revertOlderSnapshotIsRefused() { + mockChain(SNAPSHOT_ID, 15L); + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); + } + + @Test + public void revertWithRunningVmIsRefused() { + mockChain(SNAPSHOT_ID); + attachVolumeToVm(); + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void revertFailureKeepsVolumePath() { + mockChain(SNAPSHOT_ID); + doReturn(new Answer(null, false, "failed")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(volumeVO, never()).setPath(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + // delete + + private MergeDiskOnlyVmSnapshotCommand deleteAndCaptureMerge() { + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(new Answer(null, true, null)).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + return (MergeDiskOnlyVmSnapshotCommand) commandCaptor.getValue(); + } + + @Test + public void deleteMostRecentSnapshotMergesVolumeDeltaIntoIt() { + attachVolumeToVm(); + mockChain(5L, SNAPSHOT_ID); + + MergeDiskOnlyVmSnapshotCommand command = deleteAndCaptureMerge(); + + assertTrue(command.isVmRunning()); + DeltaMergeTreeTO tree = command.getDeltaMergeTreeToList().get(0); + assertEquals("frozen-" + SNAPSHOT_ID, tree.getParent().getPath()); + assertSame(volumeTO, tree.getChild()); + assertTrue(tree.getGrandChildren().isEmpty()); + verify(volumeVO).setPath("frozen-" + SNAPSHOT_ID); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + verify(volumeInfo).stateTransit(Volume.Event.SnapshotRequested); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void deleteMiddleSnapshotMergesNextSnapshotIntoIt() { + List chain = mockChain(5L, SNAPSHOT_ID, 15L); + + MergeDiskOnlyVmSnapshotCommand command = deleteAndCaptureMerge(); + + assertTrue(!command.isVmRunning()); + DeltaMergeTreeTO tree = command.getDeltaMergeTreeToList().get(0); + assertEquals("frozen-" + SNAPSHOT_ID, tree.getParent().getPath()); + assertEquals("frozen-15", tree.getChild().getPath()); + assertEquals(1, tree.getGrandChildren().size()); + assertSame(volumeTO, tree.getGrandChildren().get(0)); + + SnapshotDataStoreVO childRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(chain.get(2).getId(), DataStoreRole.Primary); + verify(childRef).setInstallPath("frozen-" + SNAPSHOT_ID); + verify(childRef).setPhysicalSize(200L); + verify(volumeVO, never()).setPath(any()); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + } + + @Test + public void deleteOldestOfThreeSnapshotsRebasesThirdSnapshot() { + mockChain(SNAPSHOT_ID, 15L, 25L); + + DeltaMergeTreeTO tree = deleteAndCaptureMerge().getDeltaMergeTreeToList().get(0); + + assertEquals("frozen-15", tree.getChild().getPath()); + assertEquals("frozen-25", tree.getGrandChildren().get(0).getPath()); + } + + @Test + public void deleteFailureKeepsMetadata() { + mockChain(SNAPSHOT_ID); + doReturn(new Answer(null, false, "blockcommit failed")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(volumeVO, never()).setPath(any()); + verify(snapshotVO, never()).setState(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void deleteSnapshotOfRemovedVolumeOnlyRemovesMetadata() { + mockChain(SNAPSHOT_ID); + when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + } + + @Test + public void deleteSnapshotInErrorOnlyRemovesMetadata() { + when(snapshotVO.getState()).thenReturn(Snapshot.State.Error); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + } + + @Test + public void deleteSnapshotFromOtherZoneIsRefused() { + assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, ZONE_ID + 1)); + } + + @Test + public void deleteSnapshotWhileVolumeIsBusyIsRefused() { + mockChain(SNAPSHOT_ID); + when(volumeInfo.getState()).thenReturn(Volume.State.Migrating); + assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void deleteSnapshotWhileVmIsStartingIsRefused() { + mockChain(SNAPSHOT_ID); + attachVolumeToVm(); + when(vm.getState()).thenReturn(VirtualMachine.State.Starting); + assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void backupSnapshotIsRefused() { + assertThrows(CloudRuntimeException.class, () -> strategy.backupSnapshot(snapshotInfo)); + } + + @Test + public void getHostIdForRunningVmIsItsHost() { + Mockito.reset(strategy); + attachVolumeToVm(); + assertEquals(HOST_ID, strategy.getHostIdForOperation(volumeInfo, vm)); + } + + @Test + public void createSnapshotOnPrimaryRequestsCreation() throws Exception { + Mockito.reset(strategy); + DataStore dataStore = mock(DataStore.class); + SnapshotObject snapshotOnPrimary = mock(SnapshotObject.class); + when(snapshotInfo.getDataStore()).thenReturn(dataStore); + when(dataStore.create(snapshotInfo)).thenReturn(snapshotOnPrimary); + + assertSame(snapshotOnPrimary, strategy.createSnapshotOnPrimary(snapshotInfo)); + + verify(snapshotOnPrimary).processEvent(Snapshot.Event.CreateRequested); + verify(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.CreateOnlyRequested); + } +} 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 3756567c98b6..e776cb6233a1 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 @@ -20,6 +20,7 @@ import static com.cloud.host.Host.HOST_CDROM_MAX_COUNT; import static com.cloud.host.Host.HOST_CPU_MAX_SPEED_MHZ; import static com.cloud.host.Host.HOST_INSTANCE_CONVERSION; +import static com.cloud.host.Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME; import static com.cloud.host.Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM; import static com.cloud.host.Host.HOST_OVFTOOL_VERSION; import static com.cloud.host.Host.HOST_QEMU_RBD_SUPPORT; @@ -446,6 +447,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv "\n" + "\n"; + private static final String TAG_DISK_NO_SNAPSHOT = "\n"; + protected int qcow2DeltaMergeTimeout; private String modifyVlanPath; @@ -4475,6 +4478,7 @@ public StartupCommand[] initialize() { cmd.getHostDetails().putAll(getVersionStrings()); cmd.getHostDetails().put(KeyStoreUtils.SECURED, String.valueOf(isHostSecured()).toLowerCase()); cmd.getHostDetails().put(HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM, Boolean.TRUE.toString()); + cmd.getHostDetails().put(HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, Boolean.TRUE.toString()); cmd.setPool(pool); cmd.setCluster(clusterId); cmd.setGatewayIpAddress(localGateway); @@ -7689,24 +7693,46 @@ public int getFlagsToUseForRunningVmSnapshotCreation(boolean quiesceVm) { return flags; } + /** + * Builds the XML of a disk-only, external snapshot of the given volumes. Every other disk of the domain is explicitly excluded with + * snapshot='no': with VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, Libvirt takes an external snapshot of the disks that are not + * listed in the XML, which would move them onto new files that CloudStack does not know about. This matters when only some of the volumes of the + * domain are snapshotted (e.g. a single volume snapshot). + */ public Pair> createSnapshotXmlAndNewVolumePathMap(List> volumeTosAndNewPaths, List disks, String snapshotName) { StringBuilder stringBuilder = new StringBuilder(); Map volumeObjectToNewPathMap = new HashMap<>(); + Set snapshottedDiskLabels = new HashSet<>(); 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))); + snapshottedDiskLabels.add(diskdef.getDiskLabel()); long snapSize = getFileSize(diskdef.getDiskPath()); volumeObjectToNewPathMap.put(volumeObjectTOAndPath.first().getUuid(), snapSize); } + for (LibvirtVMDef.DiskDef disk : disks) { + if (isDiskToExcludeFromSnapshot(disk, snapshottedDiskLabels)) { + stringBuilder.append(String.format(TAG_DISK_NO_SNAPSHOT, disk.getDiskLabel())); + } + } + String snapshotXml = String.format(SNAPSHOT_XML, snapshotName, stringBuilder); return new Pair<>(snapshotXml, volumeObjectToNewPathMap); } + protected boolean isDiskToExcludeFromSnapshot(LibvirtVMDef.DiskDef disk, Set snapshottedDiskLabels) { + if (StringUtils.isBlank(disk.getDiskLabel()) || snapshottedDiskLabels.contains(disk.getDiskLabel())) { + return false; + } + DiskDef.DeviceType deviceType = disk.getDeviceType(); + return deviceType != DiskDef.DeviceType.CDROM && deviceType != DiskDef.DeviceType.FLOPPY; + } + public long getFileSize(String path) { return new File(path).length(); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java index 62fab3b40b46..dfb257b7e14f 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java @@ -44,6 +44,7 @@ public final class LibvirtReadyCommandWrapper extends CommandWrapper hostDetails = new HashMap(); hostDetails.put(Host.HOST_KVM_DISK_ONLY_VM_SNAPSHOT_NVRAM, Boolean.TRUE.toString()); + hostDetails.put(Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, Boolean.TRUE.toString()); if (hostSupportsUefi(libvirtComputingResource.isUbuntuOrDebianHost()) && libvirtComputingResource.isUefiPropertiesFileLoaded()) { hostDetails.put(Host.HOST_UEFI_ENABLE, Boolean.TRUE.toString()); 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 ac73a0190288..1c27277c1915 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 @@ -7773,4 +7773,52 @@ public void getEffectiveGuestBridgeNameTreatsBlankLabelAsNoLabel() { libvirtComputingResourceSpy.setGuestTrafficLabel(" "); Assert.assertEquals("cloudbr1", libvirtComputingResourceSpy.getEffectiveGuestBridgeName()); } + + private DiskDef mockDiskDefForSnapshot(String label, String path, DiskDef.DeviceType deviceType) { + DiskDef disk = Mockito.mock(DiskDef.class); + Mockito.lenient().when(disk.getDiskLabel()).thenReturn(label); + Mockito.lenient().when(disk.getDiskPath()).thenReturn(path); + Mockito.lenient().when(disk.getDeviceType()).thenReturn(deviceType); + return disk; + } + + @Test + public void createSnapshotXmlAndNewVolumePathMapExcludesTheOtherDisksOfTheDomain() { + VolumeObjectTO volume = new VolumeObjectTO(); + volume.setUuid("data-volume"); + volume.setPath("data-delta"); + List disks = List.of( + mockDiskDefForSnapshot("vda", "/mnt/pool/root-delta", DiskDef.DeviceType.DISK), + mockDiskDefForSnapshot("vdb", "/mnt/pool/data-delta", DiskDef.DeviceType.DISK), + mockDiskDefForSnapshot("vdc", "/mnt/pool/other-delta", null), + mockDiskDefForSnapshot("hdc", null, DiskDef.DeviceType.CDROM)); + + String xml = libvirtComputingResourceSpy.createSnapshotXmlAndNewVolumePathMap(List.of(new Pair<>(volume, "new-delta")), disks, "snapshot").first(); + + assertTrue(xml.contains("\n")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + assertFalse(xml.contains("vdb' snapshot='no'")); + assertFalse(xml.contains("hdc")); + } + + @Test + public void createSnapshotXmlAndNewVolumePathMapDoesNotExcludeAnyDiskWhenAllAreSnapshotted() { + VolumeObjectTO root = new VolumeObjectTO(); + root.setUuid("root-volume"); + root.setPath("root-delta"); + VolumeObjectTO data = new VolumeObjectTO(); + data.setUuid("data-volume"); + data.setPath("data-delta"); + List disks = List.of( + mockDiskDefForSnapshot("vda", "/mnt/pool/root-delta", DiskDef.DeviceType.DISK), + mockDiskDefForSnapshot("vdb", "/mnt/pool/data-delta", DiskDef.DeviceType.DISK)); + + String xml = libvirtComputingResourceSpy.createSnapshotXmlAndNewVolumePathMap(List.of(new Pair<>(root, "new-root"), new Pair<>(data, "new-data")), disks, + "snapshot").first(); + + assertFalse(xml.contains("' snapshot='no'/>")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + } } diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java index 11b24a9beef6..a63bba37ca4d 100644 --- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java @@ -920,6 +920,8 @@ public VolumeVO allocVolume(long ownerId, Long zoneId, Long diskOfferingId, Long throw new InvalidParameterValueException(String.format("Snapshot %s is not in %s state yet and can't be used for volume creation", snapshotCheck, Snapshot.State.BackedUp)); } + _snapshotMgr.validateSnapshotIsNotKvmFileBasedNoCopy(snapshotCheck, "create a volume"); + SnapshotDataStoreVO snapshotStore = _snapshotDataStoreDao.findOneBySnapshotAndDatastoreRole(snapshotId, DataStoreRole.Primary); if (snapshotStore != null) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(snapshotStore.getDataStoreId()); @@ -3782,6 +3784,8 @@ public Volume migrateVolume(MigrateVolumeCmd cmd) { throw new InvalidParameterValueException("Volume cannot be migrated, please remove all Instance Snapshots for Instance to which this volume is attached"); } + _snapshotMgr.validateVolumeHasNoKvmFileBasedNoCopySnapshots(vol, "migrate it"); + StoragePoolVO srcStoragePoolVO = _storagePoolDao.findById(vol.getPoolId()); // OfflineVmwareMigration: extract this block as method and check if it is subject to regression diff --git a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java index 6fcf124a961d..af57c577de1f 100644 --- a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java +++ b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java @@ -27,6 +27,7 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.exception.ResourceAllocationException; +import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; @@ -72,6 +73,18 @@ public interface SnapshotManager extends Configurable { "For snapshot copy to another primary storage in a different zone. This is supported only for StorPool storage for now.", true, ConfigKey.Scope.StoragePool, null); + ConfigKey KvmFileBasedVolumeSnapshotNoCopy = new ConfigKey<>(Boolean.class, "kvm.file.based.volume.snapshot.no.copy", "Snapshots", "false", + "When true, volume snapshots of KVM QCOW2 volumes on file-based primary storage (NFS, SharedMountPoint and Filesystem) that are kept only on primary storage" + + " (snapshot.backup.to.secondary=false) are taken as external snapshots in the backing chain of the volume, instead of full copies of the volume." + + " Taking or reverting such a snapshot does not copy the volume; deleting it merges it with its child. While a volume has such snapshots, it cannot be" + + " migrated, regular snapshots of it cannot be reverted, and the snapshots cannot be backed up, copied, or used to create volumes, templates or Instances.", + true, ConfigKey.Scope.StoragePool, null); + + /** + * Name of the snapshot detail that marks a volume snapshot taken with {@link #KvmFileBasedVolumeSnapshotNoCopy}. + */ + String KVM_FILE_BASED_NO_COPY_SNAPSHOT = "kvmFileBasedNoCopySnapshot"; + void deletePoliciesForVolume(Long volumeId); /** @@ -88,6 +101,29 @@ public interface SnapshotManager extends Configurable { boolean canOperateOnVolume(Volume volume); + boolean isBackupSnapshotToSecondaryForZone(long zoneId); + + /** + * @return true if the snapshot was taken as a KVM file-based no-copy snapshot (see {@link #KvmFileBasedVolumeSnapshotNoCopy}). + */ + boolean isKvmFileBasedNoCopySnapshot(long snapshotId); + + /** + * @return true if the volume has KVM file-based no-copy snapshots that are not destroyed (see {@link #KvmFileBasedVolumeSnapshotNoCopy}). + */ + boolean volumeHasKvmFileBasedNoCopySnapshots(long volumeId); + + /** + * Throws an {@link com.cloud.exception.InvalidParameterValueException} if the snapshot is a KVM file-based no-copy snapshot, which cannot be used for the + * given operation. + */ + void validateSnapshotIsNotKvmFileBasedNoCopy(Snapshot snapshot, String operation); + + /** + * Throws an {@link com.cloud.exception.InvalidParameterValueException} if the volume has KVM file-based no-copy snapshots, which prevent the given operation. + */ + void validateVolumeHasNoKvmFileBasedNoCopySnapshots(Volume volume, String operation); + boolean backedUpSnapshotsExistsForVolume(Volume volume); void cleanupSnapshotsByVolume(Long volumeId); diff --git a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 6ce7a0f92bfb..c396782dc048 100755 --- a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -146,6 +146,7 @@ import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.SnapshotScheduleDao; @@ -286,7 +287,8 @@ protected DataStore getSnapshotZoneImageStore(long snapshotId, long zoneId) { return null; } - protected boolean isBackupSnapshotToSecondaryForZone(long zoneId) { + @Override + public boolean isBackupSnapshotToSecondaryForZone(long zoneId) { if (Boolean.FALSE.equals(SnapshotInfo.BackupSnapshotAfterTakingSnapshot.value())) { return false; } @@ -294,6 +296,35 @@ protected boolean isBackupSnapshotToSecondaryForZone(long zoneId) { return !DataCenter.Type.Edge.equals(zone.getType()); } + @Override + public boolean isKvmFileBasedNoCopySnapshot(long snapshotId) { + SnapshotDetailsVO detail = snapshotDetailsDao.findDetail(snapshotId, KVM_FILE_BASED_NO_COPY_SNAPSHOT); + return detail != null && Boolean.parseBoolean(detail.getValue()); + } + + @Override + public boolean volumeHasKvmFileBasedNoCopySnapshots(long volumeId) { + return _snapshotDao.listByVolumeId(volumeId).stream() + .filter(snapshot -> !Snapshot.State.Destroyed.equals(snapshot.getState()) && !Snapshot.State.Error.equals(snapshot.getState())) + .anyMatch(snapshot -> isKvmFileBasedNoCopySnapshot(snapshot.getId())); + } + + @Override + public void validateSnapshotIsNotKvmFileBasedNoCopy(Snapshot snapshot, String operation) { + if (snapshot != null && isKvmFileBasedNoCopySnapshot(snapshot.getId())) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] is a KVM file-based no-copy snapshot (see the [%s] setting), which is part of the " + + "backing chain of its volume and cannot be used to %s.", snapshot.getUuid(), KvmFileBasedVolumeSnapshotNoCopy.key(), operation)); + } + } + + @Override + public void validateVolumeHasNoKvmFileBasedNoCopySnapshots(Volume volume, String operation) { + if (volume != null && volumeHasKvmFileBasedNoCopySnapshots(volume.getId())) { + throw new InvalidParameterValueException(String.format("Volume [%s] has KVM file-based no-copy snapshots (see the [%s] setting), which are part of its " + + "backing chain. Delete them before trying to %s.", volume.getUuid(), KvmFileBasedVolumeSnapshotNoCopy.key(), operation)); + } + } + private ResourceType getStoreResourceType(long dataCenterId, Snapshot.LocationType locationType) { ResourceType storeResourceType = ResourceType.secondary_storage; if (!isBackupSnapshotToSecondaryForZone(dataCenterId) || @@ -311,7 +342,8 @@ public String getConfigComponentName() { @Override public ConfigKey[] getConfigKeys() { return new ConfigKey[] {BackupRetryAttempts, BackupRetryInterval, SnapshotHourlyMax, SnapshotDailyMax, SnapshotMonthlyMax, SnapshotWeeklyMax, usageSnapshotSelection, - SnapshotInfo.BackupSnapshotAfterTakingSnapshot, VmStorageSnapshotKvm, kvmIncrementalSnapshot, snapshotDeltaMax, snapshotShowChainSize, UseStorageReplication, KVMSnapshotEnabled}; + SnapshotInfo.BackupSnapshotAfterTakingSnapshot, VmStorageSnapshotKvm, kvmIncrementalSnapshot, snapshotDeltaMax, snapshotShowChainSize, UseStorageReplication, KVMSnapshotEnabled, + KvmFileBasedVolumeSnapshotNoCopy}; } @Override @@ -383,6 +415,11 @@ public Snapshot revertSnapshot(Long snapshotId) { throw new InvalidParameterValueException("The volume is not in Ready state."); } + if (!isKvmFileBasedNoCopySnapshot(snapshot.getId())) { + // Reverting a full copy would replace the top of the backing chain that the no-copy snapshots depend on. + validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "revert a snapshot of it that is not a no-copy snapshot"); + } + Long instanceId = volume.getInstanceId(); // If this volume is attached to an VM, then the VM needs to be in the stopped state @@ -615,6 +652,7 @@ public String extractSnapshot(ExtractSnapshotCmd cmd) { @Override public Snapshot archiveSnapshot(Long snapshotId) { + validateSnapshotIsNotKvmFileBasedNoCopy(_snapshotDao.findById(snapshotId), "archive it to secondary storage"); SnapshotInfo snapshotOnPrimary = snapshotFactory.getSnapshotOnPrimaryStore(snapshotId); if (snapshotOnPrimary == null || !snapshotOnPrimary.getStatus().equals(ObjectInDataStoreStateMachine.State.Ready)) { @@ -2389,6 +2427,7 @@ public Snapshot copySnapshot(CopySnapshotCmd cmd) throws StorageUnavailableExcep throw new InvalidParameterValueException("Unable to find snapshot with id"); } + validateSnapshotIsNotKvmFileBasedNoCopy(snapshotVO, "copy it to other zones or storage pools"); Pair snapshotZonePair = getCheckedSnapshotForCopy(snapshotVO, destZoneIds, sourceZoneId, useStorageReplication); SnapshotVO snapshot = snapshotZonePair.first(); sourceZoneId = snapshotZonePair.second(); diff --git a/server/src/main/java/com/cloud/template/TemplateManagerImpl.java b/server/src/main/java/com/cloud/template/TemplateManagerImpl.java index 86bcb8a76d79..87a883533fce 100755 --- a/server/src/main/java/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/main/java/com/cloud/template/TemplateManagerImpl.java @@ -286,6 +286,8 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, @Inject private SnapshotDao _snapshotDao; @Inject + private SnapshotManager snapshotManager; + @Inject private ConfigurationDao _configDao; @Inject private DomainDao _domainDao; @@ -2290,6 +2292,7 @@ public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, Account t if (snapshot == null) { throw new InvalidParameterValueException("Failed to create private Template record, unable to find Snapshot " + snapshotId); } + snapshotManager.validateSnapshotIsNotKvmFileBasedNoCopy(snapshot, "create a Template"); // Volume could be removed so find including removed to record source template id. volume = _volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId()); diff --git a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java index 689b748379f7..e4cae97a5be6 100644 --- a/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/UserVmManagerImpl.java @@ -361,6 +361,7 @@ import com.cloud.storage.Volume; import com.cloud.storage.VolumeApiService; import com.cloud.storage.VolumeVO; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.clvm.ClvmPoolManager; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSCategoryDao; @@ -502,6 +503,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir @Inject private SnapshotDao _snapshotDao; @Inject + private SnapshotManager snapshotManager; + @Inject private GuestOSDao _guestOSDao; @Inject private HighAvailabilityManager _haMgr; @@ -6777,6 +6780,7 @@ public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityE throw new InvalidParameterValueException("Could not find snapshot with id=" + cmd.getSnapshotId()); } _accountMgr.checkAccess(caller, null, true, snapshot); + snapshotManager.validateSnapshotIsNotKvmFileBasedNoCopy(snapshot, "deploy an Instance"); VolumeInfo volumeOfSnapshot = getVolume(snapshot.getVolumeId(), templateId, true); if (volumeOfSnapshot != null) { templateId = volumeOfSnapshot.getTemplateId(); @@ -7554,9 +7558,17 @@ private VMInstanceVO preVmStorageMigrationCheck(Long vmId) { throw new InvalidParameterValueException("Instance's disk cannot be migrated, please remove all the Instance Snapshots for this Instance"); } + validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(vmId, "migrate the storage of its Instance"); + return vm; } + protected void validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(long vmId, String operation) { + for (VolumeVO volume : _volsDao.findByInstance(vmId)) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, operation); + } + } + private VirtualMachine findMigratedVm(long vmId, VirtualMachine.Type vmType) { if (VirtualMachine.Type.User.equals(vmType)) { return _vmDao.findById(vmId); @@ -8363,6 +8375,8 @@ public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinatio throw new InvalidParameterValueException("Instance with Instance Snapshots cannot be migrated with storage, please remove all Instance Snapshots"); } + validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(vmId, "migrate its Instance with storage"); + Pair sourceDestinationHosts = getHostsForMigrateVmWithStorage(vm, destinationHost); Host srcHost = sourceDestinationHosts.first(); 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 9203a8345f3f..19b03a0ce0da 100644 --- a/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java @@ -90,6 +90,7 @@ import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; @@ -148,6 +149,7 @@ public class VMSnapshotManagerImpl extends MutualExclusiveIdsManagerBase impleme @Inject AccountManager _accountMgr; @Inject GuestOSDao _guestOSDao; @Inject SnapshotDao _snapshotDao; + @Inject SnapshotManager snapshotManager; @Inject VirtualMachineManager _itMgr; @Inject NetworkService _networkService; @Inject ConfigurationDao _configDao; @@ -387,6 +389,12 @@ public VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDesc } if (userVmVo.getHypervisorType() == HypervisorType.KVM) { + // KVM file-based no-copy volume snapshots are part of the backing chains of the volumes: an Instance snapshot would either move the volumes again or, + // when reverted, replace the top of the chains that the no-copy snapshots depend on. + for (VolumeVO volume : _volumeDao.findByInstance(userVmVo.getId())) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "take an Instance snapshot of its Instance"); + } + //DefaultVMSnapshotStrategy - allows snapshot with memory when VM is in running state and all volumes have to be in QCOW format //ScaleIOVMSnapshotStrategy - allows group snapshots without memory; all VM's volumes should be on same storage pool; The state of VM could be Running/Stopped; RAW image format is only supported //StorageVMSnapshotStrategy - allows volume snapshots without memory; VM has to be in Running state; No limitation of the image format if the storage plugin supports volume snapshots; "kvm.vmstoragesnapshot.enabled" has to be enabled diff --git a/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerImplTest.java b/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerImplTest.java index 3cd7db8ed996..0b401f8834e5 100644 --- a/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerImplTest.java +++ b/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerImplTest.java @@ -35,6 +35,8 @@ import com.cloud.storage.VolumeVO; import com.cloud.server.TaggedResourceService; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.SnapshotZoneDao; import com.cloud.storage.dao.VolumeDao; @@ -120,6 +122,8 @@ public class SnapshotManagerImplTest { VolumeDataFactory volFactory; @Mock UserVmDao userVmDao; + @Mock + SnapshotDetailsDao snapshotDetailsDao; @InjectMocks SnapshotManagerImpl snapshotManager = new SnapshotManagerImpl(); @@ -822,4 +826,75 @@ public void testEndCurrentChainIfNeededStopsOnMissingParentRef() { Mockito.verify(snapshotStoreDao, Mockito.never()).update(Mockito.anyLong(), Mockito.any(SnapshotDataStoreVO.class)); } + + private SnapshotVO mockNoCopySnapshot(long id, Snapshot.State state, boolean noCopy) { + SnapshotVO snapshot = Mockito.mock(SnapshotVO.class); + Mockito.lenient().when(snapshot.getId()).thenReturn(id); + Mockito.lenient().when(snapshot.getState()).thenReturn(state); + Mockito.lenient().when(snapshotDetailsDao.findDetail(id, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT)) + .thenReturn(noCopy ? new SnapshotDetailsVO(id, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, "true", false) : null); + return snapshot; + } + + @Test + public void isKvmFileBasedNoCopySnapshotChecksTheSnapshotDetail() { + mockNoCopySnapshot(1L, Snapshot.State.BackedUp, true); + mockNoCopySnapshot(2L, Snapshot.State.BackedUp, false); + Assert.assertTrue(snapshotManager.isKvmFileBasedNoCopySnapshot(1L)); + Assert.assertFalse(snapshotManager.isKvmFileBasedNoCopySnapshot(2L)); + } + + @Test + public void volumeHasKvmFileBasedNoCopySnapshotsIgnoresDestroyedAndFailedSnapshots() { + SnapshotVO destroyed = mockNoCopySnapshot(1L, Snapshot.State.Destroyed, true); + SnapshotVO failed = mockNoCopySnapshot(2L, Snapshot.State.Error, true); + SnapshotVO regular = mockNoCopySnapshot(3L, Snapshot.State.BackedUp, false); + List snapshots = List.of(destroyed, failed, regular); + Mockito.when(snapshotDao.listByVolumeId(10L)).thenReturn(snapshots); + Assert.assertFalse(snapshotManager.volumeHasKvmFileBasedNoCopySnapshots(10L)); + + SnapshotVO noCopy = mockNoCopySnapshot(4L, Snapshot.State.BackedUp, true); + Mockito.when(snapshotDao.listByVolumeId(10L)).thenReturn(List.of(noCopy)); + Assert.assertTrue(snapshotManager.volumeHasKvmFileBasedNoCopySnapshots(10L)); + } + + @Test + public void validateSnapshotIsNotKvmFileBasedNoCopyRefusesNoCopySnapshots() { + SnapshotVO regular = mockNoCopySnapshot(1L, Snapshot.State.BackedUp, false); + snapshotManager.validateSnapshotIsNotKvmFileBasedNoCopy(regular, "create a volume"); + snapshotManager.validateSnapshotIsNotKvmFileBasedNoCopy(null, "create a volume"); + + SnapshotVO noCopy = mockNoCopySnapshot(2L, Snapshot.State.BackedUp, true); + Assert.assertThrows(InvalidParameterValueException.class, () -> snapshotManager.validateSnapshotIsNotKvmFileBasedNoCopy(noCopy, "create a volume")); + } + + @Test + public void validateVolumeHasNoKvmFileBasedNoCopySnapshotsRefusesVolumesWithThem() { + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getId()).thenReturn(10L); + SnapshotVO regular = mockNoCopySnapshot(1L, Snapshot.State.BackedUp, false); + Mockito.when(snapshotDao.listByVolumeId(10L)).thenReturn(List.of(regular)); + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "migrate it"); + + SnapshotVO noCopy = mockNoCopySnapshot(2L, Snapshot.State.BackedUp, true); + Mockito.when(snapshotDao.listByVolumeId(10L)).thenReturn(List.of(noCopy)); + Assert.assertThrows(InvalidParameterValueException.class, () -> snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "migrate it")); + } + + @Test + public void revertRegularSnapshotIsRefusedWhileTheVolumeHasNoCopySnapshots() { + SnapshotVO regular = mockNoCopySnapshot(1L, Snapshot.State.BackedUp, false); + Mockito.when(regular.getVolumeId()).thenReturn(10L); + Mockito.when(regular.getTypeDescription()).thenReturn(Snapshot.Type.MANUAL.name()); + Mockito.when(snapshotDao.findById(1L)).thenReturn(regular); + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getId()).thenReturn(10L); + Mockito.when(volume.getState()).thenReturn(com.cloud.storage.Volume.State.Ready); + Mockito.when(volumeDao.findById(10L)).thenReturn(volume); + SnapshotVO noCopy = mockNoCopySnapshot(2L, Snapshot.State.BackedUp, true); + Mockito.when(snapshotDao.listByVolumeId(10L)).thenReturn(List.of(noCopy)); + + Assert.assertThrows(InvalidParameterValueException.class, () -> snapshotManager.revertSnapshot(1L)); + Mockito.verify(volume, Mockito.never()).getInstanceId(); + } } diff --git a/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerTest.java b/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerTest.java index 8eee0ed66261..158f4f6f7d11 100755 --- a/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerTest.java +++ b/server/src/test/java/com/cloud/storage/snapshot/SnapshotManagerTest.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.storage.snapshot; +import com.cloud.storage.dao.SnapshotDetailsDao; import org.apache.cloudstack.api.command.user.snapshot.ExtractSnapshotCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; @@ -118,6 +119,8 @@ public class SnapshotManagerTest { @InjectMocks SnapshotManagerImpl _snapshotMgr = new SnapshotManagerImpl(); @Mock + SnapshotDetailsDao snapshotDetailsDao; + @Mock SnapshotDao _snapshotDao; @Mock VolumeDao _volumeDao; diff --git a/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java b/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java index 61407a9d4c2b..879373956bc6 100755 --- a/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java +++ b/server/src/test/java/com/cloud/template/TemplateManagerImplTest.java @@ -19,6 +19,7 @@ package com.cloud.template; +import com.cloud.storage.snapshot.SnapshotManager; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; @@ -188,6 +189,9 @@ public class TemplateManagerImplTest extends TestCase { @InjectMocks TemplateManagerImpl templateManager; + @Mock + SnapshotManager snapshotManager; + @Mock DataStoreManager dataStoreManager; diff --git a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java index 89d703f3ff4b..c24d2b47035b 100644 --- a/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java +++ b/server/src/test/java/com/cloud/vm/UserVmManagerImplTest.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.vm; +import com.cloud.storage.snapshot.SnapshotManager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -237,6 +238,9 @@ public class UserVmManagerImplTest { @InjectMocks private UserVmManagerImpl userVmManagerImpl = new UserVmManagerImpl(); + @Mock + private SnapshotManager snapshotManager; + @Mock private ServiceOfferingDao _serviceOfferingDao; 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 0ef131faa95b..5af514fa0623 100644 --- a/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java +++ b/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java @@ -39,6 +39,7 @@ import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -92,6 +93,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -105,6 +107,8 @@ public class VMSnapshotManagerTest { @Mock VolumeDao _volumeDao; @Mock + SnapshotManager snapshotManager; + @Mock AccountDao _accountDao; @Mock VMInstanceDao _vmInstanceDao; @@ -205,6 +209,7 @@ public void setup() { _vmSnapshotMgr._vmInstanceDetailsDao = _vmInstanceDetailsDao; _vmSnapshotMgr._vmSnapshotDetailsDao = _vmSnapshotDetailsDao; _vmSnapshotMgr._userVmManager = _userVmManager; + _vmSnapshotMgr.snapshotManager = snapshotManager; when(_userVMDao.findById(anyLong())).thenReturn(vmMock); when(_vmSnapshotDao.findByName(anyLong(), anyString())).thenReturn(null); @@ -318,6 +323,16 @@ public void testAllocVMSnapshotF5() throws ResourceAllocationException { _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID, "", "", true); } + // KVM Instance with a volume that has KVM file-based no-copy snapshots + @Test(expected = InvalidParameterValueException.class) + public void testAllocVMSnapshotRefusedWhenAVolumeHasKvmFileBasedNoCopySnapshots() throws ResourceAllocationException { + when(vmMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + when(_hypervisorCapabilitiesDao.isVmSnapshotEnabled(Hypervisor.HypervisorType.KVM, "default")).thenReturn(true); + doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volumeMock, "take an Instance snapshot of its Instance"); + _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID, "", "", false); + } + // successful creation case @Test public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException, ResourceAllocationException, NoTransitionException { From d2d98c3a48fc7ec555dfeff2064e9a8ed27454ee Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:27:36 +0000 Subject: [PATCH 02/12] Address review: reserve the volume, order the chain by take, two-way backup checks, expunge cleanup - Take, revert and delete reserve the volume (Ready -> Snapshotting/RevertSnapshotting) before reading its chain and paths, and abort without sending any command when the reservation fails or loses a race (stateTransit returns false). - Each take records its position in the backing chain (snapshot detail kvmFileBasedNoCopySnapshotSequence), computed while the volume is reserved. The chain is ordered by it instead of by snapshot id, since ids follow allocation order. - When the volume was expunged, deleting a no-copy snapshot deletes its own frozen file (DeleteDiskOnlyVmSnapshotCommand, pool-relative path) before dropping its metadata. - Backup offerings: assigning an offering, restoring a backup and attaching to an Instance with an offering are refused while the volumes have no-copy snapshots. Co-Authored-By: Claude Opus 5.5 --- .../KvmFileBasedNoCopySnapshotStrategy.java | 166 ++++++++++++----- ...vmFileBasedNoCopySnapshotStrategyTest.java | 174 +++++++++++++++++- .../cloud/storage/VolumeApiServiceImpl.java | 5 + .../cloudstack/backup/BackupManagerImpl.java | 18 ++ .../storage/VolumeApiServiceImplTest.java | 18 ++ .../cloudstack/backup/BackupManagerTest.java | 22 +++ 6 files changed, 355 insertions(+), 48 deletions(-) diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index b4725e9617ed..fec94ac0a565 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -50,6 +50,7 @@ import com.cloud.agent.api.VMSnapshotTO; import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.DeleteDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.storage.MergeDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; @@ -68,6 +69,7 @@ import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; import com.cloud.storage.dao.SnapshotZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; @@ -93,6 +95,11 @@ */ public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { + /** + * Snapshot detail holding the position of a no-copy snapshot in the backing chain of its volume. + */ + protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE = "kvmFileBasedNoCopySnapshotSequence"; + protected static final Set SUPPORTED_POOL_TYPES = Set.of(Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint, Storage.StoragePoolType.Filesystem); @@ -302,11 +309,15 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { logger.info("Taking KVM file-based no-copy snapshot [{}] of volume [{}].", snapshot.getUuid(), volumeInfo.getUuid()); - volumeInfo.stateTransit(Volume.Event.SnapshotRequested); + SnapshotVO snapshotVO = snapshotDao.findById(snapshot.getId()); + reserveVolume(volumeInfo, Volume.Event.SnapshotRequested, snapshotVO); SnapshotObject snapshotOnPrimary = null; boolean succeeded = false; try { + // Computed while the volume is reserved: the position of the snapshot in the backing chain, which follows the order of the takes and not the order of + // the snapshot ids (allocated before the work is queued). + long sequence = listNoCopySnapshotsOfVolume(volumeInfo.getId()).stream().mapToLong(this::getChainSequence).max().orElse(0L) + 1; snapshotOnPrimary = createSnapshotOnPrimary(snapshot); VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); String oldVolumePath = volumeTO.getPath(); @@ -336,6 +347,7 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.OperationSucceeded, new CreateObjectAnswer(snapshotTO)); snapshotOnPrimary.processEvent(Snapshot.Event.OperationSucceeded); + snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false); snapshotDetailsDao.addDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, Boolean.TRUE.toString(), false); logger.info("Took KVM file-based no-copy snapshot [{}] of volume [{}]: the snapshot is [{}] and the volume is now on [{}].", snapshot.getUuid(), @@ -392,25 +404,27 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { throw new CloudRuntimeException(String.format("Unable to find the volume of snapshot [%s].", snapshotVO.getUuid())); } - List chain = listNoCopySnapshotsOfVolume(volumeInfo.getId()); - if (chain.isEmpty() || chain.get(chain.size() - 1).getId() != snapshotVO.getId()) { - throw new InvalidParameterValueException(String.format("Only the most recent KVM file-based no-copy snapshot of volume [%s] can be reverted. Delete the snapshots " + - "taken after snapshot [%s] before reverting it.", volumeInfo.getUuid(), snapshotVO.getUuid())); - } + // Reserve the volume before reading its chain and paths, so that no other snapshot operation can change them underneath. + reserveVolume(volumeInfo, Volume.Event.RevertSnapshotRequested, snapshotVO); + boolean succeeded = false; + try { + volumeInfo = volumeDataFactory.getVolume(snapshotVO.getVolumeId()); - VMInstanceVO vm = getAttachedVm(volumeInfo); - if (isVmRunning(vm)) { - throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s].", vm.getUuid(), - volumeInfo.getUuid(), snapshotVO.getUuid())); - } + List chain = listNoCopySnapshotsOfVolume(volumeInfo.getId()); + if (chain.isEmpty() || chain.get(chain.size() - 1).getId() != snapshotVO.getId()) { + throw new InvalidParameterValueException(String.format("Only the most recent KVM file-based no-copy snapshot of volume [%s] can be reverted. Delete the " + + "snapshots taken after snapshot [%s] before reverting it.", volumeInfo.getUuid(), snapshotVO.getUuid())); + } - logger.info("Reverting volume [{}] to KVM file-based no-copy snapshot [{}].", volumeInfo.getUuid(), snapshotVO.getUuid()); + VMInstanceVO vm = getAttachedVm(volumeInfo); + if (isVmRunning(vm)) { + throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s].", vm.getUuid(), + volumeInfo.getUuid(), snapshotVO.getUuid())); + } - SnapshotObjectTO snapshotTO = getSnapshotObjectTO(snapshotVO, volumeInfo); - volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested); + logger.info("Reverting volume [{}] to KVM file-based no-copy snapshot [{}].", volumeInfo.getUuid(), snapshotVO.getUuid()); - boolean succeeded = false; - try { + SnapshotObjectTO snapshotTO = getSnapshotObjectTO(snapshotVO, volumeInfo); RevertDiskOnlyVmSnapshotCommand command = new RevertDiskOnlyVmSnapshotCommand(List.of(snapshotTO), vm != null ? vm.getInstanceName() : null, vm != null ? vm.getUuid() : null, false, null); @@ -477,43 +491,50 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { VolumeVO volumeVO = volumeDao.findByIdIncludingRemoved(snapshotVO.getVolumeId()); SnapshotDataStoreVO snapshotStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); - if (volumeVO == null || volumeVO.getRemoved() != null || snapshotStoreRef == null) { - logger.debug("The volume of KVM file-based no-copy snapshot [{}] was removed, together with its backing chain; only the snapshot metadata will be removed.", - snapshotVO.getUuid()); + if (snapshotStoreRef == null) { + logger.debug("KVM file-based no-copy snapshot [{}] has no file on primary storage; only its metadata will be removed.", snapshotVO.getUuid()); removeSnapshotMetadata(snapshotVO); return true; } - VolumeInfo volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); - if (!Volume.State.Ready.equals(volumeInfo.getState())) { - throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while its volume [%s] is in state [%s].", snapshotVO.getUuid(), - volumeVO.getUuid(), volumeInfo.getState())); + if (volumeVO == null || volumeVO.getRemoved() != null || Volume.State.Expunged.equals(volumeVO.getState())) { + // The active file of the volume is gone; its frozen files are not, as nothing else references them (no-copy snapshots cannot be used to create + // volumes or templates, and template files are never one of them). + deleteFrozenFileOfExpungedVolume(snapshotVO, snapshotStoreRef); + removeSnapshotMetadata(snapshotVO); + return true; } - VMInstanceVO vm = getAttachedVm(volumeInfo); - if (vm != null && !VirtualMachine.State.Running.equals(vm.getState()) && !VirtualMachine.State.Stopped.equals(vm.getState())) { - throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while the Instance [%s] of its volume is in state [%s].", - snapshotVO.getUuid(), vm.getUuid(), vm.getState())); - } - boolean vmRunning = isVmRunning(vm); + VolumeInfo volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); + // Reserve the volume before reading its chain and paths, so that no other snapshot operation can change them underneath. + reserveVolume(volumeInfo, Volume.Event.SnapshotRequested, snapshotVO); + boolean succeeded = false; + try { + volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); + volumeVO = volumeDao.findById(volumeVO.getId()); + snapshotStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); + + VMInstanceVO vm = getAttachedVm(volumeInfo); + if (vm != null && !VirtualMachine.State.Running.equals(vm.getState()) && !VirtualMachine.State.Stopped.equals(vm.getState())) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while the Instance [%s] of its volume is in state [%s].", + snapshotVO.getUuid(), vm.getUuid(), vm.getState())); + } + boolean vmRunning = isVmRunning(vm); - List chain = listNoCopySnapshotsOfVolume(volumeVO.getId()); - int index = chain.stream().map(SnapshotVO::getId).collect(Collectors.toList()).indexOf(snapshotVO.getId()); - if (index < 0) { - throw new CloudRuntimeException(String.format("Unable to find snapshot [%s] in the backing chain of volume [%s].", snapshotVO.getUuid(), volumeVO.getUuid())); - } + List chain = listNoCopySnapshotsOfVolume(volumeVO.getId()); + int index = chain.stream().map(SnapshotVO::getId).collect(Collectors.toList()).indexOf(snapshotVO.getId()); + if (index < 0) { + throw new CloudRuntimeException(String.format("Unable to find snapshot [%s] in the backing chain of volume [%s].", snapshotVO.getUuid(), volumeVO.getUuid())); + } - VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); - SnapshotObjectTO parentTO = getSnapshotObjectTO(snapshotVO, volumeInfo); - SnapshotVO childSnapshot = index + 1 < chain.size() ? chain.get(index + 1) : null; - DeltaMergeTreeTO deltaMergeTree = createDeltaMergeTree(chain, index, volumeInfo, volumeTO, parentTO); + VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); + SnapshotObjectTO parentTO = getSnapshotObjectTO(snapshotVO, volumeInfo); + SnapshotVO childSnapshot = index + 1 < chain.size() ? chain.get(index + 1) : null; + DeltaMergeTreeTO deltaMergeTree = createDeltaMergeTree(chain, index, volumeInfo, volumeTO, parentTO); - logger.info("Deleting KVM file-based no-copy snapshot [{}] of volume [{}] by merging [{}] into it.", snapshotVO.getUuid(), volumeVO.getUuid(), - deltaMergeTree.getChild().getPath()); + logger.info("Deleting KVM file-based no-copy snapshot [{}] of volume [{}] by merging [{}] into it.", snapshotVO.getUuid(), volumeVO.getUuid(), + deltaMergeTree.getChild().getPath()); - volumeInfo.stateTransit(Volume.Event.SnapshotRequested); - boolean succeeded = false; - try { MergeDiskOnlyVmSnapshotCommand command = new MergeDiskOnlyVmSnapshotCommand(List.of(deltaMergeTree), vmRunning, vm != null ? vm.getInstanceName() : null); Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); if (answer == null || !answer.getResult()) { @@ -529,6 +550,48 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { } } + /** + * Deletes the frozen file of a snapshot whose volume was expunged, through any host with access to the storage pool of the snapshot. + */ + protected void deleteFrozenFileOfExpungedVolume(SnapshotVO snapshotVO, SnapshotDataStoreVO snapshotStoreRef) { + SnapshotInfo snapshotInfo = snapshotDataFactory.getSnapshot(snapshotVO.getId(), snapshotStoreRef.getDataStoreId(), DataStoreRole.Primary); + if (snapshotInfo == null) { + logger.warn("Unable to find KVM file-based no-copy snapshot [{}] on primary storage [{}]; its file [{}] may be left behind.", snapshotVO.getUuid(), + snapshotStoreRef.getDataStoreId(), snapshotStoreRef.getInstallPath()); + return; + } + + EndPoint endPoint = endPointSelector.select(snapshotInfo); + if (endPoint == null) { + throw new CloudRuntimeException(String.format("Unable to find a host with access to the storage pool of snapshot [%s] to delete its file.", snapshotVO.getUuid())); + } + + logger.info("Deleting the file [{}] of KVM file-based no-copy snapshot [{}], as its volume was expunged.", snapshotStoreRef.getInstallPath(), snapshotVO.getUuid()); + Answer answer = sendToHost(endPoint.getId(), new DeleteDiskOnlyVmSnapshotCommand(List.of(snapshotInfo.getTO()))); + if (answer == null || !answer.getResult()) { + throw new CloudRuntimeException(String.format("Failed to delete the file of KVM file-based no-copy snapshot [%s] due to [%s].", snapshotVO.getUuid(), + getAnswerDetails(answer))); + } + } + + /** + * Moves the volume out of Ready, which excludes every other snapshot, migration and attach operation on it until it is released. Fails if the volume is not + * Ready or if another operation changed its state concurrently ({@link VolumeInfo#stateTransit} returns false when its optimistic update loses). + */ + protected void reserveVolume(VolumeInfo volumeInfo, Volume.Event event, SnapshotVO snapshotVO) { + boolean reserved; + try { + reserved = volumeInfo.stateTransit(event); + } catch (CloudRuntimeException e) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be used while its volume [%s] is in state [%s]: %s", snapshotVO.getUuid(), + volumeInfo.getUuid(), volumeInfo.getState(), e.getMessage())); + } + if (!reserved) { + throw new CloudRuntimeException(String.format("Volume [%s] is busy with another operation; retry the operation on snapshot [%s].", volumeInfo.getUuid(), + snapshotVO.getUuid())); + } + } + /** * The child of the snapshot is the next snapshot of the volume or, for the most recent snapshot, the current delta of the volume. The child is committed into the * snapshot, and the file on top of the child (the grandchild) is rebased onto the snapshot. @@ -590,10 +653,25 @@ protected List listNoCopySnapshotsOfVolume(long volumeId) { return snapshotDao.listByVolumeId(volumeId).stream() .filter(snapshot -> Snapshot.State.BackedUp.equals(snapshot.getState()) || Snapshot.State.CreatedOnPrimary.equals(snapshot.getState())) .filter(snapshot -> snapshotManager.isKvmFileBasedNoCopySnapshot(snapshot.getId())) - .sorted(Comparator.comparingLong(SnapshotVO::getId)) + .sorted(Comparator.comparingLong(this::getChainSequence).thenComparingLong(SnapshotVO::getId)) .collect(Collectors.toList()); } + /** + * @return the position of the snapshot in the backing chain of its volume, recorded when it was taken. + */ + protected long getChainSequence(SnapshotVO snapshotVO) { + SnapshotDetailsVO detail = snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE); + if (detail == null) { + return snapshotVO.getId(); + } + try { + return Long.parseLong(detail.getValue()); + } catch (NumberFormatException e) { + return snapshotVO.getId(); + } + } + protected SnapshotObjectTO getSnapshotObjectTO(SnapshotVO snapshotVO, VolumeInfo volumeInfo) { SnapshotInfo snapshotInfo = snapshotDataFactory.getSnapshot(snapshotVO.getId(), volumeInfo.getPoolId(), DataStoreRole.Primary); if (snapshotInfo == null) { diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 381d47ad556d..000ad85297b0 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -37,6 +37,8 @@ import java.util.Map; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint; +import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; @@ -61,6 +63,7 @@ import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotCommand; +import com.cloud.agent.api.storage.DeleteDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.storage.MergeDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; @@ -78,6 +81,7 @@ import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; import com.cloud.storage.dao.SnapshotZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; @@ -111,6 +115,7 @@ public class KvmFileBasedNoCopySnapshotStrategyTest { private PrimaryDataStoreDao storagePoolDao; private SnapshotManager snapshotManager; private HostDetailsDao hostDetailsDao; + private EndPointSelector endPointSelector; private SnapshotInfo snapshotInfo; private SnapshotVO snapshotVO; @@ -187,6 +192,7 @@ public void setup() { when(volumeInfo.getState()).thenReturn(Volume.State.Ready); when(volumeInfo.getTO()).thenReturn(volumeTO); when(volumeInfo.getInstanceId()).thenReturn(null); + when(volumeInfo.stateTransit(any())).thenReturn(true); when(snapshotInfo.getBaseVolume()).thenReturn(volumeInfo); when(volumeDataFactory.getVolume(VOLUME_ID)).thenReturn(volumeInfo); @@ -202,6 +208,8 @@ public void setup() { doReturn(HOST_ID).when(strategy).getHostIdForOperation(any(), any()); hostDetailsDao = mock(HostDetailsDao.class); strategy.hostDetailsDao = hostDetailsDao; + endPointSelector = mock(EndPointSelector.class); + strategy.endPointSelector = endPointSelector; when(hostDetailsDao.findDetail(HOST_ID, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME)).thenReturn(new DetailVO(HOST_ID, Host.HOST_KVM_DISK_ONLY_SNAPSHOT_SINGLE_VOLUME, "true")); } @@ -227,7 +235,9 @@ private void attachVolumeToVm() { */ private List mockChain(long... ids) { List chain = new ArrayList<>(); + long sequence = 0; for (long id : ids) { + sequence++; SnapshotVO snapshot = id == SNAPSHOT_ID ? snapshotVO : mockSnapshotVO(id, Snapshot.State.BackedUp); when(snapshotManager.isKvmFileBasedNoCopySnapshot(id)).thenReturn(true); @@ -240,7 +250,10 @@ private List mockChain(long... ids) { SnapshotDataStoreVO storeRef = mock(SnapshotDataStoreVO.class); when(storeRef.getInstallPath()).thenReturn("frozen-" + id); when(storeRef.getPhysicalSize()).thenReturn(100L); + when(storeRef.getDataStoreId()).thenReturn(POOL_ID); when(snapshotStoreDao.findOneBySnapshotAndDatastoreRole(id, DataStoreRole.Primary)).thenReturn(storeRef); + when(snapshotDetailsDao.findDetail(id, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE)) + .thenReturn(new SnapshotDetailsVO(id, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false)); chain.add(snapshot); } when(snapshotDao.listByVolumeId(VOLUME_ID)).thenReturn(chain); @@ -578,17 +591,52 @@ public void deleteFailureKeepsMetadata() { verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); } + private Command deleteSnapshotOfGoneVolumeAndCaptureCommand() { + EndPoint endPoint = mock(EndPoint.class); + when(endPoint.getId()).thenReturn(HOST_ID); + when(endPointSelector.select(any(SnapshotInfo.class))).thenReturn(endPoint); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(new Answer(null, true, null)).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + return commandCaptor.getValue(); + } + @Test - public void deleteSnapshotOfRemovedVolumeOnlyRemovesMetadata() { + public void deleteSnapshotOfRemovedVolumeDeletesItsFrozenFile() { mockChain(SNAPSHOT_ID); when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); - assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + DeleteDiskOnlyVmSnapshotCommand command = (DeleteDiskOnlyVmSnapshotCommand) deleteSnapshotOfGoneVolumeAndCaptureCommand(); - verify(strategy, never()).sendToHost(anyLong(), any()); + assertEquals(1, command.getSnapshots().size()); + assertEquals("frozen-" + SNAPSHOT_ID, command.getSnapshots().get(0).getPath()); + verify(volumeInfo, never()).stateTransit(any()); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + } + + @Test + public void deleteSnapshotOfExpungedVolumeDeletesItsFrozenFile() { + mockChain(SNAPSHOT_ID); + when(volumeVO.getState()).thenReturn(Volume.State.Expunged); + + assertTrue(deleteSnapshotOfGoneVolumeAndCaptureCommand() instanceof DeleteDiskOnlyVmSnapshotCommand); verify(snapshotVO).setState(Snapshot.State.Destroyed); } + @Test + public void deleteSnapshotOfExpungedVolumeKeepsMetadataWhenTheFileCannotBeDeleted() { + mockChain(SNAPSHOT_ID); + when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); + EndPoint endPoint = mock(EndPoint.class); + when(endPoint.getId()).thenReturn(HOST_ID); + when(endPointSelector.select(any(SnapshotInfo.class))).thenReturn(endPoint); + doReturn(new Answer(null, false, "permission denied")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + verify(snapshotVO, never()).setState(any()); + } + @Test public void deleteSnapshotInErrorOnlyRemovesMetadata() { when(snapshotVO.getState()).thenReturn(Snapshot.State.Error); @@ -605,11 +653,129 @@ public void deleteSnapshotFromOtherZoneIsRefused() { } @Test - public void deleteSnapshotWhileVolumeIsBusyIsRefused() { + public void deleteSnapshotWhileVolumeIsInAnotherStateIsRefused() { mockChain(SNAPSHOT_ID); when(volumeInfo.getState()).thenReturn(Volume.State.Migrating); + when(volumeInfo.stateTransit(Volume.Event.SnapshotRequested)).thenThrow(new CloudRuntimeException("no transition")); assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + } + + // volume reservation races (stateTransit returns false when its optimistic update loses) + + @Test + public void takeSnapshotIsAbortedWhenTheVolumeReservationLosesARace() { + when(volumeInfo.stateTransit(Volume.Event.SnapshotRequested)).thenReturn(false); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(strategy, never()).createSnapshotOnPrimary(any()); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); + } + + @Test + public void revertSnapshotIsAbortedWhenTheVolumeReservationLosesARace() { + mockChain(SNAPSHOT_ID); + when(volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested)).thenReturn(false); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void deleteSnapshotIsAbortedWhenTheVolumeReservationLosesARace() { + mockChain(SNAPSHOT_ID); + when(volumeInfo.stateTransit(Volume.Event.SnapshotRequested)).thenReturn(false); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void revertReadsTheChainOnlyAfterReservingTheVolume() { + mockChain(5L, SNAPSHOT_ID); + doReturn(new Answer(null, false, "failed")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + org.mockito.InOrder inOrder = Mockito.inOrder(volumeInfo, snapshotDao); + inOrder.verify(volumeInfo).stateTransit(Volume.Event.RevertSnapshotRequested); + inOrder.verify(snapshotDao).listByVolumeId(VOLUME_ID); + } + + @Test + public void deleteReadsTheChainOnlyAfterReservingTheVolume() { + mockChain(SNAPSHOT_ID); + doReturn(new Answer(null, false, "failed")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + org.mockito.InOrder inOrder = Mockito.inOrder(volumeInfo, snapshotDao); + inOrder.verify(volumeInfo).stateTransit(Volume.Event.SnapshotRequested); + inOrder.verify(snapshotDao).listByVolumeId(VOLUME_ID); + } + + // chain order follows the takes, not the snapshot ids + + @Test + public void chainIsOrderedByTakeSequenceNotById() { + mockChain(SNAPSHOT_ID + 5, SNAPSHOT_ID); // the snapshot with the higher id was taken first + + List chain = strategy.listNoCopySnapshotsOfVolume(VOLUME_ID); + + assertEquals(SNAPSHOT_ID + 5, chain.get(0).getId()); + assertEquals(SNAPSHOT_ID, chain.get(1).getId()); + } + + @Test + public void revertOfTheLatestTakeIsAllowedEvenWithALowerId() { + mockChain(SNAPSHOT_ID + 5, SNAPSHOT_ID); + RevertDiskOnlyVmSnapshotAnswer answer = mock(RevertDiskOnlyVmSnapshotAnswer.class); + VolumeObjectTO reverted = new VolumeObjectTO(); + reverted.setPath("new-delta"); + when(answer.getResult()).thenReturn(true); + when(answer.getVolumeObjectTos()).thenReturn(List.of(reverted)); + doReturn(answer).when(strategy).sendToHost(anyLong(), any()); + + assertTrue(strategy.revertSnapshot(snapshotInfo)); + } + + @Test + public void revertOfAnOlderTakeIsRefusedEvenWithAHigherId() { + mockChain(SNAPSHOT_ID, SNAPSHOT_ID - 5); // the snapshot with the lower id was taken last + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void deleteMergeTreeFollowsTheTakeSequence() { + mockChain(SNAPSHOT_ID, SNAPSHOT_ID - 5); // taken: SNAPSHOT_ID first, then SNAPSHOT_ID - 5 + + DeltaMergeTreeTO tree = deleteAndCaptureMerge().getDeltaMergeTreeToList().get(0); + + assertEquals("frozen-" + SNAPSHOT_ID, tree.getParent().getPath()); + assertEquals("frozen-" + (SNAPSHOT_ID - 5), tree.getChild().getPath()); + } + + @Test + public void takeSnapshotRecordsTheNextChainSequence() { + mockChain(3L, 4L); + mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Map.of(VOLUME_UUID, 1L)); + doReturn(answer).when(strategy).sendToHost(anyLong(), any()); + + strategy.takeSnapshot(snapshotInfo); + + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, "3", false); } @Test diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java index a63bba37ca4d..d2fcdc581b85 100644 --- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java @@ -3043,6 +3043,11 @@ public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId, Boolean validateIfVmHasBackups(vm, true); + if (vm.getBackupOfferingId() != null) { + // Backups may add or replace files in the backing chains that KVM file-based no-copy snapshots are part of. + _snapshotMgr.validateVolumeHasNoKvmFileBasedNoCopySnapshots(_volsDao.findById(volumeToAttach.getId()), "attach it to an Instance with a backup offering"); + } + _accountMgr.checkAccess(caller, null, true, volumeToAttach, vm); StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId()); diff --git a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java index 93be8cb3ac68..cbc99b2304d0 100644 --- a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java +++ b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java @@ -151,6 +151,7 @@ import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.VMTemplateDao; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.dao.VolumeDao; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; @@ -215,6 +216,8 @@ public class BackupManagerImpl extends ManagerBase implements BackupManager { @Inject private VolumeDao volumeDao; @Inject + private SnapshotManager snapshotManager; + @Inject private DataCenterDao dataCenterDao; @Inject private BackgroundPollManager backgroundPollManager; @@ -670,6 +673,15 @@ public String createVolumeInfoFromVolumes(List vmVolumes) { return new Gson().toJson(list.toArray(), Backup.VolumeInfo[].class); } + /** + * KVM file-based no-copy volume snapshots are part of the backing chains of the volumes: backups may add or replace files in those chains. + */ + protected void validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(VMInstanceVO vm, String operation) { + for (VolumeVO volume : volumeDao.findByInstance(vm.getId())) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, operation); + } + } + @Override @ActionEvent(eventType = EventTypes.EVENT_VM_BACKUP_OFFERING_ASSIGN, eventDescription = "assign Instance to Backup Offering", async = true) public boolean assignVMToBackupOffering(Long vmId, Long offeringId) { @@ -687,6 +699,8 @@ public boolean assignVMToBackupOffering(Long vmId, Long offeringId) { throw new CloudRuntimeException("Instance already is assigned to a backup offering, please remove the Instance from its previous offering"); } + validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(vm, "assign its Instance to a backup offering"); + final BackupOfferingVO offering = backupOfferingDao.findById(offeringId); if (offering == null) { throw new CloudRuntimeException("Provided backup offering does not exist"); @@ -1391,6 +1405,9 @@ protected void validateBackupVolumes(BackupVO backup, VMInstanceVO vm, BackupOff List backupVolumes = CollectionUtils.isEmpty(backup.getBackedUpVolumes()) ? vm.getBackupVolumeList() : backup.getBackedUpVolumes(); List vmVolumes = volumeDao.findByInstance(vm.getId()); + for (VolumeVO volume : vmVolumes) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "restore a backup onto it"); + } if (vmVolumes.size() != backupVolumes.size()) { throw new CloudRuntimeException("Unable to restore Instance with the current Backup as the Backup has different number of disks to the Instance"); } @@ -1657,6 +1674,7 @@ public boolean restoreBackupToVM(final Long backupId, final Long vmId, boolean q if (vm.getRemoved() != null) { throw new CloudRuntimeException("Instance with ID " + backup.getVmId() + " couldn't be found."); } + validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(vm, "restore a backup onto it"); if (!vm.getState().equals(VirtualMachine.State.Stopped)) { throw new CloudRuntimeException("The Instance should be in stopped state"); } diff --git a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java index 401b12ebbf46..ac1f45b4ddc5 100644 --- a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java +++ b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java @@ -694,6 +694,24 @@ public void attachDiskWithEncryptEnabledOfferingOnKVM() throws NoSuchFieldExcept } } + // Negative test - a volume with KVM file-based no-copy snapshots cannot be attached to an Instance with a backup offering + @Test + public void attachVolumeWithKvmFileBasedNoCopySnapshotsToVmWithBackupOfferingIsRefused() { + UserVmVO kvmVmWithBackupOffering = new UserVmVO(4L, "vm", "vm", 1, HypervisorType.KVM, 1L, false, false, 1L, 1L, 1, 1L, null, null, null, "vm"); + kvmVmWithBackupOffering.setState(State.Running); + kvmVmWithBackupOffering.setDataCenterId(1L); + kvmVmWithBackupOffering.setBackupOfferingId(1L); + when(userVmDaoMock.findById(4L)).thenReturn(kvmVmWithBackupOffering); + Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManagerMock) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(Mockito.any(), Mockito.eq("attach it to an Instance with a backup offering")); + + try (MockedConstruction mockCheckedReservation = Mockito.mockConstruction(CheckedReservation.class)) { + InvalidParameterValueException e = Assert.assertThrows(InvalidParameterValueException.class, + () -> volumeApiServiceImpl.attachVolumeToVM(4L, 10L, 1L, false, false)); + Assert.assertEquals("has KVM file-based no-copy snapshots", e.getMessage()); + } + } + // volume not Ready @Test(expected = InvalidParameterValueException.class) public void testTakeSnapshotF1() throws ResourceAllocationException { diff --git a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java index 3f8d55977504..06a159f2e749 100644 --- a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java +++ b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java @@ -121,6 +121,7 @@ import com.cloud.storage.Volume; import com.cloud.storage.VolumeApiService; import com.cloud.storage.VolumeVO; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.VMTemplateDao; @@ -177,6 +178,8 @@ public class BackupManagerTest { @Mock VolumeDao volumeDao; + @Mock + SnapshotManager snapshotManager; @Mock VMInstanceDao vmInstanceDao; @@ -1452,6 +1455,25 @@ public void testAssignVMToBackupOffering() { } } + @Test + public void testAssignVMToBackupOfferingRefusedWhenAVolumeHasKvmFileBasedNoCopySnapshots() { + Long vmId = 1L; + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(vmId); + overrideBackupFrameworkConfigValue(); + when(vmInstanceDao.findById(vmId)).thenReturn(vm); + when(vm.getState()).thenReturn(VirtualMachine.State.Running); + when(vm.getDataCenterId()).thenReturn(1L); + when(vm.getBackupOfferingId()).thenReturn(null); + VolumeVO volume = mock(VolumeVO.class); + when(volumeDao.findByInstance(vmId)).thenReturn(List.of(volume)); + Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "assign its Instance to a backup offering"); + + org.junit.Assert.assertThrows(InvalidParameterValueException.class, () -> backupManager.assignVMToBackupOffering(vmId, 2L)); + verify(backupOfferingDao, never()).findById(Mockito.anyLong()); + } + @Test public void testRemoveVMFromBackupOffering() { Long vmId = 1L; From af6af900c1f65a80f782a116c8be66232cb94187 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:18:58 +0000 Subject: [PATCH 03/12] Address own review: start/HA vs snapshot operations, implicit migration, lost answers, KBOSS restore, unmanage - VM start refuses volumes in Snapshotting/RevertSnapshotting (VolumeOrchestrator): deleting or reverting a snapshot of a stopped Instance is not serialized with its start. Revert also requires the Instance to be Stopped. - Every volume move path in VolumeServiceImpl (copy, migrate, migrate with the Instance, including the implicit migrations at start and HA) refuses volumes with no-copy snapshots. - The merge command waits as long as the agent's merge timeout. Without an answer, take (running Instance), revert and delete keep the volume reserved and say what to check; a failed merge marks the snapshot as not revertible. - Take marks the snapshot before working on storage and re-reads the backup offering; assigning an offering re-checks after committing and undoes itself if a no-copy snapshot appeared. The restore check also covers KBOSS. - Unmanaging a volume with no-copy snapshots is refused, and frozen files are only deleted for expunged volumes. Co-Authored-By: Claude Opus 5.5 --- .../orchestration/VolumeOrchestrator.java | 13 ++ .../orchestration/VolumeOrchestratorTest.java | 17 +++ .../KvmFileBasedNoCopySnapshotStrategy.java | 106 +++++++++++++--- ...vmFileBasedNoCopySnapshotStrategyTest.java | 118 +++++++++++++++++- .../storage/volume/VolumeServiceImpl.java | 40 ++++++ .../storage/volume/VolumeServiceTest.java | 15 +++ .../cloudstack/backup/BackupManagerImpl.java | 37 +++++- .../VolumeImportUnmanageManagerImpl.java | 5 + .../cloudstack/backup/BackupManagerTest.java | 32 +++++ .../VolumeImportUnmanageManagerImplTest.java | 16 +++ 10 files changed, 374 insertions(+), 25 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 2b9b41b6e8ac..2a454d55d95a 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1887,12 +1887,25 @@ private static class VolumeTask { } } + /** + * A snapshot operation that is not serialized with the Instance (e.g. deleting or reverting a snapshot of a stopped Instance) may be replacing or merging the + * files of the volume: starting the Instance meanwhile would open files that are about to be removed. + */ + protected void checkVolumeIsNotUnderSnapshotOperation(VolumeVO vol, String volToString) { + if (Volume.State.Snapshotting.equals(vol.getState()) || Volume.State.RevertSnapshotting.equals(vol.getState())) { + throw new CloudRuntimeException(String.format("Volume %s is in state %s: the Instance cannot be started until the snapshot operation on it finishes.", + volToString, vol.getState())); + } + } + private List getTasks(List vols, Map destVols, VirtualMachineProfile vm) throws StorageUnavailableException { boolean recreate = RecreatableSystemVmEnabled.value(); List tasks = new ArrayList(); for (VolumeVO vol : vols) { String volToString = getReflectOnlySelectedFields(vol); + checkVolumeIsNotUnderSnapshotOperation(vol, volToString); + StoragePoolVO assignedPool = null; if (destVols != null) { StoragePool pool = destVols.get(vol); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 04e80212e8cc..2231c9d7d0e4 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -970,4 +970,21 @@ private Field findField(Class clazz, String fieldName) { return null; } + @Test + public void checkVolumeIsNotUnderSnapshotOperationRefusesReservedVolumes() { + for (Volume.State state : List.of(Volume.State.Snapshotting, Volume.State.RevertSnapshotting)) { + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getState()).thenReturn(state); + Assert.assertThrows(CloudRuntimeException.class, () -> volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol")); + } + } + + @Test + public void checkVolumeIsNotUnderSnapshotOperationAllowsOtherStates() { + for (Volume.State state : List.of(Volume.State.Ready, Volume.State.Allocated, Volume.State.Creating)) { + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getState()).thenReturn(state); + volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol"); + } + } } diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index fec94ac0a565..326006be7bcc 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -100,6 +100,23 @@ public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { */ protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE = "kvmFileBasedNoCopySnapshotSequence"; + /** + * Snapshot detail set when deleting the snapshot failed after the merge may have started: its file may already hold data of its child, so it is no longer a + * valid point in time and cannot be reverted (deleting it again completes the merge). + */ + protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE = "kvmFileBasedNoCopySnapshotMergeIncomplete"; + + /** + * Snapshot detail holding the new volume file of a take whose outcome is unknown (no answer from the host for a running Instance). + */ + protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH = "kvmFileBasedNoCopySnapshotPendingVolumePath"; + + /** + * Wait for the merge command: at least the agent's own merge timeout (qcow2.delta.merge.timeout, 72 hours by default), so that a long merge is not taken for + * a lost answer. + */ + protected static final int MERGE_COMMAND_WAIT_SECONDS = 60 * 60 * 72 + 10 * 60; + protected static final Set SUPPORTED_POOL_TYPES = Set.of(Storage.StoragePoolType.NetworkFilesystem, Storage.StoragePoolType.SharedMountPoint, Storage.StoragePoolType.Filesystem); @@ -304,8 +321,6 @@ public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) { protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { VolumeInfo volumeInfo = snapshot.getBaseVolume(); - VMInstanceVO vm = getAttachedVm(volumeInfo); - boolean vmRunning = isVmRunning(vm); logger.info("Taking KVM file-based no-copy snapshot [{}] of volume [{}].", snapshot.getUuid(), volumeInfo.getUuid()); @@ -314,9 +329,20 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { SnapshotObject snapshotOnPrimary = null; boolean succeeded = false; + boolean keepVolumeReserved = false; try { - // Computed while the volume is reserved: the position of the snapshot in the backing chain, which follows the order of the takes and not the order of - // the snapshot ids (allocated before the work is queued). + // Marks the snapshot before anything is done on storage, so that operations refused while a volume has no-copy snapshots (e.g. assigning a backup + // offering) also see a take in progress. Then re-checks what such an operation could have changed concurrently. + snapshotDetailsDao.addDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, Boolean.TRUE.toString(), false); + VMInstanceVO vm = getAttachedVm(volumeInfo); + if (vm != null && vm.getBackupOfferingId() != null) { + throw new CloudRuntimeException(String.format("Instance [%s] was assigned to a backup offering while KVM file-based no-copy snapshot [%s] was being " + + "taken; the snapshot is not taken.", vm.getUuid(), snapshot.getUuid())); + } + boolean vmRunning = isVmRunning(vm); + + // The position of the snapshot in the backing chain, which follows the order of the takes and not the order of the snapshot ids (allocated before + // the work is queued). Computed while the volume is reserved. long sequence = listNoCopySnapshotsOfVolume(volumeInfo.getId()).stream().mapToLong(this::getChainSequence).max().orElse(0L) + 1; snapshotOnPrimary = createSnapshotOnPrimary(snapshot); VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); @@ -328,6 +354,15 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { List.of(new Pair<>(volumeTO, newVolumePath)), null, vmRunning ? VirtualMachine.State.Running : VirtualMachine.State.Stopped, false); Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + if (answer == null && vmRunning) { + // The running Instance may already be writing to the new delta: releasing the volume with its old path would make its next start lose those writes. + keepVolumeReserved = true; + snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, newVolumePath, false); + throw new CloudRuntimeException(String.format("No answer from the host while taking KVM file-based no-copy snapshot [%s] of volume [%s] of running " + + "Instance [%s]. The volume stays in state [%s] until an administrator checks whether the Instance uses the new file [%s] (then sets it as the " + + "volume path) or still the file [%s], and then sets the volume state back to Ready.", snapshot.getUuid(), volumeInfo.getUuid(), vm.getUuid(), + Volume.State.Snapshotting, newVolumePath, oldVolumePath)); + } if (!(answer instanceof CreateDiskOnlyVmSnapshotAnswer) || !answer.getResult()) { throw new CloudRuntimeException(String.format("Failed to take KVM file-based no-copy snapshot [%s] of volume [%s] due to [%s].", snapshot.getUuid(), volumeInfo.getUuid(), getAnswerDetails(answer))); @@ -348,7 +383,6 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { snapshotOnPrimary.processEvent(Snapshot.Event.OperationSucceeded); snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false); - snapshotDetailsDao.addDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, Boolean.TRUE.toString(), false); logger.info("Took KVM file-based no-copy snapshot [{}] of volume [{}]: the snapshot is [{}] and the volume is now on [{}].", snapshot.getUuid(), volumeInfo.getUuid(), oldVolumePath, newVolumePath); @@ -357,9 +391,13 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { } catch (NoTransitionException e) { throw new CloudRuntimeException(String.format("Failed to update the state of snapshot [%s].", snapshot.getUuid()), e); } finally { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + if (!keepVolumeReserved) { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + } if (!succeeded && snapshotOnPrimary != null) { markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); + } else if (!succeeded) { + snapshotDetailsDao.removeDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); } } } @@ -407,9 +445,15 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { // Reserve the volume before reading its chain and paths, so that no other snapshot operation can change them underneath. reserveVolume(volumeInfo, Volume.Event.RevertSnapshotRequested, snapshotVO); boolean succeeded = false; + boolean keepVolumeReserved = false; try { volumeInfo = volumeDataFactory.getVolume(snapshotVO.getVolumeId()); + if (snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE) != null) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be reverted: a previous delete of it failed during the merge, so its file " + + "may already hold newer data. Delete it again to complete the merge.", snapshotVO.getUuid())); + } + List chain = listNoCopySnapshotsOfVolume(volumeInfo.getId()); if (chain.isEmpty() || chain.get(chain.size() - 1).getId() != snapshotVO.getId()) { throw new InvalidParameterValueException(String.format("Only the most recent KVM file-based no-copy snapshot of volume [%s] can be reverted. Delete the " + @@ -417,9 +461,9 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { } VMInstanceVO vm = getAttachedVm(volumeInfo); - if (isVmRunning(vm)) { - throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s].", vm.getUuid(), - volumeInfo.getUuid(), snapshotVO.getUuid())); + if (vm != null && !VirtualMachine.State.Stopped.equals(vm.getState())) { + throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s]; it is [%s].", vm.getUuid(), + volumeInfo.getUuid(), snapshotVO.getUuid(), vm.getState())); } logger.info("Reverting volume [{}] to KVM file-based no-copy snapshot [{}].", volumeInfo.getUuid(), snapshotVO.getUuid()); @@ -429,6 +473,14 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { vm != null ? vm.getUuid() : null, false, null); Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + if (answer == null) { + // The host may have replaced the file of the volume already: releasing the volume with its old path could start the Instance on a deleted file. + keepVolumeReserved = true; + throw new CloudRuntimeException(String.format("No answer from the host while reverting volume [%s] to snapshot [%s]. The volume stays in state [%s] " + + "until an administrator checks which file of its backing chain is its current one (a new file backed by [%s] if the revert happened), sets it as " + + "the volume path and sets the volume state back to Ready.", volumeInfo.getUuid(), snapshotVO.getUuid(), Volume.State.RevertSnapshotting, + snapshotTO.getPath())); + } if (!(answer instanceof RevertDiskOnlyVmSnapshotAnswer) || !answer.getResult() || CollectionUtils.isEmpty(((RevertDiskOnlyVmSnapshotAnswer) answer).getVolumeObjectTos())) { throw new CloudRuntimeException(String.format("Failed to revert volume [%s] to snapshot [%s] due to [%s].", volumeInfo.getUuid(), snapshotVO.getUuid(), @@ -445,7 +497,9 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { succeeded = true; return true; } finally { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + if (!keepVolumeReserved) { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + } } } @@ -497,7 +551,14 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { return true; } - if (volumeVO == null || volumeVO.getRemoved() != null || Volume.State.Expunged.equals(volumeVO.getState())) { + if (volumeVO == null || (volumeVO.getRemoved() != null && !Volume.State.Expunged.equals(volumeVO.getState()))) { + // The volume row is gone, or the volume was removed without being expunged (e.g. unmanaged): its files are not CloudStack's to delete. + logger.debug("The volume of KVM file-based no-copy snapshot [{}] is no longer managed; only the snapshot metadata will be removed.", snapshotVO.getUuid()); + removeSnapshotMetadata(snapshotVO); + return true; + } + + if (Volume.State.Expunged.equals(volumeVO.getState())) { // The active file of the volume is gone; its frozen files are not, as nothing else references them (no-copy snapshots cannot be used to create // volumes or templates, and template files are never one of them). deleteFrozenFileOfExpungedVolume(snapshotVO, snapshotStoreRef); @@ -509,6 +570,7 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { // Reserve the volume before reading its chain and paths, so that no other snapshot operation can change them underneath. reserveVolume(volumeInfo, Volume.Event.SnapshotRequested, snapshotVO); boolean succeeded = false; + boolean keepVolumeReserved = false; try { volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); volumeVO = volumeDao.findById(volumeVO.getId()); @@ -536,17 +598,33 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { deltaMergeTree.getChild().getPath()); MergeDiskOnlyVmSnapshotCommand command = new MergeDiskOnlyVmSnapshotCommand(List.of(deltaMergeTree), vmRunning, vm != null ? vm.getInstanceName() : null); + command.setWait(MERGE_COMMAND_WAIT_SECONDS); Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); if (answer == null || !answer.getResult()) { - throw new CloudRuntimeException(String.format("Failed to delete KVM file-based no-copy snapshot [%s] of volume [%s] due to [%s].", snapshotVO.getUuid(), - volumeVO.getUuid(), getAnswerDetails(answer))); + // The merge may have started: the file of this snapshot may already hold data of its child, so it is no longer a valid point in time. + snapshotDetailsDao.addDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, Boolean.TRUE.toString(), false); + } + if (answer == null) { + // The host may still complete the merge and delete the child file: releasing the volume could leave it pointing to a deleted file. + keepVolumeReserved = true; + throw new CloudRuntimeException(String.format("No answer from the host while deleting KVM file-based no-copy snapshot [%s] of volume [%s] (merging [%s] " + + "into [%s]). The volume stays in state [%s] until an administrator checks whether [%s] still exists: if it does not, set [%s] as the path of %s. " + + "Then set the volume state back to Ready and delete the snapshot again.", snapshotVO.getUuid(), volumeVO.getUuid(), + deltaMergeTree.getChild().getPath(), parentTO.getPath(), Volume.State.Snapshotting, deltaMergeTree.getChild().getPath(), parentTO.getPath(), + childSnapshot == null ? "the volume" : "snapshot " + childSnapshot.getUuid())); + } + if (!answer.getResult()) { + throw new CloudRuntimeException(String.format("Failed to delete KVM file-based no-copy snapshot [%s] of volume [%s] due to [%s]. The snapshot can no " + + "longer be reverted; delete it again to complete the merge.", snapshotVO.getUuid(), volumeVO.getUuid(), getAnswerDetails(answer))); } updateMetadataAfterMerge(snapshotVO, snapshotStoreRef, childSnapshot, volumeVO); succeeded = true; return true; } finally { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + if (!keepVolumeReserved) { + volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + } } } diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 000ad85297b0..a0e8e4cce921 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -464,7 +464,8 @@ public void takeSnapshotFailureKeepsVolumePath() throws Exception { assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); verify(volumeVO, never()).setPath(any()); - verify(snapshotDetailsDao, never()).addDetail(anyLong(), any(), any(), Mockito.anyBoolean()); + verify(snapshotDetailsDao, never()).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE), any(), + Mockito.anyBoolean()); verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); verify(snapshotOnPrimary).processEvent(Snapshot.Event.OperationFailed); verify(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); @@ -603,8 +604,9 @@ private Command deleteSnapshotOfGoneVolumeAndCaptureCommand() { } @Test - public void deleteSnapshotOfRemovedVolumeDeletesItsFrozenFile() { + public void deleteSnapshotOfExpungedVolumeDeletesItsFrozenFile() { mockChain(SNAPSHOT_ID); + when(volumeVO.getState()).thenReturn(Volume.State.Expunged); when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); DeleteDiskOnlyVmSnapshotCommand command = (DeleteDiskOnlyVmSnapshotCommand) deleteSnapshotOfGoneVolumeAndCaptureCommand(); @@ -616,18 +618,21 @@ public void deleteSnapshotOfRemovedVolumeDeletesItsFrozenFile() { } @Test - public void deleteSnapshotOfExpungedVolumeDeletesItsFrozenFile() { + public void deleteSnapshotOfRemovedButNotExpungedVolumeOnlyRemovesMetadata() { mockChain(SNAPSHOT_ID); - when(volumeVO.getState()).thenReturn(Volume.State.Expunged); + when(volumeVO.getState()).thenReturn(Volume.State.Destroy); // e.g. unmanaged: the files stay with the unmanaged disk + when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); - assertTrue(deleteSnapshotOfGoneVolumeAndCaptureCommand() instanceof DeleteDiskOnlyVmSnapshotCommand); + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); verify(snapshotVO).setState(Snapshot.State.Destroyed); } @Test public void deleteSnapshotOfExpungedVolumeKeepsMetadataWhenTheFileCannotBeDeleted() { mockChain(SNAPSHOT_ID); - when(volumeVO.getRemoved()).thenReturn(new java.util.Date()); + when(volumeVO.getState()).thenReturn(Volume.State.Expunged); EndPoint endPoint = mock(EndPoint.class); when(endPoint.getId()).thenReturn(HOST_ID); when(endPointSelector.select(any(SnapshotInfo.class))).thenReturn(endPoint); @@ -787,6 +792,107 @@ public void deleteSnapshotWhileVmIsStartingIsRefused() { verify(strategy, never()).sendToHost(anyLong(), any()); } + // unknown outcomes and partial merges + + @Test + public void takeSnapshotAbortsWhenABackupOfferingWasAssignedMeanwhile() { + attachVolumeToVm(); + when(vm.getBackupOfferingId()).thenReturn(1L); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, "true", false); + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); + verify(strategy, never()).createSnapshotOnPrimary(any()); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void takeSnapshotOfRunningVmWithoutAnswerKeepsTheVolumeReserved() { + attachVolumeToVm(); + mockSnapshotOnPrimary(); + doReturn(null).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeVO, never()).setPath(any()); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationSucceeded); + verify(snapshotDetailsDao).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH), any(), + eq(false)); + } + + @Test + public void takeSnapshotOfDetachedVolumeWithoutAnswerReleasesTheVolume() { + mockSnapshotOnPrimary(); + doReturn(null).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void deleteSendsTheMergeWithTheAgentMergeTimeoutAsWait() { + mockChain(SNAPSHOT_ID); + assertEquals(KvmFileBasedNoCopySnapshotStrategy.MERGE_COMMAND_WAIT_SECONDS, deleteAndCaptureMerge().getWait()); + } + + @Test + public void failedMergeMarksTheSnapshotAsNotRevertible() { + mockChain(SNAPSHOT_ID); + doReturn(new Answer(null, false, "blockcommit failed")).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, "true", false); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void mergeWithoutAnswerKeepsTheVolumeReserved() { + mockChain(SNAPSHOT_ID); + doReturn(null).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, "true", false); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeVO, never()).setPath(any()); + } + + @Test + public void revertOfAPartiallyMergedSnapshotIsRefused() { + mockChain(SNAPSHOT_ID); + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE)) + .thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, "true", false)); + + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void revertWithoutAnswerKeepsTheVolumeReserved() { + mockChain(SNAPSHOT_ID); + doReturn(null).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeVO, never()).setPath(any()); + } + + @Test + public void revertWhileTheVmIsStartingIsRefused() { + mockChain(SNAPSHOT_ID); + attachVolumeToVm(); + when(vm.getState()).thenReturn(VirtualMachine.State.Starting); + + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + @Test public void backupSnapshotIsRefused() { assertThrows(CloudRuntimeException.class, () -> strategy.backupSnapshot(snapshotInfo)); diff --git a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java index 05bbf13c9745..cc8947b76438 100644 --- a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java +++ b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java @@ -1947,6 +1947,13 @@ public AsyncCallFuture copyVolume(VolumeInfo srcVolume, DataSto AsyncCallFuture future = new AsyncCallFuture<>(); VolumeApiResult res = new VolumeApiResult(srcVolume); try { + if (snapshotMgr.volumeHasKvmFileBasedNoCopySnapshots(srcVolume.getId())) { + String msg = noCopySnapshotsMoveError(srcVolume); + logger.debug(msg); + res.setResult(msg); + future.complete(res); + return future; + } if (!snapshotMgr.canOperateOnVolume(srcVolume)) { logger.debug("There are snapshots creating on this volume, can not move this volume"); @@ -2098,6 +2105,13 @@ private AsyncCallFuture copyManagedVolume(VolumeInfo srcVolume, AsyncCallFuture future = new AsyncCallFuture<>(); VolumeApiResult res = new VolumeApiResult(srcVolume); try { + if (snapshotMgr.volumeHasKvmFileBasedNoCopySnapshots(srcVolume.getId())) { + String msg = noCopySnapshotsMoveError(srcVolume); + logger.debug(msg); + res.setResult(msg); + future.complete(res); + return future; + } if (!snapshotMgr.canOperateOnVolume(srcVolume)) { logger.debug("There are snapshots creating for this volume, can not move this volume"); res.setResult("There are snapshots creating for this volume, can not move this volume"); @@ -2306,11 +2320,27 @@ public MigrateVolumeContext(AsyncCompletionCallback callback, AsyncCallFuture } } + /** + * Moving a volume flattens it into a new file, which would orphan its KVM file-based no-copy snapshots (they are files of its backing chain). This covers + * the implicit migrations too, e.g. when an Instance is started or restarted by HA on another storage pool. + */ + protected String noCopySnapshotsMoveError(VolumeInfo volume) { + return String.format("Volume [%s] has KVM file-based no-copy snapshots, which are part of its backing chain; delete them before moving the volume.", + volume.getUuid()); + } + @Override public AsyncCallFuture migrateVolume(VolumeInfo srcVolume, DataStore destStore) { AsyncCallFuture future = new AsyncCallFuture<>(); VolumeApiResult res = new VolumeApiResult(srcVolume); try { + if (snapshotMgr.volumeHasKvmFileBasedNoCopySnapshots(srcVolume.getId())) { + String msg = noCopySnapshotsMoveError(srcVolume); + logger.debug(msg); + res.setResult(msg); + future.complete(res); + return future; + } if (!snapshotMgr.canOperateOnVolume(srcVolume)) { logger.debug("Snapshots are being created on this volume. This volume cannot be migrated now."); res.setResult("Snapshots are being created on this volume. This volume cannot be migrated now."); @@ -2382,6 +2412,16 @@ public AsyncCallFuture migrateVolumes(Map List volumesMigrating = new ArrayList<>(); for (Map.Entry entry : volumeMap.entrySet()) { VolumeInfo volume = entry.getKey(); + if (snapshotMgr.volumeHasKvmFileBasedNoCopySnapshots(volume.getId())) { + String msg = noCopySnapshotsMoveError(volume); + logger.debug(msg); + res.setResult(msg); + future.complete(res); + for (VolumeInfo volumeMigrating : volumesMigrating) { + volumeMigrating.processEvent(Event.OperationFailed); + } + return future; + } if (!snapshotMgr.canOperateOnVolume(volume)) { logger.debug("Snapshots are being created on a volume. Volumes cannot be migrated now."); res.setResult("Snapshots are being created on a volume. Volumes cannot be migrated now."); diff --git a/engine/storage/volume/src/test/java/org/apache/cloudstack/storage/volume/VolumeServiceTest.java b/engine/storage/volume/src/test/java/org/apache/cloudstack/storage/volume/VolumeServiceTest.java index 57d10dd800a1..5ef3c8689a3d 100644 --- a/engine/storage/volume/src/test/java/org/apache/cloudstack/storage/volume/VolumeServiceTest.java +++ b/engine/storage/volume/src/test/java/org/apache/cloudstack/storage/volume/VolumeServiceTest.java @@ -359,4 +359,19 @@ private void prepareOfferingsForEncryptionValidation(long diskOfferingId, boolea Mockito.when(diskOfferingDaoMock.findByIdIncludingRemoved(diskOfferingId)).thenReturn(diskOffering); Mockito.when(diskOfferingDaoMock.findById(diskOfferingId)).thenReturn(diskOffering); } + + @Test + public void migrateVolumeIsRefusedWhenTheVolumeHasKvmFileBasedNoCopySnapshots() throws Exception { + VolumeInfo volume = Mockito.mock(VolumeInfo.class); + Mockito.when(volume.getId()).thenReturn(42L); + Mockito.when(volume.getUuid()).thenReturn("volume-uuid"); + Mockito.when(snapshotManagerMock.volumeHasKvmFileBasedNoCopySnapshots(42L)).thenReturn(true); + + org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult result = volumeServiceImplSpy.migrateVolume(volume, + Mockito.mock(org.apache.cloudstack.engine.subsystem.api.storage.DataStore.class)).get(); + + Assert.assertTrue(result.isFailed()); + Assert.assertTrue(result.getResult().contains("no-copy snapshots")); + Mockito.verify(volume, Mockito.never()).processEvent(Mockito.any()); + } } diff --git a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java index cbc99b2304d0..53e287e457b0 100644 --- a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java +++ b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java @@ -717,7 +717,33 @@ public boolean assignVMToBackupOffering(Long vmId, Long offeringId) { throw new CloudRuntimeException("Failed to get the backup provider for the zone, please contact the administrator"); } - return transactionAssignVMToBackupOffering(vm, offering, backupProvider) != null; + VMInstanceVO assignedVm = transactionAssignVMToBackupOffering(vm, offering, backupProvider); + if (assignedVm == null) { + return false; + } + undoAssignmentIfNoCopySnapshotsAppeared(assignedVm, offering, backupProvider); + return true; + } + + /** + * A KVM file-based no-copy snapshot take marks its snapshot before working on storage and then re-reads the backup offering of the Instance. Checking for + * such marks again once the assignment is committed means that at least one of two concurrent operations sees the other: when it is this one, the + * assignment is undone. + */ + protected void undoAssignmentIfNoCopySnapshotsAppeared(VMInstanceVO vm, BackupOfferingVO offering, BackupProvider backupProvider) { + try { + validateVmVolumesHaveNoKvmFileBasedNoCopySnapshots(vm, "assign its Instance to a backup offering"); + } catch (InvalidParameterValueException e) { + logger.warn("Undoing the assignment of Instance [{}] to backup offering [{}], as a KVM file-based no-copy snapshot was taken concurrently.", vm.getUuid(), + offering.getUuid()); + backupProvider.removeVMFromBackupOffering(vm); + vm.setBackupOfferingId(null); + vm.setBackupVolumes(null); + vm.setBackupExternalId(null); + vmInstanceDao.update(vm.getId(), vm); + publishBackupOfferingUsageRemoved(vm, offering.getId()); + throw e; + } } private VMInstanceVO transactionAssignVMToBackupOffering(VMInstanceVO vm, BackupOfferingVO offering, BackupProvider backupProvider) { @@ -1397,6 +1423,11 @@ private void updateStates(VMInstanceVO vm, BackupProvider backupProvider, boolea } protected void validateBackupVolumes(BackupVO backup, VMInstanceVO vm, BackupOffering offering) { + // Every provider restores into the backing chains of the volumes, which their KVM file-based no-copy snapshots are part of. + List vmVolumes = volumeDao.findByInstance(vm.getId()); + for (VolumeVO volume : vmVolumes) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "restore a backup onto it"); + } BackupProvider backupProvider = getBackupProvider(offering.getProvider()); if (KBOSS_BACKUP_PROVIDER.equals(backupProvider.getName())) { return; @@ -1404,10 +1435,6 @@ protected void validateBackupVolumes(BackupVO backup, VMInstanceVO vm, BackupOff // This is done to handle historic backups if any with Veeam / Networker plugins List backupVolumes = CollectionUtils.isEmpty(backup.getBackedUpVolumes()) ? vm.getBackupVolumeList() : backup.getBackedUpVolumes(); - List vmVolumes = volumeDao.findByInstance(vm.getId()); - for (VolumeVO volume : vmVolumes) { - snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "restore a backup onto it"); - } if (vmVolumes.size() != backupVolumes.size()) { throw new CloudRuntimeException("Unable to restore Instance with the current Backup as the Backup has different number of disks to the Instance"); } diff --git a/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java b/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java index 3d66c1da5c19..166ac966c7e4 100644 --- a/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java +++ b/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java @@ -36,6 +36,7 @@ import com.cloud.hypervisor.Hypervisor; import com.cloud.offering.DiskOffering; import com.cloud.resourcelimit.ReservationHelper; +import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.DataStoreRole; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.Storage; @@ -125,6 +126,8 @@ public class VolumeImportUnmanageManagerImpl implements VolumeImportUnmanageServ @Inject private SnapshotDataStoreDao snapshotDataStoreDao; @Inject + private SnapshotManager snapshotManager; + @Inject private DataStoreManager dataStoreManager; static final String DEFAULT_DISK_OFFERING_NAME = "Default Custom Offering for Volume Import"; @@ -572,6 +575,8 @@ private VolumeVO checkIfVolumeCanBeUnmanaged(long volumeId) { if (volumeVO.getAttached() != null || volumeVO.getInstanceId() != null) { logFailureAndThrowException(String.format("Volume %s is attached to VM (ID: %s)", volumeVO, volumeVO.getInstanceId())); } + // The unmanaged file would keep the frozen files of KVM file-based no-copy snapshots as its backing chain. + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volumeVO, "unmanage it"); return volumeVO; } diff --git a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java index 06a159f2e749..f8e1e3c2312a 100644 --- a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java +++ b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java @@ -1474,6 +1474,38 @@ public void testAssignVMToBackupOfferingRefusedWhenAVolumeHasKvmFileBasedNoCopyS verify(backupOfferingDao, never()).findById(Mockito.anyLong()); } + @Test + public void testUndoAssignmentWhenANoCopySnapshotAppearedConcurrently() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(1L); + when(vm.getUuid()).thenReturn("vm-uuid"); + BackupOfferingVO offering = mock(BackupOfferingVO.class); + when(offering.getId()).thenReturn(2L); + VolumeVO volume = mock(VolumeVO.class); + when(volumeDao.findByInstance(1L)).thenReturn(List.of(volume)); + Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "assign its Instance to a backup offering"); + + try (MockedStatic ignored = Mockito.mockStatic(UsageEventUtils.class)) { + org.junit.Assert.assertThrows(InvalidParameterValueException.class, () -> backupManager.undoAssignmentIfNoCopySnapshotsAppeared(vm, offering, backupProvider)); + } + + verify(backupProvider).removeVMFromBackupOffering(vm); + verify(vm).setBackupOfferingId(null); + verify(vmInstanceDao).update(1L, vm); + } + + @Test + public void testAssignmentIsKeptWhenNoNoCopySnapshotAppeared() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(1L); + when(volumeDao.findByInstance(1L)).thenReturn(List.of(mock(VolumeVO.class))); + + backupManager.undoAssignmentIfNoCopySnapshotsAppeared(vm, mock(BackupOfferingVO.class), backupProvider); + + verify(backupProvider, never()).removeVMFromBackupOffering(any()); + } + @Test public void testRemoveVMFromBackupOffering() { Long vmId = 1L; diff --git a/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java b/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java index 414dd15344b3..776b5be8462e 100644 --- a/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java +++ b/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java @@ -44,6 +44,8 @@ import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplatePoolDao; import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.snapshot.SnapshotManager; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -122,6 +124,8 @@ public class VolumeImportUnmanageManagerImplTest { @Mock private VolumeDao volumeDao; @Mock + private SnapshotManager snapshotManager; + @Mock private PrimaryDataStoreDao primaryDataStoreDao; @Mock private StoragePoolHostDao storagePoolHostDao; @@ -484,6 +488,18 @@ public void testUnmanageVolumeNotifiesStorageDriverOfUnmanage() { verify(driver).volumeManagementChanged(storagePoolVO, volumeVO, false); } + @Test + public void testUnmanageVolumeWithKvmFileBasedNoCopySnapshotsIsRefused() { + when(volumeVO.getState()).thenReturn(Volume.State.Ready); + when(volumeVO.getInstanceId()).thenReturn(null); + Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volumeVO, "unmanage it"); + + Assert.assertThrows(InvalidParameterValueException.class, () -> volumeImportUnmanageManager.unmanageVolume(volumeId)); + + verify(volumeDao, Mockito.never()).update(Mockito.anyLong(), any()); + } + @Test public void testUnmanageVolumeNotExist() { try { From 2860d5f72135a7612d2cc962fa160ece0fdb1167 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:47:22 +0000 Subject: [PATCH 04/12] KVM no-copy snapshots: harden take, delete, attach and cleanup paths - Record the pending volume path before the host acts, and never mark a snapshot as failed once the host has moved the volume onto its new file. - Marking a snapshot as failed can no longer throw from the finally block. - Re-read the snapshot under its lock, so a concurrent second delete fails. - Skip no-copy snapshots in the Error-snapshot cleanup and in the volume cleanup of failed snapshot jobs at management server start. - Refuse to start an Instance only while a volume with no-copy snapshots is reserved by a snapshot operation. - Volume import also matches pool-relative snapshot paths. - Refuse to attach a volume with no-copy snapshots to an Instance that is not stopped, checked again in the attach job. - The Instance snapshot job checks the volumes again and removes the allocated Instance snapshot if one now has no-copy snapshots. Co-Authored-By: Claude Opus 5.5 --- .../main/java/com/cloud/storage/Snapshot.java | 5 ++ .../orchestration/VolumeOrchestrator.java | 27 ++++++-- .../orchestration/VolumeOrchestratorTest.java | 61 ++++++++++++++++- .../KvmFileBasedNoCopySnapshotStrategy.java | 40 ++++++++--- ...vmFileBasedNoCopySnapshotStrategyTest.java | 66 +++++++++++++++++++ .../com/cloud/storage/StorageManagerImpl.java | 12 +++- .../cloud/storage/VolumeApiServiceImpl.java | 23 +++++-- .../storage/snapshot/SnapshotManager.java | 2 +- .../vm/snapshot/VMSnapshotManagerImpl.java | 29 ++++++-- .../VolumeImportUnmanageManagerImpl.java | 20 ++++-- .../cloud/storage/StorageManagerImplTest.java | 31 +++++++++ .../storage/VolumeApiServiceImplTest.java | 22 +++++++ .../vm/snapshot/VMSnapshotManagerTest.java | 17 +++++ .../VolumeImportUnmanageManagerImplTest.java | 13 ++++ 14 files changed, 336 insertions(+), 32 deletions(-) diff --git a/api/src/main/java/com/cloud/storage/Snapshot.java b/api/src/main/java/com/cloud/storage/Snapshot.java index c0a7b812ed9e..1a89ba1c71c1 100644 --- a/api/src/main/java/com/cloud/storage/Snapshot.java +++ b/api/src/main/java/com/cloud/storage/Snapshot.java @@ -25,6 +25,11 @@ import java.util.Date; public interface Snapshot extends ControlledEntity, Identity, InternalIdentity, StateObject { + /** + * Name of the snapshot detail that marks a KVM file-based no-copy volume snapshot, which is part of the backing chain of its volume. + */ + String KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL = "kvmFileBasedNoCopySnapshot"; + public enum Type { MANUAL, RECURRING, TEMPLATE, HOURLY, DAILY, WEEKLY, MONTHLY, GROUP, FROM_GROUP; private int max = 8; diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 2a454d55d95a..3ee1d4cdda07 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -156,6 +156,7 @@ import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.VMTemplateDetailsDao; import com.cloud.storage.dao.VolumeDao; @@ -228,6 +229,8 @@ public enum UserVmCloneType { @Inject protected SnapshotDao _snapshotDao; @Inject + protected SnapshotDetailsDao snapshotDetailsDao; + @Inject protected SnapshotDataStoreDao _snapshotDataStoreDao; @Inject protected ResourceLimitService _resourceLimitMgr; @@ -1888,11 +1891,11 @@ private static class VolumeTask { } /** - * A snapshot operation that is not serialized with the Instance (e.g. deleting or reverting a snapshot of a stopped Instance) may be replacing or merging the - * files of the volume: starting the Instance meanwhile would open files that are about to be removed. + * A KVM file-based no-copy snapshot operation that is not serialized with the Instance (deleting or reverting a snapshot of a stopped Instance) may be + * replacing or merging the files of the volume: starting the Instance meanwhile would open files that are about to be removed. */ protected void checkVolumeIsNotUnderSnapshotOperation(VolumeVO vol, String volToString) { - if (Volume.State.Snapshotting.equals(vol.getState()) || Volume.State.RevertSnapshotting.equals(vol.getState())) { + if ((Volume.State.Snapshotting.equals(vol.getState()) || Volume.State.RevertSnapshotting.equals(vol.getState())) && volumeHasKvmFileBasedNoCopySnapshots(vol.getId())) { throw new CloudRuntimeException(String.format("Volume %s is in state %s: the Instance cannot be started until the snapshot operation on it finishes.", volToString, vol.getState())); } @@ -2526,7 +2529,23 @@ private void cleanupVolumeDuringMigrationFailure(Long volumeId, Long destPoolId) } - private void cleanupVolumeDuringSnapshotFailure(Long volumeId, Long snapshotId) { + /** + * @return true if the volume has KVM file-based no-copy snapshots (including one being taken), which are part of its backing chain. + */ + protected boolean volumeHasKvmFileBasedNoCopySnapshots(long volumeId) { + return _snapshotDao.listByVolumeId(volumeId).stream() + .filter(snapshot -> !Snapshot.State.Destroyed.equals(snapshot.getState()) && !Snapshot.State.Error.equals(snapshot.getState())) + .anyMatch(snapshot -> snapshotDetailsDao.findDetail(snapshot.getId(), Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL) != null); + } + + protected void cleanupVolumeDuringSnapshotFailure(Long volumeId, Long snapshotId) { + if (snapshotId != null && snapshotDetailsDao.findDetail(snapshotId, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL) != null) { + // The outcome of a KVM file-based no-copy snapshot take is unknown: a running Instance may already be writing to the new file. Resetting the volume + // with its old path would make the next start lose those writes, so it is left for an administrator (see the snapshot details). + logger.warn("Not cleaning up volume [{}] after the failed KVM file-based no-copy snapshot [{}]: check which file of its backing chain is current " + + "(snapshot detail [kvmFileBasedNoCopySnapshotPendingVolumePath]), then set the volume path and state.", volumeId, snapshotId); + return; + } _snapshotSrv.cleanupVolumeDuringSnapshotFailure(volumeId, snapshotId); VolumeVO volume = _volsDao.findById(volumeId); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 2231c9d7d0e4..0b3659195a87 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -58,6 +58,12 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import com.cloud.storage.Snapshot; +import com.cloud.storage.SnapshotVO; +import com.cloud.storage.dao.SnapshotDetailsVO; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigKey; @@ -971,7 +977,8 @@ private Field findField(Class clazz, String fieldName) { } @Test - public void checkVolumeIsNotUnderSnapshotOperationRefusesReservedVolumes() { + public void checkVolumeIsNotUnderSnapshotOperationRefusesReservedVolumesWithKvmFileBasedNoCopySnapshots() { + Mockito.doReturn(true).when(volumeOrchestrator).volumeHasKvmFileBasedNoCopySnapshots(Mockito.anyLong()); for (Volume.State state : List.of(Volume.State.Snapshotting, Volume.State.RevertSnapshotting)) { VolumeVO volume = Mockito.mock(VolumeVO.class); Mockito.when(volume.getState()).thenReturn(state); @@ -979,6 +986,58 @@ public void checkVolumeIsNotUnderSnapshotOperationRefusesReservedVolumes() { } } + @Test + public void checkVolumeIsNotUnderSnapshotOperationAllowsReservedVolumesWithoutKvmFileBasedNoCopySnapshots() { + Mockito.doReturn(false).when(volumeOrchestrator).volumeHasKvmFileBasedNoCopySnapshots(Mockito.anyLong()); + for (Volume.State state : List.of(Volume.State.Snapshotting, Volume.State.RevertSnapshotting)) { + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getState()).thenReturn(state); + volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol"); + } + } + + @Test + public void volumeHasKvmFileBasedNoCopySnapshotsIgnoresDestroyedAndErrorSnapshots() { + SnapshotDao snapshotDao = Mockito.mock(SnapshotDao.class); + SnapshotDetailsDao snapshotDetailsDao = Mockito.mock(SnapshotDetailsDao.class); + volumeOrchestrator._snapshotDao = snapshotDao; + volumeOrchestrator.snapshotDetailsDao = snapshotDetailsDao; + List snapshots = new ArrayList<>(); + long id = 1; + for (Snapshot.State state : List.of(Snapshot.State.Destroyed, Snapshot.State.Error, Snapshot.State.BackedUp)) { + SnapshotVO snapshot = Mockito.mock(SnapshotVO.class); + Mockito.when(snapshot.getState()).thenReturn(state); + Mockito.lenient().when(snapshot.getId()).thenReturn(id++); + snapshots.add(snapshot); + } + Mockito.when(snapshotDao.listByVolumeId(1L)).thenReturn(snapshots); + + Assert.assertFalse(volumeOrchestrator.volumeHasKvmFileBasedNoCopySnapshots(1L)); + + Mockito.when(snapshotDetailsDao.findDetail(3L, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL)).thenReturn(Mockito.mock(SnapshotDetailsVO.class)); + Assert.assertTrue(volumeOrchestrator.volumeHasKvmFileBasedNoCopySnapshots(1L)); + Mockito.verify(snapshotDetailsDao, Mockito.never()).findDetail(1L, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL); + Mockito.verify(snapshotDetailsDao, Mockito.never()).findDetail(2L, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL); + } + + @Test + public void cleanupVolumeDuringSnapshotFailureLeavesVolumesOfKvmFileBasedNoCopySnapshotsAlone() { + SnapshotDetailsDao snapshotDetailsDao = Mockito.mock(SnapshotDetailsDao.class); + SnapshotService snapshotService = Mockito.mock(SnapshotService.class); + volumeOrchestrator.snapshotDetailsDao = snapshotDetailsDao; + volumeOrchestrator._snapshotSrv = snapshotService; + Mockito.when(snapshotDetailsDao.findDetail(2L, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL)).thenReturn(Mockito.mock(SnapshotDetailsVO.class)); + + volumeOrchestrator.cleanupVolumeDuringSnapshotFailure(1L, 2L); + Mockito.verify(snapshotService, Mockito.never()).cleanupVolumeDuringSnapshotFailure(Mockito.anyLong(), Mockito.anyLong()); + + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getState()).thenReturn(Volume.State.Ready); + Mockito.doReturn(volume).when(volumeDao).findById(1L); + volumeOrchestrator.cleanupVolumeDuringSnapshotFailure(1L, 3L); + Mockito.verify(snapshotService).cleanupVolumeDuringSnapshotFailure(1L, 3L); + } + @Test public void checkVolumeIsNotUnderSnapshotOperationAllowsOtherStates() { for (Volume.State state : List.of(Volume.State.Ready, Volume.State.Allocated, Volume.State.Creating)) { diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index 326006be7bcc..4ee05383aede 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -329,6 +329,7 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { SnapshotObject snapshotOnPrimary = null; boolean succeeded = false; + boolean hostSucceeded = false; boolean keepVolumeReserved = false; try { // Marks the snapshot before anything is done on storage, so that operations refused while a volume has no-copy snapshots (e.g. assigning a backup @@ -353,11 +354,13 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { CreateDiskOnlyVmSnapshotCommand command = new CreateDiskOnlyVmSnapshotCommand(vm != null ? vm.getInstanceName() : null, vm != null ? vm.getUuid() : null, target, List.of(new Pair<>(volumeTO, newVolumePath)), null, vmRunning ? VirtualMachine.State.Running : VirtualMachine.State.Stopped, false); + // Recorded before the host acts, so that whatever happens next (no answer, management server restart) the new file of the volume can be found. + snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, newVolumePath, false); + Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); if (answer == null && vmRunning) { // The running Instance may already be writing to the new delta: releasing the volume with its old path would make its next start lose those writes. keepVolumeReserved = true; - snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, newVolumePath, false); throw new CloudRuntimeException(String.format("No answer from the host while taking KVM file-based no-copy snapshot [%s] of volume [%s] of running " + "Instance [%s]. The volume stays in state [%s] until an administrator checks whether the Instance uses the new file [%s] (then sets it as the " + "volume path) or still the file [%s], and then sets the volume state back to Ready.", snapshot.getUuid(), volumeInfo.getUuid(), vm.getUuid(), @@ -368,8 +371,9 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { volumeInfo.getUuid(), getAnswerDetails(answer))); } - // The volume is now on the new delta: record it first, so that a later failure can never leave the volume pointing to the frozen file. If updating the - // snapshot metadata fails afterwards, the snapshot ends in Error and the frozen file simply stays in the backing chain of the volume. + // The volume is now on the new delta: record it first, so that a later failure can never leave the volume pointing to the frozen file. From here on, + // the snapshot is never marked as failed: its frozen file is in the backing chain of the volume and must not be cleaned up as a failed snapshot. + hostSucceeded = true; VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); volumeVO.setPath(newVolumePath); volumeDao.update(volumeVO.getId(), volumeVO); @@ -383,6 +387,7 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { snapshotOnPrimary.processEvent(Snapshot.Event.OperationSucceeded); snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false); + snapshotDetailsDao.removeDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); logger.info("Took KVM file-based no-copy snapshot [{}] of volume [{}]: the snapshot is [{}] and the volume is now on [{}].", snapshot.getUuid(), volumeInfo.getUuid(), oldVolumePath, newVolumePath); @@ -392,11 +397,15 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { throw new CloudRuntimeException(String.format("Failed to update the state of snapshot [%s].", snapshot.getUuid()), e); } finally { if (!keepVolumeReserved) { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + // Once the host has succeeded the volume is on its new file, which is already recorded: the volume is usable even if the snapshot metadata is not. + volumeInfo.stateTransit(succeeded || hostSucceeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); } - if (!succeeded && snapshotOnPrimary != null) { + if (hostSucceeded && !succeeded) { + logger.error("KVM file-based no-copy snapshot [{}] of volume [{}] was taken on storage, but its metadata could not be fully updated. It is not marked as " + + "failed, so that its file (part of the backing chain of the volume) is not cleaned up.", snapshot.getUuid(), volumeInfo.getUuid()); + } else if (!succeeded && !keepVolumeReserved && snapshotOnPrimary != null) { markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); - } else if (!succeeded) { + } else if (!succeeded && !keepVolumeReserved) { snapshotDetailsDao.removeDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); } } @@ -413,13 +422,20 @@ protected SnapshotObject createSnapshotOnPrimary(SnapshotInfo snapshot) { } } + /** + * Never throws, as it runs in a finally block and must not hide the original failure. + */ protected void markSnapshotOnPrimaryAsFailed(SnapshotObject snapshotOnPrimary) { try { snapshotOnPrimary.processEvent(Snapshot.Event.OperationFailed); - } catch (NoTransitionException e) { + } catch (NoTransitionException | RuntimeException e) { logger.warn("Failed to mark snapshot [{}] as failed.", snapshotOnPrimary.getUuid(), e); } - snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + try { + snapshotOnPrimary.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } catch (RuntimeException e) { + logger.warn("Failed to mark the primary storage reference of snapshot [{}] as failed.", snapshotOnPrimary.getUuid(), e); + } } @Override @@ -535,7 +551,13 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { } try { - return deleteSnapshotInternal(snapshotVO); + // Re-read under the lock: a concurrent delete may have completed while this one waited, and must not be counted twice. + SnapshotVO current = snapshotDao.findById(snapshotId); + if (current == null || !(Snapshot.State.BackedUp.equals(current.getState()) || Snapshot.State.CreatedOnPrimary.equals(current.getState()))) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] was deleted or changed concurrently (state [%s]).", snapshotVO.getUuid(), + current == null ? null : current.getState())); + } + return deleteSnapshotInternal(current); } finally { snapshotDao.releaseFromLockTable(snapshotId); } diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index a0e8e4cce921..0465c1c25653 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -57,6 +57,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mockito; import com.cloud.agent.api.Answer; @@ -821,6 +822,71 @@ public void takeSnapshotOfRunningVmWithoutAnswerKeepsTheVolumeReserved() { verify(volumeInfo, never()).stateTransit(Volume.Event.OperationSucceeded); verify(snapshotDetailsDao).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH), any(), eq(false)); + // Not marked as failed: its outcome is unknown, and a failed snapshot could be cleaned up although its file may be in use. + verify(strategy, never()).markSnapshotOnPrimaryAsFailed(any()); + verify(snapshotDetailsDao, never()).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); + } + + @Test + public void takeSnapshotRecordsThePendingVolumePathBeforeSendingAndRemovesItOnSuccess() { + mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Map.of(VOLUME_UUID, 1L)); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(Command.class); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), commandCaptor.capture()); + + strategy.takeSnapshot(snapshotInfo); + + String newPath = ((CreateDiskOnlyVmSnapshotCommand) commandCaptor.getValue()).getVolumeTosAndNewPaths().get(0).second(); + InOrder inOrder = Mockito.inOrder(snapshotDetailsDao, strategy); + inOrder.verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, newPath, false); + inOrder.verify(strategy).sendToHost(eq(HOST_ID), any()); + inOrder.verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + } + + @Test + public void takeSnapshotWhoseMetadataFailsAfterTheHostSucceededIsNotMarkedAsFailed() { + SnapshotObject snapshotOnPrimary = mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + when(answer.getMapVolumeToSnapshotSize()).thenReturn(Map.of(VOLUME_UUID, 1L)); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), any()); + Mockito.doThrow(new CloudRuntimeException("database error")).when(snapshotOnPrimary).processEvent(eq(ObjectInDataStoreStateMachine.Event.OperationSucceeded), + any(CreateObjectAnswer.class)); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeVO).setPath(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(strategy, never()).markSnapshotOnPrimaryAsFailed(any()); + verify(snapshotDetailsDao, never()).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); + } + + @Test + public void markSnapshotOnPrimaryAsFailedNeverThrows() throws Exception { + SnapshotObject snapshotOnPrimary = mock(SnapshotObject.class); + Mockito.doThrow(new CloudRuntimeException("database error")).when(snapshotOnPrimary).processEvent(Snapshot.Event.OperationFailed); + Mockito.doThrow(new CloudRuntimeException("database error")).when(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + + strategy.markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); + + verify(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + + @Test + public void deleteSnapshotDeletedConcurrentlyWhileWaitingForTheLockIsRefused() { + mockChain(SNAPSHOT_ID); + SnapshotVO destroyed = mock(SnapshotVO.class); + when(destroyed.getState()).thenReturn(Snapshot.State.Destroyed); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(snapshotVO, destroyed); + + assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo, never()).stateTransit(any()); + verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); } @Test diff --git a/server/src/main/java/com/cloud/storage/StorageManagerImpl.java b/server/src/main/java/com/cloud/storage/StorageManagerImpl.java index 8557b91850d7..96c98d1e7c76 100644 --- a/server/src/main/java/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/main/java/com/cloud/storage/StorageManagerImpl.java @@ -231,6 +231,7 @@ import com.cloud.storage.dao.BucketDao; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; import com.cloud.storage.dao.StoragePoolAndAccessGroupMapDao; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.storage.dao.StoragePoolTagsDao; @@ -300,6 +301,8 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C @Inject protected SnapshotDao _snapshotDao; @Inject + protected SnapshotDetailsDao snapshotDetailsDao; + @Inject protected StoragePoolHostDao _storagePoolHostDao; @Inject protected VMTemplatePoolDao _vmTemplatePoolDao = null; @@ -2296,7 +2299,7 @@ private void cleanupSnapshotsFromStoreRefInDestroyingState() { } } - private void deleteSnapshot(SnapshotVO snapshot, SnapshotDataStoreVO snapshotDataStoreVO) { + protected void deleteSnapshot(SnapshotVO snapshot, SnapshotDataStoreVO snapshotDataStoreVO) { if (snapshot == null || snapshotDataStoreVO == null) { return; } @@ -2317,9 +2320,14 @@ private void deleteSnapshot(SnapshotVO snapshot, SnapshotDataStoreVO snapshotDat } } - private void removeSnapshotsInErrorStatus() { + protected void removeSnapshotsInErrorStatus() { List snapshotsInErrorStatus = _snapshotDao.listAllByStatusIncludingRemoved(Snapshot.State.Error); for (SnapshotVO snapshotVO : snapshotsInErrorStatus) { + if (snapshotDetailsDao.findDetail(snapshotVO.getId(), Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL) != null) { + // The file of a KVM file-based no-copy snapshot may be part of the backing chain of its volume: deleting it here could corrupt the volume. + logger.warn("Not cleaning up KVM file-based no-copy snapshot [{}] in Error state: check it and delete it manually if its file is not in use.", snapshotVO); + continue; + } try { List storeRefSnapshotsInErrorStatus = _snapshotStoreDao.findBySnapshotId(snapshotVO.getId()); for (SnapshotDataStoreVO snapshotDataStoreVO : storeRefSnapshotsInErrorStatus) { diff --git a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java index d2fcdc581b85..4d7631a61123 100644 --- a/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/main/java/com/cloud/storage/VolumeApiServiceImpl.java @@ -2767,6 +2767,22 @@ protected VolumeInfo createVolumeOnPrimaryForAttachIfNeeded(final VolumeInfo vol return newVolumeOnPrimaryStorage; } + /** + * KVM file-based no-copy snapshots are part of the backing chain of their volume. Backups may add or replace files in that chain, and a volume being hot + * attached to a running Instance could be snapshotted on a host other than the Instance's while the attach is in progress. + */ + protected void validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(UserVmVO vm, VolumeVO volume) { + if (vm == null || volume == null) { + return; + } + if (vm.getBackupOfferingId() != null) { + _snapshotMgr.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "attach it to an Instance with a backup offering"); + } + if (!State.Stopped.equals(vm.getState())) { + _snapshotMgr.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "attach it to an Instance that is not stopped (stop the Instance first)"); + } + } + private Volume orchestrateAttachVolumeToVM(Long vmId, Long volumeId, Long deviceId) { VolumeInfo volumeToAttach = volFactory.getVolume(volumeId); @@ -2775,6 +2791,8 @@ private Volume orchestrateAttachVolumeToVM(Long vmId, Long volumeId, Long device } UserVmVO vm = _userVmDao.findById(vmId); + // Checked again here, as the Instance may have been started, or assigned a backup offering, since the attach was requested. + validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(vm, _volsDao.findById(volumeId)); VolumeVO existingVolumeOfVm = getVmExistingVolumeForVolumeAttach(vm, volumeToAttach); VolumeInfo newVolumeOnPrimaryStorage = createVolumeOnPrimaryForAttachIfNeeded(volumeToAttach, vm, existingVolumeOfVm); @@ -3043,10 +3061,7 @@ public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId, Boolean validateIfVmHasBackups(vm, true); - if (vm.getBackupOfferingId() != null) { - // Backups may add or replace files in the backing chains that KVM file-based no-copy snapshots are part of. - _snapshotMgr.validateVolumeHasNoKvmFileBasedNoCopySnapshots(_volsDao.findById(volumeToAttach.getId()), "attach it to an Instance with a backup offering"); - } + validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(vm, _volsDao.findById(volumeToAttach.getId())); _accountMgr.checkAccess(caller, null, true, volumeToAttach, vm); diff --git a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java index af57c577de1f..5eba7ca1aa52 100644 --- a/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java +++ b/server/src/main/java/com/cloud/storage/snapshot/SnapshotManager.java @@ -83,7 +83,7 @@ public interface SnapshotManager extends Configurable { /** * Name of the snapshot detail that marks a volume snapshot taken with {@link #KvmFileBasedVolumeSnapshotNoCopy}. */ - String KVM_FILE_BASED_NO_COPY_SNAPSHOT = "kvmFileBasedNoCopySnapshot"; + String KVM_FILE_BASED_NO_COPY_SNAPSHOT = Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL; void deletePoliciesForVolume(Long volumeId); 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 19b03a0ce0da..0bba86605dc6 100644 --- a/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java +++ b/server/src/main/java/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java @@ -389,11 +389,7 @@ public VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDesc } if (userVmVo.getHypervisorType() == HypervisorType.KVM) { - // KVM file-based no-copy volume snapshots are part of the backing chains of the volumes: an Instance snapshot would either move the volumes again or, - // when reverted, replace the top of the chains that the no-copy snapshots depend on. - for (VolumeVO volume : _volumeDao.findByInstance(userVmVo.getId())) { - snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "take an Instance snapshot of its Instance"); - } + validateVolumesHaveNoKvmFileBasedNoCopySnapshots(userVmVo); //DefaultVMSnapshotStrategy - allows snapshot with memory when VM is in running state and all volumes have to be in QCOW format //ScaleIOVMSnapshotStrategy - allows group snapshots without memory; all VM's volumes should be on same storage pool; The state of VM could be Running/Stopped; RAW image format is only supported @@ -605,12 +601,35 @@ else if (jobResult instanceof Throwable) } } + /** + * KVM file-based no-copy volume snapshots are part of the backing chains of the volumes: an Instance snapshot would either move the volumes again or, when + * reverted, replace the top of the chains that the no-copy snapshots depend on. + */ + protected void validateVolumesHaveNoKvmFileBasedNoCopySnapshots(UserVmVO userVm) { + for (VolumeVO volume : _volumeDao.findByInstance(userVm.getId())) { + snapshotManager.validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "take an Instance snapshot of its Instance"); + } + } + private VMSnapshot orchestrateCreateVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm) { UserVmVO userVm = _userVMDao.findById(vmId); if (userVm == null) { throw new InvalidParameterValueException("Create Instance to Snapshot failed because Instance: " + vmId + " is not found"); } + if (userVm.getHypervisorType() == HypervisorType.KVM) { + // Checked again here, as a no-copy volume snapshot may have been taken since the Instance snapshot was allocated. + try { + validateVolumesHaveNoKvmFileBasedNoCopySnapshots(userVm); + } catch (RuntimeException e) { + VMSnapshotVO allocatedVmSnapshot = _vmSnapshotDao.findById(vmSnapshotId); + if (allocatedVmSnapshot != null && VMSnapshot.State.Allocated.equals(allocatedVmSnapshot.getState())) { + _vmSnapshotDao.remove(vmSnapshotId); + } + throw e; + } + } + List volumeVos = _volumeDao.findByInstanceAndType(vmId, Type.ROOT); if(volumeVos == null ||volumeVos.isEmpty()) { throw new CloudRuntimeException("Create Instance to Snapshot failed because no root disk was found"); diff --git a/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java b/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java index 166ac966c7e4..34ba5d2b49ac 100644 --- a/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java +++ b/server/src/main/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImpl.java @@ -87,7 +87,6 @@ import javax.inject.Inject; import java.util.ArrayList; -import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; @@ -165,7 +164,7 @@ public ListResponse listVolumesForImport(ListVolumesFor for (VolumeOnStorageTO volume : volumes) { if (checkIfVolumeManaged(pool, volume.getPath()) || checkIfVolumeForTemplate(pool, volume.getPath()) - || checkIfVolumeForSnapshot(pool, volume.getFullPath())) { + || checkIfVolumeForSnapshot(pool, volume.getFullPath(), volume.getPath())) { continue; } responses.add(createVolumeForImportResponse(volume, pool)); @@ -206,7 +205,7 @@ public VolumeResponse importVolume(ImportVolumeCmd cmd) { // 4. get volume info on storage through host and check VolumeOnStorageTO volume = getVolumeOnStorageAndCheck(pool, volumePath, false); - if (checkIfVolumeForSnapshot(pool, volume.getFullPath())) { + if (checkIfVolumeForSnapshot(pool, volume.getFullPath(), volume.getPath())) { logFailureAndThrowException("Volume is a reference of snapshot on primary: " + volume.getFullPath()); } @@ -419,9 +418,18 @@ private boolean checkIfVolumeForTemplate(StoragePoolVO pool, String volumePath) return templatePoolDao.findByPoolPath(pool.getId(), volumePath) != null; } - private boolean checkIfVolumeForSnapshot(StoragePoolVO pool, String fullVolumePath) { - List absPathList = Collections.singletonList(fullVolumePath); - return CollectionUtils.isNotEmpty(snapshotDataStoreDao.listByStoreAndInstallPaths(pool.getId(), DataStoreRole.Primary, absPathList)); + /** + * Snapshots on primary storage record either the full path of their file or, like the KVM file-based no-copy snapshots, its path relative to the pool. + */ + protected boolean checkIfVolumeForSnapshot(StoragePoolVO pool, String fullVolumePath, String volumePath) { + List pathList = new ArrayList<>(); + if (StringUtils.isNotBlank(fullVolumePath)) { + pathList.add(fullVolumePath); + } + if (StringUtils.isNotBlank(volumePath) && !volumePath.equals(fullVolumePath)) { + pathList.add(volumePath); + } + return !pathList.isEmpty() && CollectionUtils.isNotEmpty(snapshotDataStoreDao.listByStoreAndInstallPaths(pool.getId(), DataStoreRole.Primary, pathList)); } protected void checkIfVolumeIsLocked(VolumeOnStorageTO volume) { diff --git a/server/src/test/java/com/cloud/storage/StorageManagerImplTest.java b/server/src/test/java/com/cloud/storage/StorageManagerImplTest.java index f46699f88cfb..dd6bfd2c0011 100644 --- a/server/src/test/java/com/cloud/storage/StorageManagerImplTest.java +++ b/server/src/test/java/com/cloud/storage/StorageManagerImplTest.java @@ -86,6 +86,11 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorGuruManager; import com.cloud.storage.dao.VolumeDao; +import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotDetailsDao; +import com.cloud.storage.dao.SnapshotDetailsVO; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import com.cloud.user.AccountManagerImpl; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; @@ -98,6 +103,7 @@ import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doNothing; @RunWith(MockitoJUnitRunner.class) public class StorageManagerImplTest { @@ -1727,4 +1733,29 @@ public void checkUsagedSpaceReturnsFalseForZeroCapacityPool() { Assert.assertFalse(result); } + @Test + public void removeSnapshotsInErrorStatusLeavesKvmFileBasedNoCopySnapshotsAlone() { + SnapshotDao snapshotDao = Mockito.mock(SnapshotDao.class); + SnapshotDetailsDao snapshotDetailsDao = Mockito.mock(SnapshotDetailsDao.class); + SnapshotDataStoreDao snapshotStoreDao = Mockito.mock(SnapshotDataStoreDao.class); + storageManagerImpl._snapshotDao = snapshotDao; + storageManagerImpl.snapshotDetailsDao = snapshotDetailsDao; + storageManagerImpl._snapshotStoreDao = snapshotStoreDao; + SnapshotVO noCopySnapshot = Mockito.mock(SnapshotVO.class); + Mockito.when(noCopySnapshot.getId()).thenReturn(1L); + SnapshotVO regularSnapshot = Mockito.mock(SnapshotVO.class); + Mockito.when(regularSnapshot.getId()).thenReturn(2L); + Mockito.when(snapshotDao.listAllByStatusIncludingRemoved(Snapshot.State.Error)).thenReturn(List.of(noCopySnapshot, regularSnapshot)); + Mockito.when(snapshotDetailsDao.findDetail(1L, Snapshot.KVM_FILE_BASED_NO_COPY_SNAPSHOT_DETAIL)).thenReturn(Mockito.mock(SnapshotDetailsVO.class)); + SnapshotDataStoreVO storeRef = Mockito.mock(SnapshotDataStoreVO.class); + Mockito.when(snapshotStoreDao.findBySnapshotId(2L)).thenReturn(List.of(storeRef)); + doNothing().when(storageManagerImpl).deleteSnapshot(regularSnapshot, storeRef); + + storageManagerImpl.removeSnapshotsInErrorStatus(); + + Mockito.verify(snapshotStoreDao, Mockito.never()).findBySnapshotId(1L); + Mockito.verify(snapshotDao, Mockito.never()).expunge(1L); + Mockito.verify(storageManagerImpl).deleteSnapshot(regularSnapshot, storeRef); + Mockito.verify(snapshotDao).expunge(2L); + } } diff --git a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java index ac1f45b4ddc5..94aafa353c57 100644 --- a/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java +++ b/server/src/test/java/com/cloud/storage/VolumeApiServiceImplTest.java @@ -712,6 +712,28 @@ public void attachVolumeWithKvmFileBasedNoCopySnapshotsToVmWithBackupOfferingIsR } } + @Test + public void attachOfVolumeWithKvmFileBasedNoCopySnapshotsIsOnlyAllowedToStoppedInstancesWithoutBackupOffering() { + VolumeVO volume = Mockito.mock(VolumeVO.class); + UserVmVO vm = new UserVmVO(4L, "vm", "vm", 1, HypervisorType.KVM, 1L, false, false, 1L, 1L, 1, 1L, null, null, null, "vm"); + + vm.setState(State.Stopped); + volumeApiServiceImpl.validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(vm, volume); + Mockito.verify(snapshotManagerMock, Mockito.never()).validateVolumeHasNoKvmFileBasedNoCopySnapshots(Mockito.any(), Mockito.anyString()); + + for (State state : List.of(State.Running, State.Starting)) { + vm.setState(state); + volumeApiServiceImpl.validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(vm, volume); + } + Mockito.verify(snapshotManagerMock, Mockito.times(2)).validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, + "attach it to an Instance that is not stopped (stop the Instance first)"); + + vm.setState(State.Stopped); + vm.setBackupOfferingId(1L); + volumeApiServiceImpl.validateAttachOfVolumeWithKvmFileBasedNoCopySnapshots(vm, volume); + Mockito.verify(snapshotManagerMock).validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "attach it to an Instance with a backup offering"); + } + // volume not Ready @Test(expected = InvalidParameterValueException.class) public void testTakeSnapshotF1() throws ResourceAllocationException { 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 5af514fa0623..ec523340efc1 100644 --- a/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java +++ b/server/src/test/java/com/cloud/vm/snapshot/VMSnapshotManagerTest.java @@ -66,6 +66,7 @@ import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -333,6 +334,22 @@ public void testAllocVMSnapshotRefusedWhenAVolumeHasKvmFileBasedNoCopySnapshots( _vmSnapshotMgr.allocVMSnapshot(TEST_VM_ID, "", "", false); } + // a KVM file-based no-copy snapshot was taken after the Instance snapshot was allocated + @Test + public void testCreateVMSnapshotJobRemovesTheAllocatedSnapshotWhenAVolumeNowHasKvmFileBasedNoCopySnapshots() throws Exception { + when(vmMock.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); + doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volumeMock, "take an Instance snapshot of its Instance"); + VMSnapshotVO allocated = mock(VMSnapshotVO.class); + when(allocated.getState()).thenReturn(VMSnapshot.State.Allocated); + when(_vmSnapshotDao.findById(5L)).thenReturn(allocated); + + Assert.assertThrows(InvalidParameterValueException.class, + () -> _vmSnapshotMgr.orchestrateCreateVMSnapshot(new VmWorkCreateVMSnapshot(1L, 1L, TEST_VM_ID, "handler", 5L, false))); + + verify(_vmSnapshotDao).remove(5L); + } + // successful creation case @Test public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException, ResourceAllocationException, NoTransitionException { diff --git a/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java b/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java index 776b5be8462e..523982f10ea8 100644 --- a/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java +++ b/server/src/test/java/org/apache/cloudstack/storage/volume/VolumeImportUnmanageManagerImplTest.java @@ -69,6 +69,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.junit.Assert; import org.junit.Before; @@ -500,6 +501,18 @@ public void testUnmanageVolumeWithKvmFileBasedNoCopySnapshotsIsRefused() { verify(volumeDao, Mockito.never()).update(Mockito.anyLong(), any()); } + @Test + public void testCheckIfVolumeForSnapshotMatchesFullAndPoolRelativePaths() { + StoragePoolVO pool = mock(StoragePoolVO.class); + when(pool.getId()).thenReturn(poolId); + when(snapshotDataStoreDao.listByStoreAndInstallPaths(poolId, DataStoreRole.Primary, List.of("/mnt/pool/frozen-file", "frozen-file"))) + .thenReturn(List.of(mock(SnapshotDataStoreVO.class))); + + Assert.assertTrue(volumeImportUnmanageManager.checkIfVolumeForSnapshot(pool, "/mnt/pool/frozen-file", "frozen-file")); + Assert.assertFalse(volumeImportUnmanageManager.checkIfVolumeForSnapshot(pool, "/mnt/pool/other-file", "other-file")); + Assert.assertFalse(volumeImportUnmanageManager.checkIfVolumeForSnapshot(pool, null, null)); + } + @Test public void testUnmanageVolumeNotExist() { try { From 03baae18f48b039ad08c107cf5a8911ce2ef06c9 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:13:38 +0000 Subject: [PATCH 05/12] KVM no-copy snapshots: tell unsent commands from lost answers, resolve incomplete takes - Send commands with AgentManager#send: a command that was not sent (host down or disconnected) is a plain failure that releases the volume; only a command sent without an answer keeps the volume reserved. - Record both files of a take before asking the host. Deleting a snapshot whose take did not complete now completes it (the volume is on the new file) or discards it (the volume is still on its old file), once its volume is Ready again. - A definite take failure is a regular failed snapshot: the no-copy marks are removed, so the regular Error-snapshot cleanup applies. - Releasing the volume in finally blocks never throws. - Undoing a raced backup offering assignment clears the DB even if the provider fails, and reports the provider failure. Co-Authored-By: Claude Opus 5.5 --- .../orchestration/VolumeOrchestrator.java | 3 +- .../KvmFileBasedNoCopySnapshotStrategy.java | 150 ++++++++++++-- ...vmFileBasedNoCopySnapshotStrategyTest.java | 184 ++++++++++++++++++ .../cloudstack/backup/BackupManagerImpl.java | 23 ++- .../cloudstack/backup/BackupManagerTest.java | 31 ++- 5 files changed, 372 insertions(+), 19 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 3ee1d4cdda07..3a335656fd3c 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -2543,7 +2543,8 @@ protected void cleanupVolumeDuringSnapshotFailure(Long volumeId, Long snapshotId // The outcome of a KVM file-based no-copy snapshot take is unknown: a running Instance may already be writing to the new file. Resetting the volume // with its old path would make the next start lose those writes, so it is left for an administrator (see the snapshot details). logger.warn("Not cleaning up volume [{}] after the failed KVM file-based no-copy snapshot [{}]: check which file of its backing chain is current " + - "(snapshot detail [kvmFileBasedNoCopySnapshotPendingVolumePath]), then set the volume path and state.", volumeId, snapshotId); + "(snapshot details [kvmFileBasedNoCopySnapshotPendingVolumePath] and [kvmFileBasedNoCopySnapshotPendingFrozenPath]), set the volume path and the " + + "volume state to Ready, then delete the snapshot: that completes or discards it, depending on the volume path.", volumeId, snapshotId); return; } _snapshotSrv.cleanupVolumeDuringSnapshotFailure(volumeId, snapshotId); diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index 4ee05383aede..c0dfbbe0a3a5 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -55,7 +55,9 @@ import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.to.DataTO; +import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.OperationTimedoutException; import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.dao.HostDetailsDao; @@ -107,9 +109,11 @@ public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE = "kvmFileBasedNoCopySnapshotMergeIncomplete"; /** - * Snapshot detail holding the new volume file of a take whose outcome is unknown (no answer from the host for a running Instance). + * Snapshot details holding, while a take is in progress, the new file of the volume and the file that becomes the snapshot. They are removed when the take + * completes; if they remain (no answer from the host, management server restart), deleting the snapshot uses them to complete or discard it. */ protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH = "kvmFileBasedNoCopySnapshotPendingVolumePath"; + protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH = "kvmFileBasedNoCopySnapshotPendingFrozenPath"; /** * Wait for the merge command: at least the agent's own merge timeout (qcow2.delta.merge.timeout, 72 hours by default), so that a long merge is not taken for @@ -331,6 +335,8 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { boolean succeeded = false; boolean hostSucceeded = false; boolean keepVolumeReserved = false; + String pendingVolumePath = null; + boolean outcomeUnknown = false; try { // Marks the snapshot before anything is done on storage, so that operations refused while a volume has no-copy snapshots (e.g. assigning a backup // offering) also see a take in progress. Then re-checks what such an operation could have changed concurrently. @@ -354,16 +360,20 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { CreateDiskOnlyVmSnapshotCommand command = new CreateDiskOnlyVmSnapshotCommand(vm != null ? vm.getInstanceName() : null, vm != null ? vm.getUuid() : null, target, List.of(new Pair<>(volumeTO, newVolumePath)), null, vmRunning ? VirtualMachine.State.Running : VirtualMachine.State.Stopped, false); - // Recorded before the host acts, so that whatever happens next (no answer, management server restart) the new file of the volume can be found. + // Recorded before the host acts, so that whatever happens next (no answer, management server restart) the files of the take can be found. snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, newVolumePath, false); + snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH, oldVolumePath, false); + pendingVolumePath = newVolumePath; Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + outcomeUnknown = answer == null; if (answer == null && vmRunning) { // The running Instance may already be writing to the new delta: releasing the volume with its old path would make its next start lose those writes. keepVolumeReserved = true; throw new CloudRuntimeException(String.format("No answer from the host while taking KVM file-based no-copy snapshot [%s] of volume [%s] of running " + "Instance [%s]. The volume stays in state [%s] until an administrator checks whether the Instance uses the new file [%s] (then sets it as the " + - "volume path) or still the file [%s], and then sets the volume state back to Ready.", snapshot.getUuid(), volumeInfo.getUuid(), vm.getUuid(), + "volume path) or still the file [%s], and then sets the volume state back to Ready. Deleting the snapshot afterwards completes it (if the " + + "volume is on the new file) or discards it (if the volume is still on its old file).", snapshot.getUuid(), volumeInfo.getUuid(), vm.getUuid(), Volume.State.Snapshotting, newVolumePath, oldVolumePath)); } if (!(answer instanceof CreateDiskOnlyVmSnapshotAnswer) || !answer.getResult()) { @@ -387,7 +397,7 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { snapshotOnPrimary.processEvent(Snapshot.Event.OperationSucceeded); snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false); - snapshotDetailsDao.removeDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + removePendingDetails(snapshot.getId()); logger.info("Took KVM file-based no-copy snapshot [{}] of volume [{}]: the snapshot is [{}] and the volume is now on [{}].", snapshot.getUuid(), volumeInfo.getUuid(), oldVolumePath, newVolumePath); @@ -398,19 +408,45 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { } finally { if (!keepVolumeReserved) { // Once the host has succeeded the volume is on its new file, which is already recorded: the volume is usable even if the snapshot metadata is not. - volumeInfo.stateTransit(succeeded || hostSucceeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + releaseVolume(volumeInfo, succeeded || hostSucceeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); } if (hostSucceeded && !succeeded) { logger.error("KVM file-based no-copy snapshot [{}] of volume [{}] was taken on storage, but its metadata could not be fully updated. It is not marked as " + - "failed, so that its file (part of the backing chain of the volume) is not cleaned up.", snapshot.getUuid(), volumeInfo.getUuid()); - } else if (!succeeded && !keepVolumeReserved && snapshotOnPrimary != null) { - markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); + "failed, so that its file (part of the backing chain of the volume) is not cleaned up; deleting the snapshot completes it first.", + snapshot.getUuid(), volumeInfo.getUuid()); } else if (!succeeded && !keepVolumeReserved) { + // The volume keeps its file (which is not part of any other snapshot), so this is a failed snapshot like any other and its regular cleanup is safe. + if (outcomeUnknown) { + logger.warn("No answer from the host while taking KVM file-based no-copy snapshot [{}] of volume [{}], which keeps its file. The new file [{}] may " + + "have been created and, if so, is not used and can be deleted.", snapshot.getUuid(), volumeInfo.getUuid(), pendingVolumePath); + } + removePendingDetails(snapshot.getId()); snapshotDetailsDao.removeDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); + if (snapshotOnPrimary != null) { + markSnapshotOnPrimaryAsFailed(snapshotOnPrimary); + } } } } + protected void removePendingDetails(long snapshotId) { + snapshotDetailsDao.removeDetail(snapshotId, KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + snapshotDetailsDao.removeDetail(snapshotId, KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH); + } + + /** + * Releases the volume reserved by {@link #reserveVolume}. Never throws, as it runs in finally blocks and must not hide the original failure. + */ + protected void releaseVolume(VolumeInfo volumeInfo, Volume.Event event) { + try { + if (!volumeInfo.stateTransit(event)) { + logger.warn("Volume [{}] could not be released with event [{}]: its state was changed concurrently.", volumeInfo.getUuid(), event); + } + } catch (RuntimeException e) { + logger.warn("Failed to release volume [{}] with event [{}].", volumeInfo.getUuid(), event, e); + } + } + protected SnapshotObject createSnapshotOnPrimary(SnapshotInfo snapshot) { try { SnapshotObject snapshotOnPrimary = (SnapshotObject) snapshot.getDataStore().create(snapshot); @@ -514,7 +550,7 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { return true; } finally { if (!keepVolumeReserved) { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + releaseVolume(volumeInfo, succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); } } } @@ -540,6 +576,7 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { return true; case CreatedOnPrimary: case BackedUp: + case Creating: break; default: throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be deleted while it is in state [%s].", snapshotVO.getUuid(), snapshotVO.getState())); @@ -553,6 +590,13 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { try { // Re-read under the lock: a concurrent delete may have completed while this one waited, and must not be counted twice. SnapshotVO current = snapshotDao.findById(snapshotId); + if (current != null && Snapshot.State.Creating.equals(current.getState())) { + // Holding the lock means that no take of it is running any more: the take did not complete (no answer from the host, or a restart). + current = completeOrDiscardIncompleteTake(current); + if (current == null) { + return true; + } + } if (current == null || !(Snapshot.State.BackedUp.equals(current.getState()) || Snapshot.State.CreatedOnPrimary.equals(current.getState()))) { throw new InvalidParameterValueException(String.format("Snapshot [%s] was deleted or changed concurrently (state [%s]).", snapshotVO.getUuid(), current == null ? null : current.getState())); @@ -563,6 +607,69 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { } } + /** + * Resolves a snapshot whose take did not complete, from the files recorded before the host was asked to take it and the current path of its volume (which an + * administrator sets after checking the Instance, as the take failure says). + * @return the snapshot, now complete, if the take happened (the caller then deletes it as usual); null if it did not happen and the snapshot was discarded. + */ + protected SnapshotVO completeOrDiscardIncompleteTake(SnapshotVO snapshotVO) { + SnapshotDetailsVO pendingVolumePath = snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + SnapshotDetailsVO pendingFrozenPath = snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH); + VolumeVO volumeVO = volumeDao.findById(snapshotVO.getVolumeId()); + if (pendingVolumePath == null || volumeVO == null) { + logger.info("KVM file-based no-copy snapshot [{}] never reached its host; discarding it.", snapshotVO.getUuid()); + removeSnapshotMetadata(snapshotVO); + return null; + } + if (pendingFrozenPath == null) { + throw new CloudRuntimeException(String.format("KVM file-based no-copy snapshot [%s] did not complete and its files are not fully recorded; it must be " + + "resolved manually.", snapshotVO.getUuid())); + } + if (!Volume.State.Ready.equals(volumeVO.getState())) { + throw new InvalidParameterValueException(String.format("KVM file-based no-copy snapshot [%s] did not complete, and its volume [%s] is in state [%s]. Check " + + "whether the volume uses the new file [%s] or still the file [%s], set that as the volume path and the volume state to Ready, then delete the snapshot " + + "again.", snapshotVO.getUuid(), volumeVO.getUuid(), volumeVO.getState(), pendingVolumePath.getValue(), pendingFrozenPath.getValue())); + } + + VolumeInfo volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); + reserveVolume(volumeInfo, Volume.Event.SnapshotRequested, snapshotVO); + try { + volumeVO = volumeDao.findById(volumeVO.getId()); + if (pendingFrozenPath.getValue().equals(volumeVO.getPath())) { + logger.info("The take of KVM file-based no-copy snapshot [{}] did not happen: volume [{}] is still on [{}]. Discarding the snapshot; the file [{}], if it " + + "exists, is not used and can be deleted.", snapshotVO.getUuid(), volumeVO.getUuid(), volumeVO.getPath(), pendingVolumePath.getValue()); + removeSnapshotMetadata(snapshotVO); + return null; + } + List chain = listNoCopySnapshotsOfVolume(volumeVO.getId()); + if (!pendingVolumePath.getValue().equals(volumeVO.getPath())) { + boolean frozenByALaterTake = chain.stream().map(s -> snapshotStoreDao.findOneBySnapshotAndDatastoreRole(s.getId(), DataStoreRole.Primary)) + .anyMatch(storeRef -> storeRef != null && pendingVolumePath.getValue().equals(storeRef.getInstallPath())); + throw new InvalidParameterValueException(String.format("KVM file-based no-copy snapshot [%s] did not complete, and volume [%s] is neither on the new " + + "file [%s] nor on the file [%s] of the take. %s", snapshotVO.getUuid(), volumeVO.getUuid(), pendingVolumePath.getValue(), + pendingFrozenPath.getValue(), frozenByALaterTake ? "Delete the snapshots taken after it first." : "It must be resolved manually.")); + } + + logger.info("The take of KVM file-based no-copy snapshot [{}] happened: volume [{}] is on [{}]. Completing the snapshot.", snapshotVO.getUuid(), + volumeVO.getUuid(), volumeVO.getPath()); + long sequence = chain.stream().mapToLong(this::getChainSequence).max().orElse(0L) + 1; + SnapshotDataStoreVO storeRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); + if (storeRef == null) { + throw new CloudRuntimeException(String.format("Unable to find the primary storage reference of snapshot [%s].", snapshotVO.getUuid())); + } + storeRef.setInstallPath(pendingFrozenPath.getValue()); + storeRef.setState(ObjectInDataStoreStateMachine.State.Ready); + snapshotStoreDao.update(storeRef.getId(), storeRef); + snapshotDetailsDao.addDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, String.valueOf(sequence), false); + removePendingDetails(snapshotVO.getId()); + snapshotVO.setState(Snapshot.State.BackedUp); + snapshotDao.update(snapshotVO.getId(), snapshotVO); + return snapshotDao.findById(snapshotVO.getId()); + } finally { + releaseVolume(volumeInfo, Volume.Event.OperationSucceeded); + } + } + protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { VolumeVO volumeVO = volumeDao.findByIdIncludingRemoved(snapshotVO.getVolumeId()); SnapshotDataStoreVO snapshotStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); @@ -645,7 +752,7 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { return true; } finally { if (!keepVolumeReserved) { - volumeInfo.stateTransit(succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); + releaseVolume(volumeInfo, succeeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); } } } @@ -805,8 +912,29 @@ protected long getHostIdForOperation(VolumeInfo volumeInfo, VMInstanceVO vm) { return endPoint.getId(); } + /** + * Thrown when a command was not sent at all, because its host is not connected: the host did nothing, so there is no unknown outcome to handle. + */ + protected static class CommandNotSentException extends CloudRuntimeException { + protected CommandNotSentException(String message, Throwable cause) { + super(message, cause); + } + } + + /** + * @return the answer of the host, or null if the command was sent but no answer came back (its outcome is then unknown). + * @throws CommandNotSentException if the command was not sent, e.g. because the host is down or disconnected. + */ protected Answer sendToHost(long hostId, com.cloud.agent.api.Command command) { - return agentManager.easySend(hostId, command); + try { + return agentManager.send(hostId, command); + } catch (AgentUnavailableException e) { + throw new CommandNotSentException(String.format("The command [%s] was not sent, as host [%s] is not available: %s", command.getClass().getSimpleName(), + hostId, e.getMessage()), e); + } catch (OperationTimedoutException e) { + logger.warn("No answer from host [{}] to the command [{}].", hostId, command.getClass().getSimpleName(), e); + return null; + } } protected String getAnswerDetails(Answer answer) { diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 0465c1c25653..2b5b759360bb 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -21,12 +21,14 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -60,6 +62,9 @@ import org.mockito.InOrder; import org.mockito.Mockito; +import com.cloud.agent.AgentManager; +import com.cloud.exception.AgentUnavailableException; +import com.cloud.exception.OperationTimedoutException; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.storage.CreateDiskOnlyVmSnapshotAnswer; @@ -471,6 +476,9 @@ public void takeSnapshotFailureKeepsVolumePath() throws Exception { verify(snapshotOnPrimary).processEvent(Snapshot.Event.OperationFailed); verify(snapshotOnPrimary).processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); verify(snapshotDao).releaseFromLockTable(SNAPSHOT_ID); + // A definite failure is a failed snapshot like any other: its regular cleanup is safe, as its volume keeps its file. + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); } // revert @@ -827,6 +835,182 @@ public void takeSnapshotOfRunningVmWithoutAnswerKeepsTheVolumeReserved() { verify(snapshotDetailsDao, never()).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); } + // commands that were not sent (host down or disconnected) + + @Test + public void sendToHostDistinguishesNotSentFromNoAnswer() throws Exception { + AgentManager agentManager = mock(AgentManager.class); + strategy.agentManager = agentManager; + Command command = mock(Command.class); + Mockito.doCallRealMethod().when(strategy).sendToHost(anyLong(), any()); + + when(agentManager.send(HOST_ID, command)).thenThrow(new AgentUnavailableException("host is down", HOST_ID)); + assertThrows(KvmFileBasedNoCopySnapshotStrategy.CommandNotSentException.class, () -> strategy.sendToHost(HOST_ID, command)); + + Mockito.reset(agentManager); + when(agentManager.send(HOST_ID, command)).thenThrow(new OperationTimedoutException(new Command[0], HOST_ID, 1L, 10, false)); + assertNull(strategy.sendToHost(HOST_ID, command)); + + Mockito.reset(agentManager); + Answer answer = new Answer(null, true, null); + when(agentManager.send(HOST_ID, command)).thenReturn(answer); + assertSame(answer, strategy.sendToHost(HOST_ID, command)); + } + + @Test + public void takeSnapshotOfRunningVmWhoseHostIsDownReleasesTheVolume() throws Exception { + attachVolumeToVm(); + SnapshotObject snapshotOnPrimary = mockSnapshotOnPrimary(); + doThrow(new KvmFileBasedNoCopySnapshotStrategy.CommandNotSentException("host is down", null)).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + verify(volumeVO, never()).setPath(any()); + verify(snapshotOnPrimary).processEvent(Snapshot.Event.OperationFailed); + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + } + + @Test + public void deleteSnapshotWhoseHostIsDownReleasesTheVolumeAndKeepsItRevertible() { + attachVolumeToVm(); + mockChain(SNAPSHOT_ID); + doThrow(new KvmFileBasedNoCopySnapshotStrategy.CommandNotSentException("host is down", null)).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + verify(snapshotDetailsDao, never()).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE), + any(), Mockito.anyBoolean()); + } + + @Test + public void revertSnapshotWhoseHostIsDownReleasesTheVolume() { + mockChain(SNAPSHOT_ID); + doThrow(new KvmFileBasedNoCopySnapshotStrategy.CommandNotSentException("host is down", null)).when(strategy).sendToHost(anyLong(), any()); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + verify(volumeVO, never()).setPath(any()); + } + + @Test + public void releaseVolumeNeverThrows() { + when(volumeInfo.stateTransit(Volume.Event.OperationFailed)).thenThrow(new CloudRuntimeException("no transition")); + strategy.releaseVolume(volumeInfo, Volume.Event.OperationFailed); + when(volumeInfo.stateTransit(Volume.Event.OperationSucceeded)).thenReturn(false); + strategy.releaseVolume(volumeInfo, Volume.Event.OperationSucceeded); + } + + // takes that did not complete (no answer for a running Instance, or a management server restart) + + private SnapshotVO mockIncompleteTake(String pendingVolumePath, String pendingFrozenPath, Volume.State volumeState, String volumePath) { + SnapshotVO creating = mock(SnapshotVO.class); + when(creating.getId()).thenReturn(SNAPSHOT_ID); + when(creating.getUuid()).thenReturn("snapshot-" + SNAPSHOT_ID); + when(creating.getVolumeId()).thenReturn(VOLUME_ID); + when(creating.getDataCenterId()).thenReturn(ZONE_ID); + when(creating.getState()).thenReturn(Snapshot.State.Creating); + when(snapshotDao.acquireInLockTable(SNAPSHOT_ID)).thenReturn(creating); + if (pendingVolumePath != null) { + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH)) + .thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, + pendingVolumePath, false)); + } + if (pendingFrozenPath != null) { + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH)) + .thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH, + pendingFrozenPath, false)); + } + when(volumeVO.getState()).thenReturn(volumeState); + when(volumeVO.getPath()).thenReturn(volumePath); + return creating; + } + + @Test + public void deleteOfAnIncompleteTakeThatHappenedCompletesItThenMergesIt() { + List chainBefore = mockChain(5L); + SnapshotVO creating = mockIncompleteTake("new-delta", "frozen-10", Volume.State.Ready, "new-delta"); + SnapshotDataStoreVO storeRef = mock(SnapshotDataStoreVO.class); + when(storeRef.getInstallPath()).thenReturn("frozen-10"); + when(storeRef.getDataStoreId()).thenReturn(POOL_ID); + when(snapshotStoreDao.findOneBySnapshotAndDatastoreRole(SNAPSHOT_ID, DataStoreRole.Primary)).thenReturn(storeRef); + SnapshotObjectTO snapshotTO = new SnapshotObjectTO(); + snapshotTO.setPath("frozen-10"); + SnapshotInfo info = mock(SnapshotInfo.class); + when(info.getTO()).thenReturn(snapshotTO); + when(snapshotDataFactory.getSnapshot(SNAPSHOT_ID, POOL_ID, DataStoreRole.Primary)).thenReturn(info); + when(snapshotManager.isKvmFileBasedNoCopySnapshot(SNAPSHOT_ID)).thenReturn(true); + // Once completed, the snapshot is BackedUp and part of the chain, after snapshot 5. + List chainAfter = new ArrayList<>(chainBefore); + chainAfter.add(snapshotVO); + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE)) + .thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, "2", false)); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating, creating, snapshotVO); + when(snapshotDao.listByVolumeId(VOLUME_ID)).thenReturn(chainBefore, chainAfter); + + MergeDiskOnlyVmSnapshotCommand command = deleteAndCaptureMerge(); + + verify(storeRef).setInstallPath("frozen-10"); + verify(storeRef).setState(ObjectInDataStoreStateMachine.State.Ready); + verify(creating).setState(Snapshot.State.BackedUp); + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_SEQUENCE, "2", false); + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + assertEquals("frozen-10", command.getDeltaMergeTreeToList().get(0).getParent().getPath()); + } + + @Test + public void deleteOfAnIncompleteTakeThatDidNotHappenDiscardsIt() { + SnapshotVO creating = mockIncompleteTake("new-delta", VOLUME_PATH, Volume.State.Ready, VOLUME_PATH); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(creating).setState(Snapshot.State.Destroyed); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeVO, never()).setPath(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void deleteOfAnIncompleteTakeIsRefusedWhileItsVolumeIsStillReserved() { + SnapshotVO creating = mockIncompleteTake("new-delta", VOLUME_PATH, Volume.State.Snapshotting, VOLUME_PATH); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + + InvalidParameterValueException e = assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + assertTrue(e.getMessage().contains("new-delta")); + verify(creating, never()).setState(any()); + verify(volumeInfo, never()).stateTransit(any()); + } + + @Test + public void deleteOfAnIncompleteTakeThatNeverReachedTheHostDiscardsIt() { + SnapshotVO creating = mockIncompleteTake(null, null, Volume.State.Snapshotting, VOLUME_PATH); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(creating).setState(Snapshot.State.Destroyed); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void deleteOfAnIncompleteTakeFrozenByALaterTakeAsksToDeleteTheLaterOnesFirst() { + mockChain(5L); + SnapshotDataStoreVO laterStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(5L, DataStoreRole.Primary); + when(laterStoreRef.getInstallPath()).thenReturn("new-delta"); + SnapshotVO creating = mockIncompleteTake("new-delta", "frozen-10", Volume.State.Ready, "newer-delta"); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + + InvalidParameterValueException e = assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + assertTrue(e.getMessage().contains("taken after it first")); + verify(creating, never()).setState(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + } + @Test public void takeSnapshotRecordsThePendingVolumePathBeforeSendingAndRemovesItOnSuccess() { mockSnapshotOnPrimary(); diff --git a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java index 53e287e457b0..50d0edecec8f 100644 --- a/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java +++ b/server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java @@ -736,12 +736,23 @@ protected void undoAssignmentIfNoCopySnapshotsAppeared(VMInstanceVO vm, BackupOf } catch (InvalidParameterValueException e) { logger.warn("Undoing the assignment of Instance [{}] to backup offering [{}], as a KVM file-based no-copy snapshot was taken concurrently.", vm.getUuid(), offering.getUuid()); - backupProvider.removeVMFromBackupOffering(vm); - vm.setBackupOfferingId(null); - vm.setBackupVolumes(null); - vm.setBackupExternalId(null); - vmInstanceDao.update(vm.getId(), vm); - publishBackupOfferingUsageRemoved(vm, offering.getId()); + boolean removedFromProvider = false; + try { + removedFromProvider = backupProvider.removeVMFromBackupOffering(vm); + } catch (RuntimeException providerException) { + logger.error("Failed to remove Instance [{}] from backup offering [{}] in its provider.", vm.getUuid(), offering.getUuid(), providerException); + } finally { + // Cleared even if the provider failed: the offering recorded in the DB is what KVM file-based no-copy snapshot takes check. + vm.setBackupOfferingId(null); + vm.setBackupVolumes(null); + vm.setBackupExternalId(null); + vmInstanceDao.update(vm.getId(), vm); + publishBackupOfferingUsageRemoved(vm, offering.getId()); + } + if (!removedFromProvider) { + throw new InvalidParameterValueException(String.format("%s The assignment was undone in CloudStack, but the provider of backup offering [%s] failed to " + + "remove the Instance: remove it there.", e.getMessage(), offering.getUuid())); + } throw e; } } diff --git a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java index f8e1e3c2312a..4341c0f27494 100644 --- a/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java +++ b/server/src/test/java/org/apache/cloudstack/backup/BackupManagerTest.java @@ -1486,8 +1486,12 @@ public void testUndoAssignmentWhenANoCopySnapshotAppearedConcurrently() { Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "assign its Instance to a backup offering"); + when(backupProvider.removeVMFromBackupOffering(vm)).thenReturn(true); + try (MockedStatic ignored = Mockito.mockStatic(UsageEventUtils.class)) { - org.junit.Assert.assertThrows(InvalidParameterValueException.class, () -> backupManager.undoAssignmentIfNoCopySnapshotsAppeared(vm, offering, backupProvider)); + InvalidParameterValueException e = org.junit.Assert.assertThrows(InvalidParameterValueException.class, + () -> backupManager.undoAssignmentIfNoCopySnapshotsAppeared(vm, offering, backupProvider)); + org.junit.Assert.assertEquals("has KVM file-based no-copy snapshots", e.getMessage()); } verify(backupProvider).removeVMFromBackupOffering(vm); @@ -1495,6 +1499,31 @@ public void testUndoAssignmentWhenANoCopySnapshotAppearedConcurrently() { verify(vmInstanceDao).update(1L, vm); } + @Test + public void testUndoAssignmentClearsTheDbEvenWhenTheProviderFails() { + VMInstanceVO vm = mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(1L); + when(vm.getUuid()).thenReturn("vm-uuid"); + BackupOfferingVO offering = mock(BackupOfferingVO.class); + when(offering.getId()).thenReturn(2L); + when(offering.getUuid()).thenReturn("offering-uuid"); + VolumeVO volume = mock(VolumeVO.class); + when(volumeDao.findByInstance(1L)).thenReturn(List.of(volume)); + Mockito.doThrow(new InvalidParameterValueException("has KVM file-based no-copy snapshots")).when(snapshotManager) + .validateVolumeHasNoKvmFileBasedNoCopySnapshots(volume, "assign its Instance to a backup offering"); + when(backupProvider.removeVMFromBackupOffering(vm)).thenThrow(new CloudRuntimeException("provider unreachable")); + + try (MockedStatic ignored = Mockito.mockStatic(UsageEventUtils.class)) { + InvalidParameterValueException e = org.junit.Assert.assertThrows(InvalidParameterValueException.class, + () -> backupManager.undoAssignmentIfNoCopySnapshotsAppeared(vm, offering, backupProvider)); + org.junit.Assert.assertTrue(e.getMessage().contains("offering-uuid")); + } + + verify(vm).setBackupOfferingId(null); + verify(vm).setBackupExternalId(null); + verify(vmInstanceDao).update(1L, vm); + } + @Test public void testAssignmentIsKeptWhenNoNoCopySnapshotAppeared() { VMInstanceVO vm = mock(VMInstanceVO.class); From 6f4cee9fd116a315fa547f39101c03245ce53bd5 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:23:52 +0000 Subject: [PATCH 06/12] KVM no-copy snapshots: count incomplete takes once, block chain operations until resolved - A take that fails but leaves its snapshot in place (no answer, or the metadata update failed after the host succeeded) records that the failed take released its resource count; deleting the snapshot counts it again first, so the delete does not release it twice. - Taking, reverting or deleting a snapshot of a volume is refused while another take of that volume did not complete, since its chain in the DB may be missing a file; deleting the incomplete snapshot resolves it. - An incomplete take whose frozen file was frozen by a later take did not happen, and is discarded. - Any other failure sending a command (e.g. while processing its answer) is treated as an unknown outcome. Co-Authored-By: Claude Opus 5.5 --- .../KvmFileBasedNoCopySnapshotStrategy.java | 55 +++++++++++- ...vmFileBasedNoCopySnapshotStrategyTest.java | 89 +++++++++++++++++++ 2 files changed, 142 insertions(+), 2 deletions(-) diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index c0dfbbe0a3a5..63af8d57664f 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -55,6 +55,7 @@ import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotAnswer; import com.cloud.agent.api.storage.RevertDiskOnlyVmSnapshotCommand; import com.cloud.agent.api.to.DataTO; +import com.cloud.configuration.Resource; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; @@ -75,6 +76,7 @@ import com.cloud.storage.dao.SnapshotZoneDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.snapshot.SnapshotManager; +import com.cloud.user.ResourceLimitService; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -115,6 +117,12 @@ public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH = "kvmFileBasedNoCopySnapshotPendingVolumePath"; protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH = "kvmFileBasedNoCopySnapshotPendingFrozenPath"; + /** + * Snapshot detail set when a take failed but left its snapshot in place: the failed take released the snapshot resource count of the account + * (SnapshotManagerImpl#takeSnapshot), so deleting the snapshot counts it again first, as the delete releases it. + */ + protected static final String KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED = "kvmFileBasedNoCopySnapshotResourceCountReleased"; + /** * Wait for the merge command: at least the agent's own merge timeout (qcow2.delta.merge.timeout, 72 hours by default), so that a long merge is not taken for * a lost answer. @@ -162,6 +170,8 @@ public class KvmFileBasedNoCopySnapshotStrategy extends SnapshotStrategyBase { @Inject protected AgentManager agentManager; + @Inject + protected ResourceLimitService resourceLimitService; @Inject protected HostDetailsDao hostDetailsDao; @@ -338,6 +348,7 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { String pendingVolumePath = null; boolean outcomeUnknown = false; try { + validateNoIncompleteTakeOfVolume(volumeInfo.getId(), snapshot.getId(), snapshot.getUuid()); // Marks the snapshot before anything is done on storage, so that operations refused while a volume has no-copy snapshots (e.g. assigning a backup // offering) also see a take in progress. Then re-checks what such an operation could have changed concurrently. snapshotDetailsDao.addDetail(snapshot.getId(), SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT, Boolean.TRUE.toString(), false); @@ -410,6 +421,14 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { // Once the host has succeeded the volume is on its new file, which is already recorded: the volume is usable even if the snapshot metadata is not. releaseVolume(volumeInfo, succeeded || hostSucceeded ? Volume.Event.OperationSucceeded : Volume.Event.OperationFailed); } + if (!succeeded && (keepVolumeReserved || hostSucceeded)) { + // The snapshot stays, although the failed take releases its resource count. + try { + snapshotDetailsDao.addDetail(snapshot.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED, Boolean.TRUE.toString(), false); + } catch (RuntimeException e) { + logger.warn("Failed to record that the resource count of snapshot [{}] is released.", snapshot.getUuid(), e); + } + } if (hostSucceeded && !succeeded) { logger.error("KVM file-based no-copy snapshot [{}] of volume [{}] was taken on storage, but its metadata could not be fully updated. It is not marked as " + "failed, so that its file (part of the backing chain of the volume) is not cleaned up; deleting the snapshot completes it first.", @@ -500,6 +519,7 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { boolean keepVolumeReserved = false; try { volumeInfo = volumeDataFactory.getVolume(snapshotVO.getVolumeId()); + validateNoIncompleteTakeOfVolume(volumeInfo.getId(), snapshotVO.getId(), snapshotVO.getUuid()); if (snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE) != null) { throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be reverted: a previous delete of it failed during the merge, so its file " + @@ -590,6 +610,11 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { try { // Re-read under the lock: a concurrent delete may have completed while this one waited, and must not be counted twice. SnapshotVO current = snapshotDao.findById(snapshotId); + if (current != null && snapshotDetailsDao.findDetail(snapshotId, KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED) != null) { + // Counted again while it exists, so that the release by this delete (SnapshotManagerImpl#deleteSnapshot) does not count it twice. + resourceLimitService.incrementResourceCount(current.getAccountId(), Resource.ResourceType.snapshot); + snapshotDetailsDao.removeDetail(snapshotId, KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED); + } if (current != null && Snapshot.State.Creating.equals(current.getState())) { // Holding the lock means that no take of it is running any more: the take did not complete (no answer from the host, or a restart). current = completeOrDiscardIncompleteTake(current); @@ -607,6 +632,20 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { } } + /** + * While a take of the volume did not complete, the volume's chain in the DB may be missing one file: taking, reverting or deleting another snapshot of it + * could then build a wrong chain. The incomplete take must be resolved first, by deleting its snapshot. + */ + protected void validateNoIncompleteTakeOfVolume(long volumeId, long snapshotId, String snapshotUuid) { + for (SnapshotVO other : snapshotDao.listByVolumeId(volumeId)) { + if (other.getId() != snapshotId && Snapshot.State.Creating.equals(other.getState()) + && snapshotDetailsDao.findDetail(other.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH) != null) { + throw new InvalidParameterValueException(String.format("Snapshot [%s] cannot be used now: the take of KVM file-based no-copy snapshot [%s] of the same " + + "volume did not complete. Delete snapshot [%s] first (that completes or discards it).", snapshotUuid, other.getUuid(), other.getUuid())); + } + } + } + /** * Resolves a snapshot whose take did not complete, from the files recorded before the host was asked to take it and the current path of its volume (which an * administrator sets after checking the Instance, as the take failure says). @@ -642,9 +681,16 @@ protected SnapshotVO completeOrDiscardIncompleteTake(SnapshotVO snapshotVO) { return null; } List chain = listNoCopySnapshotsOfVolume(volumeVO.getId()); + List chainPaths = chain.stream().map(s -> snapshotStoreDao.findOneBySnapshotAndDatastoreRole(s.getId(), DataStoreRole.Primary)) + .filter(storeRef -> storeRef != null).map(SnapshotDataStoreVO::getInstallPath).collect(Collectors.toList()); + if (!pendingVolumePath.getValue().equals(volumeVO.getPath()) && chainPaths.contains(pendingFrozenPath.getValue())) { + logger.info("The take of KVM file-based no-copy snapshot [{}] did not happen: its file [{}] was frozen by a later snapshot. Discarding the snapshot; the " + + "file [{}], if it exists, is not used and can be deleted.", snapshotVO.getUuid(), pendingFrozenPath.getValue(), pendingVolumePath.getValue()); + removeSnapshotMetadata(snapshotVO); + return null; + } if (!pendingVolumePath.getValue().equals(volumeVO.getPath())) { - boolean frozenByALaterTake = chain.stream().map(s -> snapshotStoreDao.findOneBySnapshotAndDatastoreRole(s.getId(), DataStoreRole.Primary)) - .anyMatch(storeRef -> storeRef != null && pendingVolumePath.getValue().equals(storeRef.getInstallPath())); + boolean frozenByALaterTake = chainPaths.contains(pendingVolumePath.getValue()); throw new InvalidParameterValueException(String.format("KVM file-based no-copy snapshot [%s] did not complete, and volume [%s] is neither on the new " + "file [%s] nor on the file [%s] of the take. %s", snapshotVO.getUuid(), volumeVO.getUuid(), pendingVolumePath.getValue(), pendingFrozenPath.getValue(), frozenByALaterTake ? "Delete the snapshots taken after it first." : "It must be resolved manually.")); @@ -704,6 +750,7 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { volumeInfo = volumeDataFactory.getVolume(volumeVO.getId()); volumeVO = volumeDao.findById(volumeVO.getId()); snapshotStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); + validateNoIncompleteTakeOfVolume(volumeVO.getId(), snapshotVO.getId(), snapshotVO.getUuid()); VMInstanceVO vm = getAttachedVm(volumeInfo); if (vm != null && !VirtualMachine.State.Running.equals(vm.getState()) && !VirtualMachine.State.Stopped.equals(vm.getState())) { @@ -934,6 +981,10 @@ protected Answer sendToHost(long hostId, com.cloud.agent.api.Command command) { } catch (OperationTimedoutException e) { logger.warn("No answer from host [{}] to the command [{}].", hostId, command.getClass().getSimpleName(), e); return null; + } catch (RuntimeException e) { + // E.g. a failure while processing the answer: the host may have executed the command, so its outcome is unknown. + logger.warn("Unexpected failure sending the command [{}] to host [{}]; its outcome is unknown.", command.getClass().getSimpleName(), hostId, e); + return null; } } diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 2b5b759360bb..34e6768c041b 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -63,6 +63,8 @@ import org.mockito.Mockito; import com.cloud.agent.AgentManager; +import com.cloud.configuration.Resource; +import com.cloud.user.ResourceLimitService; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.OperationTimedoutException; import com.cloud.agent.api.Answer; @@ -122,6 +124,7 @@ public class KvmFileBasedNoCopySnapshotStrategyTest { private SnapshotManager snapshotManager; private HostDetailsDao hostDetailsDao; private EndPointSelector endPointSelector; + private ResourceLimitService resourceLimitService; private SnapshotInfo snapshotInfo; private SnapshotVO snapshotVO; @@ -157,6 +160,8 @@ public void setup() { strategy.vmSnapshotDao = vmSnapshotDao; strategy.storagePoolDao = storagePoolDao; strategy.snapshotManager = snapshotManager; + resourceLimitService = mock(ResourceLimitService.class); + strategy.resourceLimitService = resourceLimitService; snapshotVO = mockSnapshotVO(SNAPSHOT_ID, Snapshot.State.BackedUp); when(snapshotVO.getTypeDescription()).thenReturn(Snapshot.Type.MANUAL.name()); @@ -832,6 +837,7 @@ public void takeSnapshotOfRunningVmWithoutAnswerKeepsTheVolumeReserved() { eq(false)); // Not marked as failed: its outcome is unknown, and a failed snapshot could be cleaned up although its file may be in use. verify(strategy, never()).markSnapshotOnPrimaryAsFailed(any()); + verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED, "true", false); verify(snapshotDetailsDao, never()).removeDetail(SNAPSHOT_ID, SnapshotManager.KVM_FILE_BASED_NO_COPY_SNAPSHOT); } @@ -851,6 +857,10 @@ public void sendToHostDistinguishesNotSentFromNoAnswer() throws Exception { when(agentManager.send(HOST_ID, command)).thenThrow(new OperationTimedoutException(new Command[0], HOST_ID, 1L, 10, false)); assertNull(strategy.sendToHost(HOST_ID, command)); + Mockito.reset(agentManager); + when(agentManager.send(HOST_ID, command)).thenThrow(new CloudRuntimeException("failed processing the answer")); + assertNull(strategy.sendToHost(HOST_ID, command)); + Mockito.reset(agentManager); Answer answer = new Answer(null, true, null); when(agentManager.send(HOST_ID, command)).thenReturn(answer); @@ -1011,6 +1021,85 @@ public void deleteOfAnIncompleteTakeFrozenByALaterTakeAsksToDeleteTheLaterOnesFi verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); } + @Test + public void deleteOfASnapshotLeftByAFailedTakeCountsItAgainFirst() { + SnapshotVO creating = mockIncompleteTake("new-delta", VOLUME_PATH, Volume.State.Ready, VOLUME_PATH); + when(creating.getAccountId()).thenReturn(7L); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + when(snapshotDetailsDao.findDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED)) + .thenReturn(new SnapshotDetailsVO(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED, "true", false)); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(resourceLimitService).incrementResourceCount(7L, Resource.ResourceType.snapshot); + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_RESOURCE_COUNT_RELEASED); + } + + @Test + public void deleteOfARegularlyTakenSnapshotDoesNotCountItAgain() { + mockChain(SNAPSHOT_ID); + deleteAndCaptureMerge(); + verify(resourceLimitService, never()).incrementResourceCount(Mockito.anyLong(), any()); + } + + private void mockIncompleteTakeOfAnotherSnapshot(List chain) { + SnapshotVO incomplete = mock(SnapshotVO.class); + when(incomplete.getId()).thenReturn(99L); + when(incomplete.getUuid()).thenReturn("incomplete-snapshot"); + when(incomplete.getState()).thenReturn(Snapshot.State.Creating); + when(snapshotDetailsDao.findDetail(99L, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH)) + .thenReturn(new SnapshotDetailsVO(99L, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH, "new-delta", false)); + List all = new ArrayList<>(chain); + all.add(incomplete); + when(snapshotDao.listByVolumeId(VOLUME_ID)).thenReturn(all); + } + + @Test + public void deleteIsRefusedWhileAnotherTakeOfTheVolumeDidNotComplete() { + mockIncompleteTakeOfAnotherSnapshot(mockChain(SNAPSHOT_ID)); + + InvalidParameterValueException e = assertThrows(InvalidParameterValueException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + assertTrue(e.getMessage().contains("incomplete-snapshot")); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void revertIsRefusedWhileAnotherTakeOfTheVolumeDidNotComplete() { + mockIncompleteTakeOfAnotherSnapshot(mockChain(SNAPSHOT_ID)); + + assertThrows(InvalidParameterValueException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + } + + @Test + public void takeIsRefusedWhileAnotherTakeOfTheVolumeDidNotComplete() { + mockIncompleteTakeOfAnotherSnapshot(new ArrayList<>()); + mockSnapshotOnPrimary(); + + assertThrows(InvalidParameterValueException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(strategy, never()).createSnapshotOnPrimary(any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void deleteOfAnIncompleteTakeWhoseFileWasFrozenByALaterTakeDiscardsIt() { + mockChain(5L); + SnapshotDataStoreVO laterStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(5L, DataStoreRole.Primary); + when(laterStoreRef.getInstallPath()).thenReturn(VOLUME_PATH); + SnapshotVO creating = mockIncompleteTake("new-delta", VOLUME_PATH, Volume.State.Ready, "newer-delta"); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(creating).setState(Snapshot.State.Destroyed); + verify(strategy, never()).sendToHost(anyLong(), any()); + } + @Test public void takeSnapshotRecordsThePendingVolumePathBeforeSendingAndRemovesItOnSuccess() { mockSnapshotOnPrimary(); From bdef27ae7a16bf30330604c25faa6612becf78df Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:38:11 +0000 Subject: [PATCH 07/12] KVM no-copy snapshots: keep volumes reserved when the outcome cannot be saved - The startup cleanup of failed snapshot jobs no longer sets a volume with no-copy snapshots back to Ready, whichever snapshot the failed job was for: a no-copy operation without an answer may hold the volume. - When the host acted but saving its outcome fails (new path of a take on a running Instance, of a revert, or the metadata after a merge), the volume stays reserved with instructions instead of being released with a stale path. - Deleting an incomplete take of an expunged volume deletes its frozen file if the take had happened. - The discard of a take that never reached its host says how to release its volume. Co-Authored-By: Claude Opus 5.5 --- .../orchestration/VolumeOrchestrator.java | 6 ++ .../orchestration/VolumeOrchestratorTest.java | 19 ++++++ .../KvmFileBasedNoCopySnapshotStrategy.java | 62 ++++++++++++++--- ...vmFileBasedNoCopySnapshotStrategyTest.java | 67 +++++++++++++++++++ 4 files changed, 144 insertions(+), 10 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 3a335656fd3c..817621c0bd50 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -2552,6 +2552,12 @@ protected void cleanupVolumeDuringSnapshotFailure(Long volumeId, Long snapshotId String volumeToString = getReflectOnlySelectedFields(volume); + if (volume.getState() == Volume.State.Snapshotting && volumeHasKvmFileBasedNoCopySnapshots(volumeId)) { + // Another operation on its KVM file-based no-copy snapshots (a take or a delete without an answer) may hold the volume deliberately. + logger.warn("Not changing the state of volume [{}] back to Ready, as it has KVM file-based no-copy snapshots: check them, then set its state.", + volumeToString); + return; + } if (volume.getState() == Volume.State.Snapshotting) { logger.debug("Changing volume [{}] state back to Ready.", volumeToString); volume.setState(Volume.State.Ready); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 0b3659195a87..8502a97d6e43 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -1038,6 +1038,25 @@ public void cleanupVolumeDuringSnapshotFailureLeavesVolumesOfKvmFileBasedNoCopyS Mockito.verify(snapshotService).cleanupVolumeDuringSnapshotFailure(1L, 3L); } + @Test + public void cleanupVolumeDuringSnapshotFailureKeepsAVolumeWithKvmFileBasedNoCopySnapshotsReserved() { + SnapshotDetailsDao snapshotDetailsDao = Mockito.mock(SnapshotDetailsDao.class); + SnapshotService snapshotService = Mockito.mock(SnapshotService.class); + volumeOrchestrator.snapshotDetailsDao = snapshotDetailsDao; + volumeOrchestrator._snapshotSrv = snapshotService; + VolumeVO volume = Mockito.mock(VolumeVO.class); + Mockito.when(volume.getState()).thenReturn(Volume.State.Snapshotting); + Mockito.doReturn(volume).when(volumeDao).findById(1L); + // The failed job is of another (regular) snapshot of the volume; a no-copy snapshot operation may hold the volume. + Mockito.doReturn(true).when(volumeOrchestrator).volumeHasKvmFileBasedNoCopySnapshots(1L); + + volumeOrchestrator.cleanupVolumeDuringSnapshotFailure(1L, 3L); + + Mockito.verify(snapshotService).cleanupVolumeDuringSnapshotFailure(1L, 3L); + Mockito.verify(volume, Mockito.never()).setState(Mockito.any()); + Mockito.verify(volumeDao, Mockito.never()).update(Mockito.anyLong(), Mockito.any()); + } + @Test public void checkVolumeIsNotUnderSnapshotOperationAllowsOtherStates() { for (Volume.State state : List.of(Volume.State.Ready, Volume.State.Allocated, Volume.State.Creating)) { diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index 63af8d57664f..5c4975aab3fa 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -394,10 +394,19 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { // The volume is now on the new delta: record it first, so that a later failure can never leave the volume pointing to the frozen file. From here on, // the snapshot is never marked as failed: its frozen file is in the backing chain of the volume and must not be cleaned up as a failed snapshot. + try { + VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); + volumeVO.setPath(newVolumePath); + volumeDao.update(volumeVO.getId(), volumeVO); + } catch (RuntimeException e) { + // The host moved the volume, but the DB does not say so: a running Instance is writing to the new file, so its volume stays reserved. + outcomeUnknown = true; + keepVolumeReserved = vmRunning; + throw new CloudRuntimeException(String.format("KVM file-based no-copy snapshot [%s] was taken on the host, but the new path [%s] of volume [%s] " + + "could not be saved.%s", snapshot.getUuid(), newVolumePath, volumeInfo.getUuid(), vmRunning ? String.format(" The volume stays in state [%s]: " + + "set its path to [%s] and its state to Ready, then delete the snapshot to complete it.", Volume.State.Snapshotting, newVolumePath) : ""), e); + } hostSucceeded = true; - VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); - volumeVO.setPath(newVolumePath); - volumeDao.update(volumeVO.getId(), volumeVO); Long frozenFileSize = ((CreateDiskOnlyVmSnapshotAnswer) answer).getMapVolumeToSnapshotSize().get(volumeInfo.getUuid()); @@ -560,10 +569,18 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { } String newVolumePath = ((RevertDiskOnlyVmSnapshotAnswer) answer).getVolumeObjectTos().get(0).getPath(); - VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); - volumeVO.setPath(newVolumePath); - // The size of the volume and the primary storage resource count are updated by SnapshotManagerImpl#revertSnapshot. - volumeDao.update(volumeVO.getId(), volumeVO); + try { + VolumeVO volumeVO = volumeDao.findById(volumeInfo.getId()); + volumeVO.setPath(newVolumePath); + // The size of the volume and the primary storage resource count are updated by SnapshotManagerImpl#revertSnapshot. + volumeDao.update(volumeVO.getId(), volumeVO); + } catch (RuntimeException e) { + // The host replaced the file of the volume, which may already be deleted: the volume must not be used with its old path. + keepVolumeReserved = true; + throw new CloudRuntimeException(String.format("Volume [%s] was reverted to snapshot [%s] on the host, but its new path [%s] could not be saved. The " + + "volume stays in state [%s]: set its path to [%s] and its state to Ready.", volumeInfo.getUuid(), snapshotVO.getUuid(), newVolumePath, + Volume.State.RevertSnapshotting, newVolumePath), e); + } logger.info("Reverted volume [{}] to KVM file-based no-copy snapshot [{}]: the volume is now on [{}].", volumeInfo.getUuid(), snapshotVO.getUuid(), newVolumePath); succeeded = true; @@ -655,8 +672,25 @@ protected SnapshotVO completeOrDiscardIncompleteTake(SnapshotVO snapshotVO) { SnapshotDetailsVO pendingVolumePath = snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); SnapshotDetailsVO pendingFrozenPath = snapshotDetailsDao.findDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_FROZEN_PATH); VolumeVO volumeVO = volumeDao.findById(snapshotVO.getVolumeId()); - if (pendingVolumePath == null || volumeVO == null) { - logger.info("KVM file-based no-copy snapshot [{}] never reached its host; discarding it.", snapshotVO.getUuid()); + if (pendingVolumePath == null) { + logger.warn("KVM file-based no-copy snapshot [{}] never reached its host; discarding it. If its volume [{}] is still in state [{}] because of this take, " + + "set it back to Ready: its path was not changed.", snapshotVO.getUuid(), snapshotVO.getVolumeId(), Volume.State.Snapshotting); + removeSnapshotMetadata(snapshotVO); + return null; + } + if (volumeVO == null) { + VolumeVO removedVolume = volumeDao.findByIdIncludingRemoved(snapshotVO.getVolumeId()); + if (removedVolume != null && Volume.State.Expunged.equals(removedVolume.getState()) && pendingFrozenPath != null && + !pendingFrozenPath.getValue().equals(removedVolume.getPath())) { + // The take happened (the volume had moved off the frozen file), so the expunge left the frozen file behind. + SnapshotDataStoreVO storeRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(snapshotVO.getId(), DataStoreRole.Primary); + if (storeRef != null) { + storeRef.setInstallPath(pendingFrozenPath.getValue()); + snapshotStoreDao.update(storeRef.getId(), storeRef); + deleteFrozenFileOfExpungedVolume(snapshotVO, storeRef); + } + } + logger.info("The volume of KVM file-based no-copy snapshot [{}] is gone; discarding the snapshot.", snapshotVO.getUuid()); removeSnapshotMetadata(snapshotVO); return null; } @@ -794,7 +828,15 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { "longer be reverted; delete it again to complete the merge.", snapshotVO.getUuid(), volumeVO.getUuid(), getAnswerDetails(answer))); } - updateMetadataAfterMerge(snapshotVO, snapshotStoreRef, childSnapshot, volumeVO); + try { + updateMetadataAfterMerge(snapshotVO, snapshotStoreRef, childSnapshot, volumeVO); + } catch (RuntimeException e) { + // The child file is merged and deleted on the host, but the DB may still point to it. + keepVolumeReserved = true; + throw new CloudRuntimeException(String.format("Snapshot [%s] was merged on the host, but its metadata could not be updated. Volume [%s] stays in state " + + "[%s]: set [%s] as the path of %s (if it is not already), set the volume state to Ready and delete the snapshot again.", snapshotVO.getUuid(), + volumeVO.getUuid(), Volume.State.Snapshotting, parentTO.getPath(), childSnapshot == null ? "the volume" : "snapshot " + childSnapshot.getUuid()), e); + } succeeded = true; return true; } finally { diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 34e6768c041b..4779c6726fe4 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -27,6 +27,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -1100,6 +1101,72 @@ public void deleteOfAnIncompleteTakeWhoseFileWasFrozenByALaterTakeDiscardsIt() { verify(strategy, never()).sendToHost(anyLong(), any()); } + // the host acted, but saving the outcome in the DB failed + + @Test + public void takeSnapshotOfRunningVmWhoseNewPathCannotBeSavedKeepsTheVolumeReserved() { + attachVolumeToVm(); + mockSnapshotOnPrimary(); + CreateDiskOnlyVmSnapshotAnswer answer = mock(CreateDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + doReturn(answer).when(strategy).sendToHost(eq(HOST_ID), any()); + when(volumeDao.update(Mockito.eq(VOLUME_ID), any())).thenThrow(new CloudRuntimeException("database error")); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationSucceeded); + verify(strategy, never()).markSnapshotOnPrimaryAsFailed(any()); + verify(snapshotDetailsDao, never()).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_PENDING_VOLUME_PATH); + } + + @Test + public void revertWhoseNewPathCannotBeSavedKeepsTheVolumeReserved() { + mockChain(SNAPSHOT_ID); + RevertDiskOnlyVmSnapshotAnswer answer = mock(RevertDiskOnlyVmSnapshotAnswer.class); + when(answer.getResult()).thenReturn(true); + VolumeObjectTO revertedTO = new VolumeObjectTO(); + revertedTO.setPath("reverted-delta"); + when(answer.getVolumeObjectTos()).thenReturn(List.of(revertedTO)); + doReturn(answer).when(strategy).sendToHost(anyLong(), any()); + when(volumeDao.update(Mockito.eq(VOLUME_ID), any())).thenThrow(new CloudRuntimeException("database error")); + + CloudRuntimeException e = assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + assertTrue(e.getMessage().contains("reverted-delta")); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void mergeWhoseMetadataCannotBeSavedKeepsTheVolumeReserved() { + mockChain(SNAPSHOT_ID); + doReturn(new Answer(null, true, null)).when(strategy).sendToHost(anyLong(), any()); + when(volumeDao.update(Mockito.eq(VOLUME_ID), any())).thenThrow(new CloudRuntimeException("database error")); + + assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationFailed); + verify(volumeInfo, never()).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void deleteOfAnIncompleteTakeOfAnExpungedVolumeDeletesTheFrozenFile() { + SnapshotVO creating = mockIncompleteTake("new-delta", "frozen-10", Volume.State.Expunged, "new-delta"); + when(snapshotDao.findById(SNAPSHOT_ID)).thenReturn(creating); + when(volumeDao.findById(VOLUME_ID)).thenReturn(null); + SnapshotDataStoreVO storeRef = mock(SnapshotDataStoreVO.class); + when(storeRef.getDataStoreId()).thenReturn(POOL_ID); + when(snapshotStoreDao.findOneBySnapshotAndDatastoreRole(SNAPSHOT_ID, DataStoreRole.Primary)).thenReturn(storeRef); + doNothing().when(strategy).deleteFrozenFileOfExpungedVolume(creating, storeRef); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(storeRef).setInstallPath("frozen-10"); + verify(strategy).deleteFrozenFileOfExpungedVolume(creating, storeRef); + verify(creating).setState(Snapshot.State.Destroyed); + } + @Test public void takeSnapshotRecordsThePendingVolumePathBeforeSendingAndRemovesItOnSuccess() { mockSnapshotOnPrimary(); From d8e8deb74b32aa6a784ce4a89f4187ce76e4acbf Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:52:38 +0000 Subject: [PATCH 08/12] KVM no-copy snapshots: mark a merge incomplete before it starts - Record that a snapshot's merge may be incomplete before asking the host, so that a management server restart during the merge cannot leave the snapshot revertible onto a file that already holds newer data; the mark is removed only when the command was not sent. - If the child of a snapshot is already its merged file (a merge that completed on the host but whose metadata was not updated), deleting the snapshot only updates the metadata instead of merging a file into itself. - Refuse to revert while the volume is on the file of one of its snapshots, as the revert would delete that file. Co-Authored-By: Claude Opus 5.5 --- .../KvmFileBasedNoCopySnapshotStrategy.java | 35 ++++++++++++++--- ...vmFileBasedNoCopySnapshotStrategyTest.java | 38 ++++++++++++++++++- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index 5c4975aab3fa..fb90b144042b 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -541,6 +541,16 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { "snapshots taken after snapshot [%s] before reverting it.", volumeInfo.getUuid(), snapshotVO.getUuid())); } + String volumePath = ((VolumeObjectTO) volumeInfo.getTO()).getPath(); + for (SnapshotVO chainSnapshot : chain) { + SnapshotDataStoreVO chainStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(chainSnapshot.getId(), DataStoreRole.Primary); + if (chainStoreRef != null && volumePath != null && volumePath.equals(chainStoreRef.getInstallPath())) { + // Reverting replaces (and deletes) the current file of the volume, which here is also the file of a snapshot. + throw new CloudRuntimeException(String.format("Volume [%s] is on [%s], which is also the file of snapshot [%s]: delete snapshot [%s] (which completes " + + "an earlier merge) before reverting.", volumeInfo.getUuid(), volumePath, chainSnapshot.getUuid(), chainSnapshot.getUuid())); + } + } + VMInstanceVO vm = getAttachedVm(volumeInfo); if (vm != null && !VirtualMachine.State.Stopped.equals(vm.getState())) { throw new InvalidParameterValueException(String.format("The Instance [%s] of volume [%s] must be stopped to revert snapshot [%s]; it is [%s].", vm.getUuid(), @@ -807,12 +817,26 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { logger.info("Deleting KVM file-based no-copy snapshot [{}] of volume [{}] by merging [{}] into it.", snapshotVO.getUuid(), volumeVO.getUuid(), deltaMergeTree.getChild().getPath()); + if (deltaMergeTree.getChild().getPath().equals(parentTO.getPath())) { + // A previous merge completed on the host but its metadata was not updated, and the child was then set to the merged file: only the metadata is left. + logger.info("The child of KVM file-based no-copy snapshot [{}] is already its merged file [{}]; updating the metadata only.", snapshotVO.getUuid(), + parentTO.getPath()); + updateMetadataAfterMerge(snapshotVO, snapshotStoreRef, childSnapshot, volumeVO); + succeeded = true; + return true; + } + MergeDiskOnlyVmSnapshotCommand command = new MergeDiskOnlyVmSnapshotCommand(List.of(deltaMergeTree), vmRunning, vm != null ? vm.getInstanceName() : null); command.setWait(MERGE_COMMAND_WAIT_SECONDS); - Answer answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); - if (answer == null || !answer.getResult()) { - // The merge may have started: the file of this snapshot may already hold data of its child, so it is no longer a valid point in time. - snapshotDetailsDao.addDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, Boolean.TRUE.toString(), false); + // Recorded before the host acts: once the merge starts, the file of this snapshot may hold data of its child, so it is no longer a valid point in time. + // This also holds if the management server stops before an answer comes back. + snapshotDetailsDao.addDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, Boolean.TRUE.toString(), false); + Answer answer; + try { + answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + } catch (CommandNotSentException e) { + snapshotDetailsDao.removeDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE); + throw e; } if (answer == null) { // The host may still complete the merge and delete the child file: releasing the volume could leave it pointing to a deleted file. @@ -834,7 +858,8 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { // The child file is merged and deleted on the host, but the DB may still point to it. keepVolumeReserved = true; throw new CloudRuntimeException(String.format("Snapshot [%s] was merged on the host, but its metadata could not be updated. Volume [%s] stays in state " + - "[%s]: set [%s] as the path of %s (if it is not already), set the volume state to Ready and delete the snapshot again.", snapshotVO.getUuid(), + "[%s]: set [%s] as the path of %s (if it is not already), set the volume state to Ready and delete the snapshot again, which then only updates " + + "the metadata.", snapshotVO.getUuid(), volumeVO.getUuid(), Volume.State.Snapshotting, parentTO.getPath(), childSnapshot == null ? "the volume" : "snapshot " + childSnapshot.getUuid()), e); } succeeded = true; diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 4779c6726fe4..d54d4a86225e 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -891,8 +891,42 @@ public void deleteSnapshotWhoseHostIsDownReleasesTheVolumeAndKeepsItRevertible() assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); - verify(snapshotDetailsDao, never()).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE), - any(), Mockito.anyBoolean()); + // Recorded before sending, and removed again as nothing was sent. + verify(snapshotDetailsDao).removeDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE); + } + + @Test + public void mergeIsMarkedIncompleteBeforeTheHostIsAsked() { + mockChain(SNAPSHOT_ID); + deleteAndCaptureMerge(); + + InOrder inOrder = Mockito.inOrder(snapshotDetailsDao, strategy); + inOrder.verify(snapshotDetailsDao).addDetail(SNAPSHOT_ID, KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, "true", false); + inOrder.verify(strategy).sendToHost(eq(HOST_ID), any()); + } + + @Test + public void deleteWhoseChildIsAlreadyTheMergedFileOnlyUpdatesTheMetadata() { + mockChain(SNAPSHOT_ID); + volumeTO.setPath("frozen-" + SNAPSHOT_ID); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeVO).setPath("frozen-" + SNAPSHOT_ID); + verify(snapshotVO).setState(Snapshot.State.Destroyed); + verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); + } + + @Test + public void revertIsRefusedWhenTheVolumeIsOnTheFileOfASnapshot() { + mockChain(SNAPSHOT_ID); + volumeTO.setPath("frozen-" + SNAPSHOT_ID); + + assertThrows(CloudRuntimeException.class, () -> strategy.revertSnapshot(snapshotInfo)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); } @Test From 5d8670ebff086e3168323128c9e564fc461b5fb0 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:58:01 +0000 Subject: [PATCH 09/12] KVM no-copy snapshots: refuse chain operations while two chain entries share a file - While a snapshot and its child share a file (a merge completed on the host but not in the metadata, and the child was set to the merged file), take, revert and every delete other than the one completing that merge are refused, as they could delete or replace a file that is still in use. - Choose the host of a merge before recording that it may be incomplete, so that a merge that cannot be sent leaves the snapshot revertible. - Completing an earlier merge does not add the physical size to the child twice. Co-Authored-By: Claude Opus 5.5 --- .../KvmFileBasedNoCopySnapshotStrategy.java | 48 ++++++++++++++----- ...vmFileBasedNoCopySnapshotStrategyTest.java | 39 +++++++++++++++ 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index fb90b144042b..ceb87670c2c4 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -361,7 +361,9 @@ protected SnapshotInfo takeSnapshotInternal(SnapshotInfo snapshot) { // The position of the snapshot in the backing chain, which follows the order of the takes and not the order of the snapshot ids (allocated before // the work is queued). Computed while the volume is reserved. - long sequence = listNoCopySnapshotsOfVolume(volumeInfo.getId()).stream().mapToLong(this::getChainSequence).max().orElse(0L) + 1; + List currentChain = listNoCopySnapshotsOfVolume(volumeInfo.getId()); + validateChainFilesAreDistinct(currentChain, ((VolumeObjectTO) volumeInfo.getTO()).getPath(), volumeInfo.getUuid()); + long sequence = currentChain.stream().mapToLong(this::getChainSequence).max().orElse(0L) + 1; snapshotOnPrimary = createSnapshotOnPrimary(snapshot); VolumeObjectTO volumeTO = (VolumeObjectTO) volumeInfo.getTO(); String oldVolumePath = volumeTO.getPath(); @@ -541,15 +543,8 @@ protected boolean revertSnapshotInternal(SnapshotVO snapshotVO) { "snapshots taken after snapshot [%s] before reverting it.", volumeInfo.getUuid(), snapshotVO.getUuid())); } - String volumePath = ((VolumeObjectTO) volumeInfo.getTO()).getPath(); - for (SnapshotVO chainSnapshot : chain) { - SnapshotDataStoreVO chainStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(chainSnapshot.getId(), DataStoreRole.Primary); - if (chainStoreRef != null && volumePath != null && volumePath.equals(chainStoreRef.getInstallPath())) { - // Reverting replaces (and deletes) the current file of the volume, which here is also the file of a snapshot. - throw new CloudRuntimeException(String.format("Volume [%s] is on [%s], which is also the file of snapshot [%s]: delete snapshot [%s] (which completes " + - "an earlier merge) before reverting.", volumeInfo.getUuid(), volumePath, chainSnapshot.getUuid(), chainSnapshot.getUuid())); - } - } + // Reverting replaces (and deletes) the current file of the volume, which must not also be the file of a snapshot. + validateChainFilesAreDistinct(chain, ((VolumeObjectTO) volumeInfo.getTO()).getPath(), volumeInfo.getUuid()); VMInstanceVO vm = getAttachedVm(volumeInfo); if (vm != null && !VirtualMachine.State.Stopped.equals(vm.getState())) { @@ -659,6 +654,28 @@ public boolean deleteSnapshot(Long snapshotId, Long zoneId) { } } + /** + * The files of the snapshots of a volume and of the volume itself are distinct, except while an earlier merge is completed on storage but not in the + * metadata (the child was then set to the merged file). Until that snapshot is deleted again, which only updates the metadata, any other operation on the + * chain could delete or replace a file that is still in use. + */ + protected void validateChainFilesAreDistinct(List chain, String volumePath, String volumeUuid) { + List files = new ArrayList<>(); + for (SnapshotVO chainSnapshot : chain) { + SnapshotDataStoreVO storeRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(chainSnapshot.getId(), DataStoreRole.Primary); + files.add(storeRef == null ? null : storeRef.getInstallPath()); + } + files.add(volumePath); + for (int i = 0; i < chain.size(); i++) { + String file = files.get(i); + if (file != null && files.subList(i + 1, files.size()).contains(file)) { + throw new CloudRuntimeException(String.format("The file [%s] of KVM file-based no-copy snapshot [%s] of volume [%s] is also used by its child: an " + + "earlier merge was not completed in the metadata. Delete snapshot [%s] first, which completes it.", file, chain.get(i).getUuid(), volumeUuid, + chain.get(i).getUuid())); + } + } + } + /** * While a take of the volume did not complete, the volume's chain in the DB may be missing one file: taking, reverting or deleting another snapshot of it * could then build a wrong chain. The incomplete take must be resolved first, by deleting its snapshot. @@ -826,14 +843,18 @@ protected boolean deleteSnapshotInternal(SnapshotVO snapshotVO) { return true; } + // Any other shared file means an earlier merge is not completed in the metadata: merging now could delete a file that is still in use. + validateChainFilesAreDistinct(chain, volumeTO.getPath(), volumeVO.getUuid()); + MergeDiskOnlyVmSnapshotCommand command = new MergeDiskOnlyVmSnapshotCommand(List.of(deltaMergeTree), vmRunning, vm != null ? vm.getInstanceName() : null); command.setWait(MERGE_COMMAND_WAIT_SECONDS); + long hostId = getHostIdForOperation(volumeInfo, vm); // Recorded before the host acts: once the merge starts, the file of this snapshot may hold data of its child, so it is no longer a valid point in time. // This also holds if the management server stops before an answer comes back. snapshotDetailsDao.addDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE, Boolean.TRUE.toString(), false); Answer answer; try { - answer = sendToHost(getHostIdForOperation(volumeInfo, vm), command); + answer = sendToHost(hostId, command); } catch (CommandNotSentException e) { snapshotDetailsDao.removeDetail(snapshotVO.getId(), KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE); throw e; @@ -940,8 +961,11 @@ protected void updateMetadataAfterMerge(SnapshotVO snapshotVO, SnapshotDataStore } else { SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(childSnapshot.getId(), DataStoreRole.Primary); logger.debug("Snapshot [{}] is now on [{}].", childSnapshot.getUuid(), mergedPath); + if (!mergedPath.equals(childStoreRef.getInstallPath())) { + // Not when completing an earlier merge whose child was already updated. + childStoreRef.setPhysicalSize(childStoreRef.getPhysicalSize() + snapshotStoreRef.getPhysicalSize()); + } childStoreRef.setInstallPath(mergedPath); - childStoreRef.setPhysicalSize(childStoreRef.getPhysicalSize() + snapshotStoreRef.getPhysicalSize()); snapshotStoreDao.update(childStoreRef.getId(), childStoreRef); } removeSnapshotMetadata(snapshotVO); diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index d54d4a86225e..78a08324f8ec 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -918,6 +918,45 @@ public void deleteWhoseChildIsAlreadyTheMergedFileOnlyUpdatesTheMetadata() { verify(volumeInfo).stateTransit(Volume.Event.OperationSucceeded); } + @Test + public void deleteOfAnOlderSnapshotIsRefusedWhileANewerOneSharesItsFileWithTheVolume() { + mockChain(SNAPSHOT_ID, 11L); + volumeTO.setPath("frozen-11"); + + CloudRuntimeException e = assertThrows(CloudRuntimeException.class, () -> strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + assertTrue(e.getMessage().contains("snapshot-11")); + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(snapshotDetailsDao, never()).addDetail(eq(SNAPSHOT_ID), eq(KvmFileBasedNoCopySnapshotStrategy.KVM_FILE_BASED_NO_COPY_SNAPSHOT_MERGE_INCOMPLETE), + any(), Mockito.anyBoolean()); + } + + @Test + public void takeIsRefusedWhileTheVolumeSharesItsFileWithASnapshot() { + mockChain(5L); + volumeTO.setPath("frozen-5"); + mockSnapshotOnPrimary(); + + assertThrows(CloudRuntimeException.class, () -> strategy.takeSnapshot(snapshotInfo)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(volumeInfo).stateTransit(Volume.Event.OperationFailed); + } + + @Test + public void completingAnEarlierMiddleMergeDoesNotCountThePhysicalSizeTwice() { + mockChain(SNAPSHOT_ID, 11L); + SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(11L, DataStoreRole.Primary); + when(childStoreRef.getInstallPath()).thenReturn("frozen-" + SNAPSHOT_ID); + ((SnapshotObjectTO) snapshotDataFactory.getSnapshot(11L, POOL_ID, DataStoreRole.Primary).getTO()).setPath("frozen-" + SNAPSHOT_ID); + + assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); + + verify(strategy, never()).sendToHost(anyLong(), any()); + verify(childStoreRef, never()).setPhysicalSize(Mockito.anyLong()); + verify(childStoreRef).setInstallPath("frozen-" + SNAPSHOT_ID); + } + @Test public void revertIsRefusedWhenTheVolumeIsOnTheFileOfASnapshot() { mockChain(SNAPSHOT_ID); From 613d50c801f8c6e01c653a5e3af08d65213ff331 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:05:48 +0000 Subject: [PATCH 10/12] KVM no-copy snapshots: update the metadata after a merge in one transaction The child update and the removal of the merged snapshot's metadata are now one transaction, so a failure cannot leave the child updated while the snapshot remains. Completing an earlier merge (whose child was set to the merged file by an administrator) therefore always adds the merged size once. Co-Authored-By: Claude Opus 5.5 --- .../KvmFileBasedNoCopySnapshotStrategy.java | 34 +++++++++++-------- ...vmFileBasedNoCopySnapshotStrategyTest.java | 6 ++-- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java index ceb87670c2c4..863b855c9574 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategy.java @@ -78,6 +78,9 @@ import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.user.ResourceLimitService; import com.cloud.utils.Pair; +import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.TransactionCallbackNoReturn; +import com.cloud.utils.db.TransactionStatus; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.VMInstanceVO; @@ -954,21 +957,24 @@ protected DeltaMergeTreeTO createDeltaMergeTree(List chain, int inde */ protected void updateMetadataAfterMerge(SnapshotVO snapshotVO, SnapshotDataStoreVO snapshotStoreRef, SnapshotVO childSnapshot, VolumeVO volumeVO) { String mergedPath = snapshotStoreRef.getInstallPath(); - if (childSnapshot == null) { - logger.debug("Volume [{}] is now on [{}].", volumeVO.getUuid(), mergedPath); - volumeVO.setPath(mergedPath); - volumeDao.update(volumeVO.getId(), volumeVO); - } else { - SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(childSnapshot.getId(), DataStoreRole.Primary); - logger.debug("Snapshot [{}] is now on [{}].", childSnapshot.getUuid(), mergedPath); - if (!mergedPath.equals(childStoreRef.getInstallPath())) { - // Not when completing an earlier merge whose child was already updated. - childStoreRef.setPhysicalSize(childStoreRef.getPhysicalSize() + snapshotStoreRef.getPhysicalSize()); + // One transaction, so that a failure cannot leave the child updated while the snapshot remains (deleting it again would then count its size twice). + Transaction.execute(new TransactionCallbackNoReturn() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + if (childSnapshot == null) { + logger.debug("Volume [{}] is now on [{}].", volumeVO.getUuid(), mergedPath); + volumeVO.setPath(mergedPath); + volumeDao.update(volumeVO.getId(), volumeVO); + } else { + SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(childSnapshot.getId(), DataStoreRole.Primary); + logger.debug("Snapshot [{}] is now on [{}].", childSnapshot.getUuid(), mergedPath); + childStoreRef.setInstallPath(mergedPath); + childStoreRef.setPhysicalSize(childStoreRef.getPhysicalSize() + snapshotStoreRef.getPhysicalSize()); + snapshotStoreDao.update(childStoreRef.getId(), childStoreRef); + } + removeSnapshotMetadata(snapshotVO); } - childStoreRef.setInstallPath(mergedPath); - snapshotStoreDao.update(childStoreRef.getId(), childStoreRef); - } - removeSnapshotMetadata(snapshotVO); + }); } protected void removeSnapshotMetadata(SnapshotVO snapshotVO) { diff --git a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java index 78a08324f8ec..1b874b7efd32 100644 --- a/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java +++ b/engine/storage/snapshot/src/test/java/org/apache/cloudstack/storage/snapshot/KvmFileBasedNoCopySnapshotStrategyTest.java @@ -944,7 +944,7 @@ public void takeIsRefusedWhileTheVolumeSharesItsFileWithASnapshot() { } @Test - public void completingAnEarlierMiddleMergeDoesNotCountThePhysicalSizeTwice() { + public void completingAnEarlierMiddleMergeOnlyUpdatesTheMetadata() { mockChain(SNAPSHOT_ID, 11L); SnapshotDataStoreVO childStoreRef = snapshotStoreDao.findOneBySnapshotAndDatastoreRole(11L, DataStoreRole.Primary); when(childStoreRef.getInstallPath()).thenReturn("frozen-" + SNAPSHOT_ID); @@ -953,8 +953,10 @@ public void completingAnEarlierMiddleMergeDoesNotCountThePhysicalSizeTwice() { assertTrue(strategy.deleteSnapshot(SNAPSHOT_ID, null)); verify(strategy, never()).sendToHost(anyLong(), any()); - verify(childStoreRef, never()).setPhysicalSize(Mockito.anyLong()); + // The size of the merged file was never added (the admin set the path): it is added now. + verify(childStoreRef).setPhysicalSize(200L); verify(childStoreRef).setInstallPath("frozen-" + SNAPSHOT_ID); + verify(snapshotVO).setState(Snapshot.State.Destroyed); } @Test From 02d371ea10ae079dd7786ba8e99ecfaf9c15cc1d Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:15:06 +0000 Subject: [PATCH 11/12] KVM no-copy snapshots: check reserved volumes before listing the usable ones at start The usable volumes of an Instance leave out the volumes in Snapshotting or RevertSnapshotting, so the start check never saw them and the Instance started without such a volume (found in a lab test). The check now runs on all the volumes of the Instance before they are prepared. Co-Authored-By: Claude Opus 5.5 --- .../orchestration/VolumeOrchestrator.java | 8 ++++++-- .../orchestration/VolumeOrchestratorTest.java | 20 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 817621c0bd50..a49aa97641ff 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1907,8 +1907,6 @@ private List getTasks(List vols, Map for (VolumeVO vol : vols) { String volToString = getReflectOnlySelectedFields(vol); - checkVolumeIsNotUnderSnapshotOperation(vol, volToString); - StoragePoolVO assignedPool = null; if (destVols != null) { StoragePool pool = destVols.get(vol); @@ -2306,6 +2304,12 @@ public void prepare(VirtualMachineProfile vm, DeployDestination dest) throws Sto throw new CloudRuntimeException(String.format("ROOT volume is missing, unable to prepare volumes for the VM [%s].", vm.getVirtualMachine())); } + // Checked on all the volumes of the Instance: the usable volumes below leave out the volumes reserved by a snapshot operation, so the Instance would + // otherwise start without them. + for (VolumeVO vol : _volsDao.findByInstance(vm.getId())) { + checkVolumeIsNotUnderSnapshotOperation(vol, getReflectOnlySelectedFields(vol)); + } + List vols = _volsDao.findUsableVolumesForInstance(vm.getId()); VirtualMachine vmInstance = vm.getVirtualMachine(); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 8502a97d6e43..47c2f28d164e 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -26,6 +26,7 @@ import com.cloud.configuration.Resource; import com.cloud.deploy.DeploymentClusterPlanner; +import com.cloud.deploy.DeployDestination; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.StorageAccessException; import com.cloud.host.Host; @@ -47,6 +48,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachineProfile; import com.cloud.utils.Pair; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; @@ -996,6 +998,24 @@ public void checkVolumeIsNotUnderSnapshotOperationAllowsReservedVolumesWithoutKv } } + @Test + public void prepareRefusesToStartAnInstanceWithAVolumeReservedByANoCopySnapshotOperation() { + VirtualMachineProfile profile = Mockito.mock(VirtualMachineProfile.class); + Mockito.when(profile.getId()).thenReturn(MOCK_VM_ID); + VolumeVO root = Mockito.mock(VolumeVO.class); + Mockito.when(volumeDao.findByInstanceAndType(MOCK_VM_ID, Volume.Type.ROOT)).thenReturn(List.of(root)); + VolumeVO reserved = Mockito.mock(VolumeVO.class); + Mockito.when(reserved.getId()).thenReturn(7L); + Mockito.when(reserved.getState()).thenReturn(Volume.State.Snapshotting); + Mockito.when(volumeDao.findByInstance(MOCK_VM_ID)).thenReturn(List.of(reserved)); + Mockito.doReturn(true).when(volumeOrchestrator).volumeHasKvmFileBasedNoCopySnapshots(7L); + + Assert.assertThrows(CloudRuntimeException.class, () -> volumeOrchestrator.prepare(profile, Mockito.mock(DeployDestination.class))); + + // The usable volumes leave the reserved volume out, so it must be checked before they are listed. + Mockito.verify(volumeDao, Mockito.never()).findUsableVolumesForInstance(Mockito.anyLong()); + } + @Test public void volumeHasKvmFileBasedNoCopySnapshotsIgnoresDestroyedAndErrorSnapshots() { SnapshotDao snapshotDao = Mockito.mock(SnapshotDao.class); From ca77067a7644f68ab49f6e0644b585cabe6a2276 Mon Sep 17 00:00:00 2001 From: DRDAVIDBANNER <24955356+DRDAVIDBANNER@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:19:16 +0000 Subject: [PATCH 12/12] KVM no-copy snapshots: say how to resolve a start refused by a reserved volume Co-Authored-By: Claude Opus 5.5 --- .../engine/orchestration/VolumeOrchestrator.java | 10 ++++++---- .../engine/orchestration/VolumeOrchestratorTest.java | 6 +++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index a49aa97641ff..0c06d95a6b30 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1894,10 +1894,12 @@ private static class VolumeTask { * A KVM file-based no-copy snapshot operation that is not serialized with the Instance (deleting or reverting a snapshot of a stopped Instance) may be * replacing or merging the files of the volume: starting the Instance meanwhile would open files that are about to be removed. */ - protected void checkVolumeIsNotUnderSnapshotOperation(VolumeVO vol, String volToString) { + protected void checkVolumeIsNotUnderSnapshotOperation(VolumeVO vol) { if ((Volume.State.Snapshotting.equals(vol.getState()) || Volume.State.RevertSnapshotting.equals(vol.getState())) && volumeHasKvmFileBasedNoCopySnapshots(vol.getId())) { - throw new CloudRuntimeException(String.format("Volume %s is in state %s: the Instance cannot be started until the snapshot operation on it finishes.", - volToString, vol.getState())); + throw new CloudRuntimeException(String.format("Volume %s is in state %s: the Instance cannot be started until the snapshot operation on it finishes. If " + + "no operation is running, a KVM file-based no-copy snapshot operation on it did not complete: check the error of that operation if there is one, " + + "otherwise the details of the volume's snapshots and its backing chain on the storage; set the paths and the volume state as needed, and start " + + "the Instance again.", getReflectOnlySelectedFields(vol), vol.getState())); } } @@ -2307,7 +2309,7 @@ public void prepare(VirtualMachineProfile vm, DeployDestination dest) throws Sto // Checked on all the volumes of the Instance: the usable volumes below leave out the volumes reserved by a snapshot operation, so the Instance would // otherwise start without them. for (VolumeVO vol : _volsDao.findByInstance(vm.getId())) { - checkVolumeIsNotUnderSnapshotOperation(vol, getReflectOnlySelectedFields(vol)); + checkVolumeIsNotUnderSnapshotOperation(vol); } List vols = _volsDao.findUsableVolumesForInstance(vm.getId()); diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 47c2f28d164e..d482abb4b5cf 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -984,7 +984,7 @@ public void checkVolumeIsNotUnderSnapshotOperationRefusesReservedVolumesWithKvmF for (Volume.State state : List.of(Volume.State.Snapshotting, Volume.State.RevertSnapshotting)) { VolumeVO volume = Mockito.mock(VolumeVO.class); Mockito.when(volume.getState()).thenReturn(state); - Assert.assertThrows(CloudRuntimeException.class, () -> volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol")); + Assert.assertThrows(CloudRuntimeException.class, () -> volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume)); } } @@ -994,7 +994,7 @@ public void checkVolumeIsNotUnderSnapshotOperationAllowsReservedVolumesWithoutKv for (Volume.State state : List.of(Volume.State.Snapshotting, Volume.State.RevertSnapshotting)) { VolumeVO volume = Mockito.mock(VolumeVO.class); Mockito.when(volume.getState()).thenReturn(state); - volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol"); + volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume); } } @@ -1082,7 +1082,7 @@ public void checkVolumeIsNotUnderSnapshotOperationAllowsOtherStates() { for (Volume.State state : List.of(Volume.State.Ready, Volume.State.Allocated, Volume.State.Creating)) { VolumeVO volume = Mockito.mock(VolumeVO.class); Mockito.when(volume.getState()).thenReturn(state); - volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume, "vol"); + volumeOrchestrator.checkVolumeIsNotUnderSnapshotOperation(volume); } } }