Repository navigation
KVM: opt-in no-copy volume snapshots on file-based primary storage - #14804
DRDAVIDBANNER wants to merge 12 commits into
Conversation
Adds the storage-pool setting kvm.file.based.volume.snapshot.no.copy (default false). When it is enabled, volume snapshots of KVM QCOW2 volumes on NFS, SharedMountPoint and Filesystem pools that are kept only on primary storage are taken in the backing chain of the volume instead of as full copies. Taking and reverting such a snapshot no longer copies the volume, and deleting it merges it with its child. - New KvmFileBasedNoCopySnapshotStrategy, reusing the disk-only Instance snapshot agent commands for one volume. - KVM agent: disk-only snapshot XML lists every other disk of the domain with snapshot='no', so that Libvirt does not implicitly move the volumes that are not snapshotted. Advertised as host.kvm.diskonlysnapshot.singlevolume; running Instances only get no-copy snapshots on hosts that advertise it. - Only the latest no-copy snapshot of a volume can be reverted, so its snapshots stay a single chain. - While a volume has no-copy snapshots, volume and Instance storage migration, Instance snapshots and reverting regular snapshots are refused, and the no-copy snapshots cannot be archived, copied or used to create volumes, templates or Instances. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Congratulations on your first Pull Request and welcome to the Apache CloudStack community! If you have any issues or are unsure about any anything please check our Contribution Guide (https://github.com/apache/cloudstack/blob/main/CONTRIBUTING.md)
|
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved findings expose snapshot-chain corruption through unsafe backup interactions, concurrency races, incorrect ancestry ordering, and ignored state-transition failures, while volume cleanup can orphan frozen files.
5 open issues
Add reciprocal validation for backup assignment, attachment, and restore · New Abort snapshot creation when the volume state transition fails · New Reserve the volume before reading snapshot chains and paths · New Order snapshots by backing-chain sequence, not allocated ID · New Delete frozen snapshot files when expunging a volume · New
Review effort: Balanced
| 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; | ||
| } |
There was a problem hiding this comment.
Agreed, and fixed in d2d98c3, hardened in af6af90 and 03baae1. 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 (
validateBackupVolumesandrestoreBackupToVM); - 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.
|
|
||
| logger.info("Taking KVM file-based no-copy snapshot [{}] of volume [{}].", snapshot.getUuid(), volumeInfo.getUuid()); | ||
|
|
||
| volumeInfo.stateTransit(Volume.Event.SnapshotRequested); |
There was a problem hiding this comment.
Agreed, fixed in d2d98c3. 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 03baae1 it never throws.
Tests: takeSnapshotIsAbortedWhenTheVolumeReservationLosesARace, revertSnapshotIsAbortedWhenTheVolumeReservationLosesARace and deleteSnapshotIsAbortedWhenTheVolumeReservationLosesARace. Each one verifies that no command is sent and nothing is released.
| 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); |
There was a problem hiding this comment.
Agreed, fixed in d2d98c3. 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 (02d371e). A delete re-reads the snapshot under its lock, so two concurrent deletes cannot both succeed (2860d5f).
Tests: revertReadsTheChainOnlyAfterReservingTheVolume and deleteReadsTheChainOnlyAfterReservingTheVolume (in-order verification), plus the race tests above.
| 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)) |
There was a problem hiding this comment.
Agreed: the ids follow allocation order, not take order. Fixed in d2d98c3. 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.
| 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; |
There was a problem hiding this comment.
Agreed, fixed in d2d98c3 and af6af90. 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.
…backup checks, expunge cleanup - Take, revert and delete reserve the volume (Ready -> Snapshotting/RevertSnapshotting) before reading its chain and paths, and abort without sending any command when the reservation fails or loses a race (stateTransit returns false). - Each take records its position in the backing chain (snapshot detail kvmFileBasedNoCopySnapshotSequence), computed while the volume is reserved. The chain is ordered by it instead of by snapshot id, since ids follow allocation order. - When the volume was expunged, deleting a no-copy snapshot deletes its own frozen file (DeleteDiskOnlyVmSnapshotCommand, pool-relative path) before dropping its metadata. - Backup offerings: assigning an offering, restoring a backup and attaching to an Instance with an offering are refused while the volumes have no-copy snapshots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #14804 +/- ##
============================================
+ Coverage 20.80% 20.85% +0.04%
- Complexity 20925 21020 +95
============================================
Files 6053 6054 +1
Lines 548466 548849 +383
Branches 73283 73349 +66
============================================
+ Hits 114129 114465 +336
- Misses 420977 420982 +5
- Partials 13360 13402 +42
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…on, lost answers, KBOSS restore, unmanage - VM start refuses volumes in Snapshotting/RevertSnapshotting (VolumeOrchestrator): deleting or reverting a snapshot of a stopped Instance is not serialized with its start. Revert also requires the Instance to be Stopped. - Every volume move path in VolumeServiceImpl (copy, migrate, migrate with the Instance, including the implicit migrations at start and HA) refuses volumes with no-copy snapshots. - The merge command waits as long as the agent's merge timeout. Without an answer, take (running Instance), revert and delete keep the volume reserved and say what to check; a failed merge marks the snapshot as not revertible. - Take marks the snapshot before working on storage and re-reads the backup offering; assigning an offering re-checks after committing and undoes itself if a no-copy snapshot appeared. The restore check also covers KBOSS. - Unmanaging a volume with no-copy snapshots is refused, and frozen files are only deleted for expunged volumes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Record the pending volume path before the host acts, and never mark a snapshot as failed once the host has moved the volume onto its new file. - Marking a snapshot as failed can no longer throw from the finally block. - Re-read the snapshot under its lock, so a concurrent second delete fails. - Skip no-copy snapshots in the Error-snapshot cleanup and in the volume cleanup of failed snapshot jobs at management server start. - Refuse to start an Instance only while a volume with no-copy snapshots is reserved by a snapshot operation. - Volume import also matches pool-relative snapshot paths. - Refuse to attach a volume with no-copy snapshots to an Instance that is not stopped, checked again in the attach job. - The Instance snapshot job checks the volumes again and removes the allocated Instance snapshot if one now has no-copy snapshots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e incomplete takes - Send commands with AgentManager#send: a command that was not sent (host down or disconnected) is a plain failure that releases the volume; only a command sent without an answer keeps the volume reserved. - Record both files of a take before asking the host. Deleting a snapshot whose take did not complete now completes it (the volume is on the new file) or discards it (the volume is still on its old file), once its volume is Ready again. - A definite take failure is a regular failed snapshot: the no-copy marks are removed, so the regular Error-snapshot cleanup applies. - Releasing the volume in finally blocks never throws. - Undoing a raced backup offering assignment clears the DB even if the provider fails, and reports the provider failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tions until resolved - A take that fails but leaves its snapshot in place (no answer, or the metadata update failed after the host succeeded) records that the failed take released its resource count; deleting the snapshot counts it again first, so the delete does not release it twice. - Taking, reverting or deleting a snapshot of a volume is refused while another take of that volume did not complete, since its chain in the DB may be missing a file; deleting the incomplete snapshot resolves it. - An incomplete take whose frozen file was frozen by a later take did not happen, and is discarded. - Any other failure sending a command (e.g. while processing its answer) is treated as an unknown outcome. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…be saved - The startup cleanup of failed snapshot jobs no longer sets a volume with no-copy snapshots back to Ready, whichever snapshot the failed job was for: a no-copy operation without an answer may hold the volume. - When the host acted but saving its outcome fails (new path of a take on a running Instance, of a revert, or the metadata after a merge), the volume stays reserved with instructions instead of being released with a stale path. - Deleting an incomplete take of an expunged volume deletes its frozen file if the take had happened. - The discard of a take that never reached its host says how to release its volume. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Record that a snapshot's merge may be incomplete before asking the host, so that a management server restart during the merge cannot leave the snapshot revertible onto a file that already holds newer data; the mark is removed only when the command was not sent. - If the child of a snapshot is already its merged file (a merge that completed on the host but whose metadata was not updated), deleting the snapshot only updates the metadata instead of merging a file into itself. - Refuse to revert while the volume is on the file of one of its snapshots, as the revert would delete that file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s share a file - While a snapshot and its child share a file (a merge completed on the host but not in the metadata, and the child was set to the merged file), take, revert and every delete other than the one completing that merge are refused, as they could delete or replace a file that is still in use. - Choose the host of a merge before recording that it may be incomplete, so that a merge that cannot be sent leaves the snapshot revertible. - Completing an earlier merge does not add the physical size to the child twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…action The child update and the removal of the merged snapshot's metadata are now one transaction, so a failure cannot leave the child updated while the snapshot remains. Completing an earlier merge (whose child was set to the merged file by an administrator) therefore always adds the merged size once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le ones at start The usable volumes of an Instance leave out the volumes in Snapshotting or RevertSnapshotting, so the start check never saw them and the Instance started without such a volume (found in a lab test). The check now runs on all the volumes of the Instance before they are prepared. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed volume Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>


