feat(backup): incremental NAS backup support for KVM#13074
Conversation
Adds the design document for incremental NAS backups using QEMU dirty bitmaps and libvirt's backup-begin API. Reduces daily backup storage 80-95% for large VMs. Refs: apache#12899
NASBackupChainKeys defines the keys this provider stores under the existing backup_details kv table (parent_backup_id, bitmap_name, chain_id, chain_position, type). This keeps the backups table provider-agnostic per the RFC review. nas.backup.full.every is a zone-scoped ConfigKey that controls how often a full backup is taken; the remaining backups in the cycle are incremental. Counts backups (not days), so it works for hourly, daily, and ad-hoc schedules. Default 10. Set to 1 to disable incrementals (every backup is full). Refs: apache#12899
Adds three new optional CLI flags to nasbackup.sh:
-M|--mode <full|incremental>
--bitmap-new <name> (checkpoint to create with this backup)
--bitmap-parent <name> (incremental: parent bitmap to read changes since)
--parent-path <path> (incremental: parent backup file for rebase)
Behavior:
- When -M is omitted, behavior is unchanged (legacy full-only, no checkpoint
created), so existing callers are not affected.
- With -M full + --bitmap-new, a full backup is taken AND a libvirt
checkpoint of that name is registered atomically (via backup-begin's
--checkpointxml), giving the next incremental its starting bitmap.
- With -M incremental, libvirt's <incremental> element references the
parent bitmap; only changed blocks are written. After completion,
qemu-img rebase wires the new file to its parent so the chain on the
NAS is self-describing for restore.
- Stopped VMs cannot use backup-begin; if -M incremental is requested
while VM is stopped, the script falls back to a full and emits
INCREMENTAL_FALLBACK= on stderr so the orchestrator can record it
correctly in the chain.
- The script echoes BITMAP_CREATED=<name> on success so the Java caller
can store it under backup_details (NASBackupChainKeys.BITMAP_NAME).
Works across local file, NFS-file, and LINSTOR primary storage. Ceph RBD
running-VM support is a pre-existing limitation of this script, not
affected by this change.
Refs: apache#12899
Adds the Java side of the incremental NAS backup feature:
TakeBackupCommand
+ mode, bitmapNew, bitmapParent, parentPath fields (null for legacy
callers — script preserves its existing behaviour when these are
omitted).
BackupAnswer
+ bitmapCreated (echoed by the agent on success)
+ incrementalFallback (true when an incremental was requested but the
agent had to fall back to full because the VM was stopped).
LibvirtTakeBackupCommandWrapper
- Forwards the new fields to nasbackup.sh.
- Strips the new BITMAP_CREATED= / INCREMENTAL_FALLBACK= marker lines
out of stdout before the existing numeric-suffix size parser runs,
so the script can keep the same "size as last line(s)" contract.
- Surfaces both markers on the BackupAnswer.
NASBackupProvider
- decideChain(vm) walks backup_details (chain_id, chain_position,
bitmap_name) for the latest BackedUp backup of the VM and decides:
* Stopped VM -> full (libvirt backup-begin needs running QEMU)
* No prior chain -> full (chain_position=0)
* chain_position+1 >= nas.backup.full.every -> new full
* otherwise -> incremental, parent=last bitmap
- Generates timestamp-based bitmap names ("backup-<epoch>") matching
what the script then registers as the libvirt checkpoint name.
- persistChainMetadata() writes parent_backup_id, bitmap_name,
chain_id, chain_position, type into the existing backup_details
key/value table (per the RFC review — no new columns on backups).
- Honours the agent's INCREMENTAL_FALLBACK= signal: re-records the
backup as a full and starts a fresh chain.
- createBackupObject() now takes a type argument so the BackupVO
reflects the actual decision instead of always being "FULL".
Refs: apache#12899
CloudStack rebuilds the libvirt domain XML on every VM start, which means
persistent QEMU dirty bitmaps don't survive a stop/start cycle. Rather
than hooking into the VM start lifecycle (intrusive across the
orchestration layer), this commit handles the missing bitmap *lazily* at
the next backup attempt:
nasbackup.sh
- When -M incremental is requested, the script first checks
`virsh checkpoint-list` for the parent bitmap. If absent, it
recreates the checkpoint on the running domain so libvirt accepts
the <incremental> reference. The next incremental will be larger
than usual (it captures all writes since recreate, not since the
previous incremental) but is correct; subsequent ones return to
normal size.
- On recreation, emits BITMAP_RECREATED=<name> on stdout for the
orchestrator to record.
BackupAnswer
+ bitmapRecreated field surfaced from the agent.
LibvirtTakeBackupCommandWrapper
- Strips BITMAP_RECREATED= line from stdout before size parsing.
- Sets answer.setBitmapRecreated(...).
NASBackupChainKeys
+ BITMAP_RECREATED key for backup_details.
NASBackupProvider
- When the agent reports a recreated bitmap, persists it under
backup_details and logs an info-level message so operators can
correlate larger-than-usual incrementals with VM restarts.
This satisfies the bitmap-loss-on-VM-restart concern from the RFC review
without touching VirtualMachineManager / StartCommand / agent lifecycle.
Refs: apache#12899
Two changes that together let an incremental NAS backup be restored
without manual chain assembly:
scripts/vm/hypervisor/kvm/nasbackup.sh
- qemu-img rebase now writes a backing-file path that is RELATIVE to
the new qcow2's directory (e.g. ../<parent-ts>/root.<uuid>.qcow2)
rather than the absolute path on the current mount point. NAS mount
points are ephemeral (mktemp -d), so an absolute reference would
not resolve when the backup is re-mounted at restore time. Relative
references are resolved by qemu-img against the file's own
directory, so the chain stays valid no matter where the NAS is
mounted next.
- Verifies the parent file exists on the NAS before rebasing.
LibvirtRestoreBackupCommandWrapper
- For file-based primary storage (local, NFS-file), the existing
code rsync'd the source qcow2 to the volume. That copies only the
differential blocks of an incremental, leaving a volume whose
backing-file reference points at a path the primary storage host
doesn't have. Now: detect a backing-chain via qemu-img info JSON
and flatten via 'qemu-img convert -O qcow2', which follows the
chain and produces a self-contained qcow2. Full backups continue
to use rsync (faster, no chain to flatten).
- The block-storage path (RBD/Linstor) already used qemu-img convert
via the QemuImg helper, which auto-flattens chains, so that path
needed no change.
Refs: apache#12899
Adds the delete-with-chain-repair semantics agreed in the RFC review:
scripts/vm/hypervisor/kvm/nasbackup.sh
- New '-o rebase' operation: rebases an existing on-NAS qcow2 onto
a new backing parent. Uses a SAFE rebase (no -u) so the target
absorbs blocks of the about-to-be-deleted parent before the
backing pointer is moved up to the grandparent. Writes the new
backing reference relative to the target's directory so it
survives mount-point changes.
- New CLI flags --rebase-target, --rebase-new-backing (both passed
mount-relative).
RebaseBackupCommand + LibvirtRebaseBackupCommandWrapper
- New agent command that wraps the script's rebase operation. The
provider sends one of these per child that needs re-pointing.
NASBackupProvider.deleteBackup
- Now plans the chain repair before touching files via
computeChainRepair():
* No chain metadata -> single-file delete (legacy behaviour)
* Tail incremental -> single delete, no rebase
* Middle incremental -> rebase immediate child onto our
parent, then delete; shift
chain_position of all later
descendants by -1
* Full with descendants -> refuse unless forced=true; with
forced=true delete full + every
descendant newest-first
- Updates parent_backup_id, chain_position metadata in
backup_details after each rebase so the model in the DB matches
the on-disk chain.
This implements the cascade-delete behaviour requested in @abh1sar's
review point apache#7.
Refs: apache#12899
Adds five new test cases to test_backup_recovery_nas.py covering the
end-to-end behaviour of the incremental NAS backup feature:
* test_incremental_chain_cadence
- Sets nas.backup.full.every=3, takes 5 backups, verifies the
type pattern is FULL, INC, INC, FULL, INC.
* test_restore_from_incremental
- FULL + 2 INCs, each with a marker file. Restores from the
latest INC and verifies all three markers are present
(i.e. qemu-img convert flattened the chain correctly).
* test_delete_middle_incremental_repairs_chain
- Builds FULL, INC1, INC2; deletes INC1 (no force needed);
restores from the surviving INC2 and verifies that markers
from FULL, INC1 (which was deleted), and INC2 are all present
— proving the rebase merged INC1's blocks into INC2.
* test_refuse_delete_full_with_children
- Verifies plain delete of a FULL that has children fails, and
delete with forced=true succeeds and removes the whole chain.
* test_stopped_vm_falls_back_to_full
- Sets cadence to 2, takes one backup (FULL), stops the VM,
triggers another (cadence would say INC). Verifies the second
backup is recorded as FULL because the agent fell back when
backup-begin couldn't run on a stopped VM.
All tests restore nas.backup.full.every to 10 in finally blocks.
Refs: apache#12899
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #13074 +/- ##
======================================
Coverage 3.46% 3.46%
======================================
Files 479 479
Lines 41162 41162
Branches 7793 7793
======================================
Hits 1426 1426
Misses 39543 39543
Partials 193 193
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:
|
|
@jmsperu can you check the build failure. thanks. |
|
@jmsperu |
Phase 6 added a hasBackingChain() check before rsync that uses qemu-img info to detect chained incrementals. The existing testExecuteWithRsyncFailure test mocks Script.runSimpleBashScriptForExitValue to return 0 for any command, so the new qemu-img info check incorrectly evaluates as "has backing chain" and routes the test through the chain-flatten path instead of rsync — the test then asserts a failure that never occurs. Add a clause to the mock that returns 1 (no backing chain) for the qemu-img info backing-filename probe, so the test continues to exercise the rsync path it was designed for.
|
@weizhouapache yes — ready for review. @sureshanaparti — apologies, I missed your earlier ping. The build failure was a unit test in Fixed in d80ed16: the test's CI should be green on the next run. Cc @abh1sar @JoaoJandre @harikrishna-patnala in case you also want to take a look. |
There was a problem hiding this comment.
Pull request overview
Adds incremental backup-chain support to the NAS backup provider for KVM by leveraging libvirt backup-begin with checkpoints/dirty-bitmaps, plus restore/flatten and chain-aware delete/repair semantics.
Changes:
- Introduces backup-chain metadata keys (
NASBackupChainKeys) and zone-scoped cadence confignas.backup.full.every, with orchestration logic to choose full vs incremental and persist chain details inbackup_details. - Extends the KVM agent +
nasbackup.shto support full-with-checkpoint and incremental-with-rebase, plus a new “rebase” operation used for chain repair during delete. - Updates restore logic to detect qcow2 backing chains and flatten via
qemu-img convert, and adds new integration smoke tests for incremental-chain behavior.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| test/integration/smoke/test_backup_recovery_nas.py | Adds incremental-chain smoke tests (cadence, restore, delete-middle repair, forced delete behavior, stopped-VM fallback). |
| scripts/vm/hypervisor/kvm/nasbackup.sh | Adds mode-aware backup (full/incremental), checkpoint creation, incremental rebase, and a new rebase operation for delete-middle chain repair. |
| plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java | Extends restore wrapper tests to exercise the “no backing chain => rsync” path. |
| plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java | Passes incremental args to nasbackup.sh and parses bitmap/fallback markers from script output. |
| plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java | Detects qcow2 backing chains and flattens incrementals during restore using qemu-img convert. |
| plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebaseBackupCommandWrapper.java | New wrapper to run nasbackup.sh -o rebase for chain repair. |
| plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java | Implements full-vs-incremental decisions, stores chain metadata in backup_details, and adds chain-aware delete/repair logic. |
| plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupChainKeys.java | Defines backup_details keys for chain id/position/type/bitmap/parent linkage. |
| docs/rfcs/incremental-nas-backup.md | Adds an RFC document describing incremental NAS backup approach (needs alignment with final implementation). |
| core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java | Adds optional incremental-mode fields (mode/bitmap names/parent path). |
| core/src/main/java/org/apache/cloudstack/backup/RebaseBackupCommand.java | New agent command to rebase a backup qcow2 onto a new backing file for chain repair. |
| core/src/main/java/org/apache/cloudstack/backup/BackupAnswer.java | Adds fields to return bitmap creation/recreation and incremental-fallback markers back to orchestration. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
@bernardodemarco pointed out that design docs / RFCs go in the project wiki or as a separate issue rather than into the source tree. The RFC content has been posted as a comment on the existing tracking issue apache#12899 (which is where the design discussion already lives), and the docs/rfcs/ directory is removed from this PR.
|
@bernardodemarco thanks — good point. Done in 9764025:
PR is now purely the implementation. Updated PR description to drop the doc reference. |
|
@abh1sar a [SL] Jenkins job has been kicked to build packages. It will be bundled with no SystemVM templates. I'll keep you posted as I make progress. |
|
Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 18435 |
|
@jmsperu firstly, thanks for all the work. I see the current PR is targeted for main branch and seems to be in a good state to get this in 4.23 release. On the other hand I'm also thinking if we can somehow make this into current LTS release of 4.22 (the next one 4.22.2) that will help many other users on the current LTS release. I'm thinking of 2 options,
Let me know your thoughts too. |
@harikrishna-patnala I personally would prefer 1. 2 would be higher effort and might delay merging of this PR. |
|
This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch. |
|
@jmsperu Please fix the conflicts also |
| // removing again here would double-handle and destroy delete-pending tombstones, | ||
| // so defer entirely to the provider for those. | ||
| if (backupProvider.handlesChainDeleteResourceAccounting()) { | ||
| return true; |
There was a problem hiding this comment.
ae2a6b2 doesnt fix this issue
| return true; | |
| checkAndGenerateUsageForLastBackupDeletedAfterOfferingRemove(vm, backup); | |
| return true; |
Test Status - 3 JulyAdded tests for Shared Mount Point and Local Storage Remaining - 0
|
…ckpointable storage Addresses abh1sar review: - decideChain: fall back to legacy-full when any VM volume is on storage that cannot carry per-disk checkpoints (Ceph-RBD, Linstor), avoiding regressions. - nasbackup.sh: after a successful incremental, free the now-redundant parent bitmap per-disk via block-dirty-bitmap-remove. This is a clean free, not checkpoint-delete (which would merge the parent into the new bitmap and make the next incremental re-copy already-backed-up regions). Best-effort: a removal failure logs a warning and never fails the backup. - Surface the reclaim: script emits a PARENT_BITMAP_DELETED marker, the wrapper sets BackupAnswer.parentBitmapDeleted, and the provider logs it. Validated: NASBackupProviderTest (18 tests) green; a live libvirt/QEMU 10.0.0 run confirms the parent bitmap is freed without merging and the next incremental still works (incr stays small, chain intact).
|
Thanks @abh1sar — both addressed in 4552c44. 1. Storage guard in 2. Parent-bitmap cleanup: implemented, with one deliberate deviation from the sketch I want to flag. Rather than Validated on a live host (libvirt/QEMU 10.0.0): after the incremental the parent bitmap is gone and only the new one remains, the next incremental still succeeds (chain intact), and incrementals stay small — confirming the free-not-merge behavior. |
|
+1 for Option 1 from me too. Let this land in main first, then I will open a clean cherry-pick PR against |
| # The parent bitmap must be present on EVERY disk's qcow2, not just one of them. A volume | ||
| # snapshot restore (or a partial migration) can wipe the bitmap on some disks while leaving | ||
| # it on others; a plain "is the name anywhere in query-block" check passes in that case and | ||
| # backup-begin then fails on the disk that is missing the bitmap. Require the bitmap on all | ||
| # disks: compare the disk count to the number of disks reporting the bitmap (tests 17/19). | ||
| disk_count=$(virsh -c qemu:///system domblklist "$VM" --details 2>/dev/null | awk '$2=="disk"{c++} END{print c+0}') | ||
| # Count DISKS that actually carry the parent bitmap, not raw name occurrences. query-block | ||
| # lists each disk's bitmap under more than one node, so "grep -o name | wc -l" double-counts: | ||
| # with two disks where only one has the bitmap it returns 2, is misread as present-on-all, and | ||
| # the incremental then fails on the disk missing it (test 19). Parse per-device exactly as | ||
| # LibvirtStartBackupCommandWrapper.getVmDiskPathHasFromCheckpointMap() does (one count per | ||
| # inserted.file whose dirty-bitmaps contains the parent). The trailing "|| echo 0" also keeps a | ||
| # no-match from aborting the script under "set -eo pipefail" before the fallback below runs | ||
| # (a snapshot restore wipes the bitmap on all disks, so nothing matches — tests 17/18). |
There was a problem hiding this comment.
This comment is too verbose and include unnecessary details on changes done between commits.
Compact this to only the most important logic.
There was a problem hiding this comment.
Done in 560c6d3. Compacted to the essential logic and dropped the inter-commit / test-number details.
…ED marker, compact comments, fix usage event on chain delete - nasbackup.sh: remove Linstor branch in the incremental path (Linstor has no incremental support); compact the checkpoint-redefine, per-disk bitmap-count and parent-bitmap-free comments to the essential logic - drop the PARENT_BITMAP_DELETED marker end to end (script echo + counters, wrapper constant/parse/set/strip, BackupAnswer field+accessors, NAS consumer); it only drove a debug log and no orchestrator state, so the parent-bitmap reclaim stays plain best-effort - BackupManagerImpl: call checkAndGenerateUsageForLastBackupDeletedAfterOfferingRemove before returning in the chain-delete-accounting branch, so the usage event still fires when a chain-aware provider deletes the last backup
…cremental # Conflicts: # server/src/main/java/org/apache/cloudstack/backup/BackupManagerImpl.java
|
Merged latest |
|
This pull request has merge conflicts. Dear author, please fix the conflicts and sync your branch with the base branch. |
|
@blueorangutan package |
|
@abh1sar a [SL] Jenkins job has been kicked to build packages. It will be bundled with no SystemVM templates. I'll keep you posted as I make progress. |
|
Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 18488 |
Summary
Implements incremental backup support for the NAS backup provider on KVM, using QEMU dirty bitmaps and libvirt's
backup-beginAPI. RFC: #12899.For large VMs this reduces daily backup storage 80–95% and shortens backup windows from hours to minutes (e.g. a 500 GB VM with moderate writes goes from ~500 GB/day to ~5–15 GB/day after the initial full backup).
What's in the PR
f2a9202d741981469099NASBackupChainKeysconstants + zone-scopednas.backup.full.everyConfigKey (default 10)fbb916b254nasbackup.shmode-aware: full+checkpoint or incremental+rebase viabackup-begin1f2aebca36backup_details43e2f7504a39303fbf88qemu-img convertflatten for file-based primaryb8d069e127RebaseBackupCommand, chain repair for delete-middle, refuse-delete-full-with-children49edc7f22ctest/integration/smoke/test_backup_recovery_nas.pyFull diff: 11 files, +1617 / −30.
Review feedback addressed (all from #12899 thread)
backupsbackup_detailskv table viaNASBackupChainKeysnas.backup.full.interval(days) doesn't fit hourly/ad-hocnas.backup.full.every(default 10)backup-beginfor full backups toobackup-begin; full omits<incremental>backup-<epoch>(System.currentTimeMillis()/1000)block-dirty-bitmap-add--checkpointxml; manual bitmap commands removedqemu-img rebaseafter each incrementalnasbackup.sh, with relative backing path so chain survives mount-point churnINCREMENTAL_FALLBACK=if cadence asked for incforced=truevirsh checkpoint-list, recreates if missing, emitsBITMAP_RECREATED=test_backup_recovery_nas.pyBackwards compatibility
-M/--bitmap-*flags onnasbackup.share optional. Without them, the script preserves the legacy full-only behaviour exactly (no checkpoint creation, same XML).TakeBackupCommandnew fields default to null;LibvirtTakeBackupCommandWrapperonly emits the new flags when set, so a 4.22 management server talking to a 4.23 agent still works.chain_idinbackup_details) are treated as standalone fulls by the cascade-delete logic — no migration needed.Test plan
Environment
feature/nas-backup-incrementalagainstmain(4.23-SNAPSHOT)ol8 mgmt + kvm-ol8profile)backup-begin --checkpointxml)Automated coverage
NASBackupProviderTestLibvirtRestoreBackupCommandWrapperTesttest/integration/smoke/test_backup_recovery_nas.pyrequired_hardware="true"Smoke scenarios
test_incremental_chain_cadencenas.backup.full.every=3and 5 backups, observed type sequence is['FULL','INCREMENTAL','INCREMENTAL','FULL','INCREMENTAL']test_restore_from_incrementaltest_delete_middle_incremental_repairs_chainparent_idis repointed to the surviving ancestor, backing file is rebased, downstream restore still correcttest_refuse_delete_full_with_childrenCloudRuntimeException;forced=truecascadestest_stopped_vm_falls_back_to_fullManual scenarios (outside smoke scope)
full.every=10; take 25 backups across 5 daysbackup_detailscarries no chain keysnas.backup.incremental.enabled=falsezone-scopedvirsh checkpoint-create; INC succeeds; restore from this INC is correctnasbackup.shlegacy invocation-M/--bitmap-*Backwards-compat checks
TakeBackupCommandnew fields default null → 4.22 agents ignore them (covered by Scenario B).chain_idinbackup_detailsare treated as standalone FULLs; cascade-delete short-circuits without touching them.RebaseBackupCommandis only sent when chain metadata is present, so a downgraded agent never receives it.Results
Test results from running this plan will be posted as a follow-up comment after execution.
Refs