DRDAVIDBANNER commented on code in PR #14804:
URL: https://github.com/apache/cloudstack/pull/14804#discussion_r4684857514


##########
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}).
+ * <br/><br/>
+ * 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.
+ * <br/><br/>
+ * 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<Storage.StoragePoolType> 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;
+        }

Review Comment:
   Agreed, and fixed in d2d98c3a48, hardened in af6af900c1 and 03baae18f4. The 
check now works in both directions:
   - assigning a backup offering to an Instance whose volumes have no-copy 
snapshots is refused (`BackupManagerImpl#assignVMToBackupOffering`). A take 
marks its snapshot before working on storage and re-reads the offering, and the 
assignment re-checks after it commits and undoes itself. So a take and an 
assignment running at the same time cannot both succeed;
   - restoring a backup onto such volumes is refused, for every provider 
including KBOSS (`validateBackupVolumes` and `restoreBackupToVM`);
   - attaching a volume with no-copy snapshots to an Instance that has a backup 
offering is refused (`VolumeApiServiceImpl#attachVolumeToVM`, checked again in 
the attach job).
   
   Tests: 
`BackupManagerTest#testAssignVMToBackupOfferingRefusedWhenAVolumeHasKvmFileBasedNoCopySnapshots`,
 `#testUndoAssignmentWhenANoCopySnapshotAppearedConcurrently` and 
`VolumeApiServiceImplTest#attachVolumeWithKvmFileBasedNoCopySnapshotsToVmWithBackupOfferingIsRefused`.
   



##########
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}).
+ * <br/><br/>
+ * 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.
+ * <br/><br/>
+ * 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<Storage.StoragePoolType> 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);

Review Comment:
   Agreed, fixed in d2d98c3a48. Take, revert and delete now reserve the volume 
through `reserveVolume`. If `stateTransit` returns false, it aborts before any 
snapshot record is created or any command is sent. It also turns an invalid 
transition into a clear "volume is in state X" error. The release in `finally` 
only runs after a successful reservation, and since 03baae18f4 it never throws.
   
   Tests: `takeSnapshotIsAbortedWhenTheVolumeReservationLosesARace`, 
`revertSnapshotIsAbortedWhenTheVolumeReservationLosesARace` and 
`deleteSnapshotIsAbortedWhenTheVolumeReservationLosesARace`. Each one verifies 
that no command is sent and nothing is released.
   



##########
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}).
+ * <br/><br/>
+ * 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.
+ * <br/><br/>
+ * 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<Storage.StoragePoolType> 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<SnapshotVO> 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<SnapshotVO> 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);

Review Comment:
   Agreed, fixed in d2d98c3a48. Delete and revert now reserve the volume first: 
Ready to Snapshotting, or to RevertSnapshotting. That reservation also excludes 
takes, other deletes, attach and migration, because all of them require Ready. 
Only then do they reload the volume, the chain and the store refs and build the 
merge tree or the revert TO. A validation failure after the reservation 
releases it with `OperationFailed`.
   
   Starting the Instance is excluded too, while such a volume is reserved 
(02d371ea10). A delete re-reads the snapshot under its lock, so two concurrent 
deletes cannot both succeed (2860d5f721).
   
   Tests: `revertReadsTheChainOnlyAfterReservingTheVolume` and 
`deleteReadsTheChainOnlyAfterReservingTheVolume` (in-order verification), plus 
the race tests above.
   



##########
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}).
+ * <br/><br/>
+ * 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.
+ * <br/><br/>
+ * 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<Storage.StoragePoolType> 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<SnapshotVO> 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<SnapshotVO> 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<SnapshotVO> 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<DataTO> 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<SnapshotDataStoreVO> 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<SnapshotVO> 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))

Review Comment:
   Agreed: the ids follow allocation order, not take order. Fixed in 
d2d98c3a48. Each take now records its position in the chain as a snapshot 
detail, `kvmFileBasedNoCopySnapshotSequence`. It is computed as the maximum 
existing sequence plus one while the volume is reserved, so two takes cannot 
both compute it. The chain is ordered by that sequence, with the id only as a 
fallback.
   
   Tests: `chainIsOrderedByTakeSequenceNotById`, 
`revertOfTheLatestTakeIsAllowedEvenWithALowerId`, 
`revertOfAnOlderTakeIsRefusedEvenWithAHigherId`, 
`deleteMergeTreeFollowsTheTakeSequence` and 
`takeSnapshotRecordsTheNextChainSequence`.
   



##########
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}).
+ * <br/><br/>
+ * 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.
+ * <br/><br/>
+ * 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<Storage.StoragePoolType> 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<SnapshotVO> 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;

Review Comment:
   Agreed, fixed in d2d98c3a48 and af6af900c1. 
`VolumeServiceImpl#deleteVolumeCallback` removes the volume before calling 
`deleteSnapshot` for its primary snapshot refs, so the metadata-only branch 
leaked the frozen files.
   
   When the volume is expunged, the strategy now deletes the snapshot's own 
frozen file first, with `DeleteDiskOnlyVmSnapshotCommand` on a host that can 
reach the pool. That command resolves the pool-relative path, unlike 
`DeleteCommand`, which expects an absolute path. Only then does it drop the 
metadata. If the file cannot be deleted, the metadata is kept so the delete can 
be retried. A volume that was removed without being expunged (e.g. unmanaged) 
only loses the metadata.
   
   Template files are never touched: every frozen file is a file the volume 
itself owned when the snapshot was taken, and no-copy snapshots cannot be used 
to create volumes or templates.
   
   Tests: `deleteSnapshotOfExpungedVolumeDeletesItsFrozenFile`, 
`deleteSnapshotOfRemovedButNotExpungedVolumeOnlyRemovesMetadata` and 
`deleteSnapshotOfExpungedVolumeKeepsMetadataWhenTheFileCannotBeDeleted`. In the 
lab, expunging a volume with two no-copy snapshots leaves none of its three 
files on the pool.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to