Description
This PR adds an opt-in way to take volume snapshots of KVM QCOW2 volumes on file-based primary storage (NFS, SharedMountPoint and Filesystem) without copying the volume.
Today, a volume snapshot of such a volume that is kept only on primary storage (
snapshot.backup.to.secondary=false) is a full copy.KVMStorageProcessorrunsqemu-img convertof the whole volume into thesnapshotsdirectory of the pool, and reverting copies the whole snapshot back (LibvirtRevertSnapshotCommandWrapper). Both take time proportional to the size of the volume, so tens of minutes for a volume of a few hundred GB or more. The disk-only Instance snapshots for file-based storage (#9524, #10632) already avoid the copy by keeping the snapshot in the backing chain of the volume. But an Instance snapshot covers all the volumes of the Instance and blocks attaching, detaching and migrating volumes, adding and removing NICs, and taking volume snapshots, so it cannot replace a volume snapshot in workflows that do those things.With the new setting
kvm.file.based.volume.snapshot.no.copy(storage pool scope, defaultfalse), a volume snapshot is taken the same way as one volume of a disk-only Instance snapshot:virDomainSnapshotCreateXMLcall (disk-only, atomic, no metadata) for that disk. For a stopped Instance, or a detached volume, it isqemu-img create -b. Nothing is copied.blockcommitif the Instance is running andqemu-img commitandrebaseotherwise. The cost is proportional to the data written after the snapshot, not to the size of the volume.Because the snapshot travels with the volume (only
volumes.pathchanges), the volume can still be detached, attached to another Instance, or attached as the root volume while it has such snapshots.Implementation
KvmFileBasedNoCopySnapshotStrategy(engine/storage/snapshot),HIGHESTpriority:TAKE: only when the setting is enabled for the pool of the volume and all of these hold:
kvm.incremental.snapshotis false;In every other case the existing strategies are used, as today.
REVERT/DELETE/BACKUP of the snapshots it created: these are marked with the snapshot detail
kvmFileBasedNoCopySnapshot.CreateDiskOnlyVmSnapshotCommand,RevertDiskOnlyVmSnapshotCommandandMergeDiskOnlyVmSnapshotCommand, called for a single volume. No new agent commands.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY, Libvirt also takes an external snapshot of the disks that are not listed in the snapshot XML, which would move them onto files CloudStack does not know about.LibvirtComputingResource#createSnapshotXmlAndNewVolumePathMapnow lists every other disk of the domain withsnapshot='no'. CD-ROMs and floppies are skipped. When all the volumes are snapshotted, as disk-only Instance snapshots do, the XML is unchanged.host.kvm.diskonlysnapshot.singlevolume(synced byAgentManagerImpllike the NVRAM capability). A no-copy snapshot of a running Instance is only taken on a host that advertises it; otherwise the regular snapshot is taken.kvmFileBasedNoCopySnapshotSequence) while the volume is reserved.VolumeOrchestratorrefuses to start an Instance while a volume that has no-copy snapshots is in Snapshotting or RevertSnapshotting, since deleting or reverting a snapshot of a stopped Instance is not otherwise serialized with its start. Volumes without no-copy snapshots are not affected. Revert requires the Instance to be Stopped. A delete re-reads the snapshot under its lock, so two concurrent deletes of one snapshot cannot both succeed.qcow2.delta.merge.timeout, 72 h by default). Commands are sent withAgentManager#send, so a command that was never sent (host down or disconnected) is told apart from one that got no answer: the former is a plain failure that releases the volume.VMSnapshotManagerImpl#allocVMSnapshot, checked again in the Instance snapshot job, which then removes the allocated Instance snapshot). Without this guard,StorageVMSnapshotStrategycould accept such an Instance snapshot, and reverting it would replace the top of the chain;VolumeServiceImpl(copy, migrate, and migrate with the Instance), so it also covers the implicit migrations when an Instance is started or restarted by HA on another pool, besides the API checks formigrateVolume,migrateVirtualMachineandmigrateVirtualMachineWithVolume;unmanageVolume), and listing or importing a frozen file as an unmanaged volume (listVolumesForImport/importVolumenow also match the pool-relative paths these snapshots record);deleteSnapshotfor the volume's primary snapshot refs after the volume is removed. For no-copy snapshots, the strategy then deletes each snapshot's own frozen file withDeleteDiskOnlyVmSnapshotCommand(pool-relative path) before dropping its metadata. That only happens for expunged volumes, and template files are never touched.Limitations (possible follow-ups)
qemu-img convertof the snapshot file flattens its backing chain, but it needs its own testing.Documentation (cloudstack-documentation) to follow once the behaviour is agreed.
Types of changes
Feature/Enhancement Scale or Bug Severity
Feature/Enhancement Scale
Screenshots (if appropriate):
How Has This Been Tested?
Unit tests:
KvmFileBasedNoCopySnapshotStrategyTest(new, 91 tests):canHandlematrix for every eligibility condition, including the host capability;VolumeOrchestratorTest: the start check on all the volumes of the Instance, and the startup cleanup leaving volumes with no-copy snapshots alone.LibvirtComputingResourceTest: snapshot XML excludes the other disks withsnapshot='no', skips CD-ROMs, and is unchanged when all disks are snapshotted.SnapshotManagerImplTestandSnapshotManagerTest: detail lookup, volume check, the validation helpers, and refusal to revert a regular snapshot while the volume has no-copy snapshots.AgentManagerImplTest: the new capability is stored from the ReadyAnswer.VMSnapshotManagerTest: Instance snapshots are refused, at allocation and again in the job, while a volume of the Instance has no-copy snapshots.BackupManagerTest: backup offering assignment is refused, and undone after a concurrent take, even if the provider fails.VolumeApiServiceImplTest: attach to an Instance that is not stopped or has a backup offering is refused.StorageManagerImplTest: the cleanup of snapshots in Error skips no-copy snapshots.VolumeImportUnmanageManagerImplTest: unmanage is refused, and import listing matches pool-relative snapshot paths.VolumeServiceTest,TemplateManagerImplTest,UserVmManagerImplTest: the move, template and deploy guards.These 14 test classes (1349 tests) pass on the final head, with checkstyle.
Manual testing, on a lab zone built for this PR. Debian packages were built from this branch (head of this PR) and installed on Ubuntu 24.04 VMs (libvirt 10.0.0, QEMU 8.2.2, MySQL 8.0):
The zone was Advanced, with an L2 guest network,
snapshot.backup.to.secondary=falseand the new setting enabled on the pools. The checks were scripted, and 57 of 58 checks passed. The one failure was a check of the error text, not of the behaviour: CloudStack reports a refused start as a generic start failure, with the reason only in the management server log. With the check fixed, T10 to T13 were run again on the same build and all 14 passed.Capability: the host advertises
host.kvm.diskonlysnapshot.singlevolume.Take on a running Instance: the snapshot of one data volume of a running Instance with three disks is BackedUp in about 2.4 s. The volume moves onto a new delta backed by the frozen file. The domain's other disks and their DB paths are unchanged, and the frozen file keeps the data written before the snapshot.
Guards: refused are
migrateVolumeto another pool,migrateVirtualMachineof the stopped Instance to another pool,createVolumeandcreateTemplatefrom the snapshot, Instance snapshots while a volume has no-copy snapshots (no Instance snapshot record is left), and revert of a snapshot that is not the latest.Snapshot travels with the volume: the volume with an open snapshot is detached, the Instance's ROOT is detached, and the volume is attached as ROOT (deviceid 0). The Instance boots on the volume's delta, and the data written after the snapshot is live.
Revert (2.2 s): after stopping the Instance, revert puts the volume on a new delta over the snapshot, and the pre-snapshot data is back. The original layout is then restored and the Instance started again.
Delete on a running Instance, three snapshots:
Live data stays intact throughout.
Stopped Instance and detached volume: take, revert and delete work through the
qemu-imgpath.Setting disabled: snapshots are regular copies and the volume path is unchanged.
Concurrency (detached volume, so no per-Instance work queue serialises the calls):
After each case the DB and the storage agree: the volume is the top of its chain, and the live snapshots are exactly the files under it.
Attach: hot-attaching a volume with no-copy snapshots to a running Instance is refused; attaching it to a stopped Instance works.
Reserved volume at start: while such a volume is in Snapshotting, as after a take without an answer, its Instance does not start; once the volume is Ready, it starts. Before this was fixed, a start silently left the reserved volume out, because the usable volumes of an Instance exclude it.
Expunge: deleting a volume with two no-copy snapshots leaves none of its three files on the pool, and the snapshots are gone.
Timing and checksums on an 8 GiB volume holding 6 GiB of data, attached to the running Instance (revert with the Instance stopped). The content after each revert and delete was compared with its sha256 at take time; it matched in every case.
The no-copy times are mostly the test's 2-second polling of the async jobs. The stock take and revert copy the whole volume, so they grow with its size; the no-copy ones do not. Deleting a no-copy snapshot costs time in proportion to the data written since it was taken.
The libvirt behaviour behind the agent fix was also checked on its own with the same libvirt and QEMU versions. With the previous XML, a disk-only snapshot that lists only one disk moved the domain's other two disks onto new overlays. With the new XML, only the listed disk moved.
How did you try to break this feature and the system with this change?
KvmFileBasedStorageVmSnapshotStrategyalready refuses Instance snapshots of volumes with snapshots. Manual testing showed thatStorageVMSnapshotStrategywould still accept one, hence the new check inVMSnapshotManagerImpl#allocVMSnapshot.snapshot.backup.to.secondaryis not dynamic, so it needs a management server restart before no-copy snapshots are taken. The new setting is dynamic, but setting values are cached for 30 s.