Skip to content

Nas backup: Fix restore-and-attach of a backed up volume on NFS, Linstor and Ceph primary storages - #14007

Merged
weizhouapache merged 1 commit into
apache:4.22from
shapeblue:restore-single-volume
Sep 9, 2026
Merged

weizhouapache merged 1 commit into
apache:4.22from
shapeblue:restore-single-volume

Conversation

@abh1sar

@abh1sar abh1sar commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Description

Restoring a volume from a backup and attaching it to a VM doesn't work since the restore commands were changed to run without a shell in 56ad044

  1. getDeviceToAttachDisk pipes virsh domblklist through awk, but passes the awk program still wrapped in the single quotes a shell would have stripped. Run directly, awk fails with "invalid char" and returns nothing, so the device name is empty and charAt throws StringIndexOutOfBoundsException before any attach is attempted. This affects every storage type. The exit value was also never checked, and the output not trimmed, so even a working awk would leave the trailing line separator and increment that instead of the device letter.

  2. The RBD branch passes the literal string "<<EOF%sEOF" as a virsh argument. The placeholder is never substituted with the disk XML, and a here-document cannot work without a shell, so virsh is handed a bogus argument and fails. The XML is now written to a temporary file that virsh reads.

  3. The Linstor branch declares "--subdriver qcow2", inverting the previous behaviour where Linstor got a raw attach and every other pool got qcow2. A Linstor volume is a raw DRBD block device, so libvirt rejects it with "Image is not in qcow2 format". The condition is restored, along with the "--driver qemu" that was dropped.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)
  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (improves an existing feature and functionality)
  • Cleanup (Code refactoring and cleanup, that may add test cases)
  • Build/CI
  • Test (unit or integration test code)

Feature/Enhancement Scale or Bug Severity

Feature/Enhancement Scale

  • Major
  • Minor

Bug Severity

  • BLOCKER
  • Critical
  • Major
  • Minor
  • Trivial

Screenshots (if appropriate):

How Has This Been Tested?

Before fix:

  1. awk quoting — getDeviceToAttachDisk (breaks restore-and-attach on all storage)

API

  Error restoring volume [0965ff84-c3e2-4bbe-acfe-a2ae239f61fb] of VM [7b3f859c-1560-42c7-b2e0-61138e2cb8d1]                               
  to host [294e5d7b-3581-46be-b33b-b1df6965a563] using backup provider [nas] due to: [].                                                   
  Note the empty [] — the details are lost, which is part of what makes it hard to diagnose.    

Agent log:

  java.lang.StringIndexOutOfBoundsException: String index out of range: -1                                                                 
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)                                                                   
        at com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRestoreBackupCommandWrapper.getDeviceToAttachDisk(LibvirtRestoreBackupCommandWr
  java:401)                                                                                                                                
        at com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRestoreBackupCommandWrapper.attachVolumeToVm(LibvirtRestoreBackupCommandWrapper
  368)                                                                                                                                     
        at                                                                                                                                 
  com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRestoreBackupCommandWrapper.restoreVolume(LibvirtRestoreBackupCommandWrapper.java:192)  
  Root cause at OS level (observed on nas-h1, output truncated at 70 chars by my harness):                                                 
  awk: cmd. line:1: '{print $1}'                                                                                                           
  awk: cmd. line:1: ^ invalid char ''' in         
  1. RBD <<EOF%sEOF (Ceph only; only reachable once 1 is fixed)

Agent log:

  Executing command [/usr/bin/virsh attach-device i-2-5-VM /dev/stdin <<EOF%sEOF ].                                                        
  Execution of process [1818313] for command [...] failed.                                                                                 
  Exit value of process [...] is [1].                                                                                                      
  API (observed):                                                                                                                          
  Error restoring volume [...] ... due to: [Failed to attach volume to VM: i-2-5-VM].                                                      
                                               
  1. Linstor --subdriver qcow2 inversion (LINSTOR only; also only reachable after 1)

Agent log:

  Execution of process [7761] for command [/usr/bin/virsh attach-disk i-2-9-VM                                                             
  /dev/drbd/by-res/cs-742678da-c440-4d2b-b63a-5ecbe10ba206/0 vdb --subdriver qcow2 --cache none ] failed.                                  
  ... encountered the error: [1].                                                                                                          
  libvirt's own message, when I ran that command by hand (observed):                                                                       
  error: Failed to attach disk                                                                                                             
  error: internal error: unable to execute QEMU command 'blockdev-add': Image is not in qcow2 format                                       
  API: same Failed to attach volume to VM: i-2-9-VM shape as above.     

After fix:
Restore and attach volume works as expected on all 3 NFS, Linstor and Ceph primary storages

How did you try to break this feature and the system with this change?

Restoring a volume from a backup and attaching it to a VM has been broken
since the restore commands were changed to run without a shell, in three
independent ways.

getDeviceToAttachDisk pipes virsh domblklist through awk, but passes the awk
program still wrapped in the single quotes a shell would have stripped. Run
directly, awk fails with "invalid char" and returns nothing, so the device
name is empty and charAt throws StringIndexOutOfBoundsException before any
attach is attempted. This affects every storage type. The exit value was also
never checked, and the output not trimmed, so even a working awk would leave
the trailing line separator and increment that instead of the device letter.

The RBD branch passes the literal string "<<EOF%sEOF" as a virsh argument. The
placeholder is never substituted with the disk XML, and a here-document cannot
work without a shell, so virsh is handed a bogus argument and fails. The XML is
now written to a temporary file that virsh reads.

The Linstor branch declares "--subdriver qcow2", inverting the previous
behaviour where Linstor got a raw attach and every other pool got qcow2. A
Linstor volume is a raw DRBD block device, so libvirt rejects it with "Image is
not in qcow2 format". The condition is restored, along with the "--driver qemu"
that was dropped.
@codecov

codecov Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 17.80%. Comparing base (7ea1dca) to head (ec83614).
⚠️ Report is 20 commits behind head on 4.22.

Files with missing lines Patch % Lines
...ce/wrapper/LibvirtRestoreBackupCommandWrapper.java 75.00% 5 Missing and 4 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               4.22   #14007      +/-   ##
============================================
+ Coverage     17.79%   17.80%   +0.01%     
- Complexity    15995    16002       +7     
============================================
  Files          5928     5928              
  Lines        534306   534323      +17     
  Branches      65383    65387       +4     
============================================
+ Hits          95069    95130      +61     
+ Misses       428467   428418      -49     
- Partials      10770    10775       +5     
Flag Coverage Δ
uitests 3.69% <ø> (ø)
unittests 18.88% <75.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@abh1sar

abh1sar commented Aug 29, 2026

Copy link
Copy Markdown
Contributor Author

@blueorangutan package

@blueorangutan

Copy link
Copy Markdown

@abh1sar a [SL] Jenkins job has been kicked to build packages. It will be bundled with KVM, XenServer and VMware SystemVM templates. I'll keep you posted as I make progress.

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 19016

@abh1sar
abh1sar requested review from shwstppr and weizhouapache and a lite review from Copilot August 29, 2026 16:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes KVM restore-and-attach of volumes restored from backup after prior changes switched virsh/awk invocation to run without a shell, which broke device detection and certain storage-specific attach flows (notably Ceph RBD and Linstor).

Changes:

  • Fixes getDeviceToAttachDisk so awk is invoked without shell quotes, trims output before incrementing the device letter, and fails fast when no device is detected.
  • Fixes Ceph RBD attach by writing the generated disk XML to a temporary file and passing that file to virsh attach-device (instead of a non-functional here-doc argument).
  • Restores correct attach options by omitting --subdriver qcow2 for Linstor (raw DRBD) while using qcow2 for file-backed pools; adds --driver qemu.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java Fixes shell-less command execution issues affecting device discovery and storage-type-specific attach behavior (RBD, Linstor).
plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java Adds unit tests covering device selection trimming/awk quoting and storage-specific attach command construction.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@andrijapanicsb

Copy link
Copy Markdown
Contributor

wow, I just see this now. @abh1sar do we have a issue loggeds for this? Sounds serious for any Veeam customers relying on it.

Is there anything I can help with? cc @shwstppr @weizhouapache - how did this slip the 4.23 voting 😢

@shwstppr shwstppr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code lgtm

@shwstppr

shwstppr commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

wow, I just see this now. @abh1sar do we have a issue loggeds for this? Sounds serious for any Veeam customers relying on it.

Is there anything I can help with? cc @shwstppr @weizhouapache - how did this slip the 4.23 voting 😢

@andrijapanicsb I think this got into the security release, and then we proceeded 4.23 as there is a workaround someone referred to.

@abh1sar

abh1sar commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

wow, I just see this now. @abh1sar do we have a issue loggeds for this? Sounds serious for any Veeam customers relying on it.

Is there anything I can help with? cc @shwstppr @weizhouapache - how did this slip the 4.23 voting 😢

@andrijapanicsb this only affects Nas backup provider, and only the restore and attach single volume workflow.
Full volume restore works.
so as a workaround user can create a new instance from backup (restoring all volumes) and use the volume that was required to be restored.

@weizhouapache

Copy link
Copy Markdown
Member

wow, I just see this now. @abh1sar do we have a issue loggeds for this? Sounds serious for any Veeam customers relying on it.
Is there anything I can help with? cc @shwstppr @weizhouapache - how did this slip the 4.23 voting 😢

@andrijapanicsb this only affects Nas backup provider, and only the restore and attach single volume workflow. Full volume restore works. so as a workaround user can create a new instance from backup (restoring all volumes) and use the volume that was required to be restored.

thanks @abh1sar for the explanation.

@andrijapanicsb it is mentioned in the 4.23.0.0 release note: https://docs.cloudstack.apache.org/en/4.23.0.0/releasenotes/about.html

@andrijapanicsb

Copy link
Copy Markdown
Contributor

Ah cool, thx @abh1sar and all, so doesn't affect Veeam, and we have a workaround. Good to know! 🙏

@abh1sar abh1sar changed the title Fix restore-and-attach of a backed up volume on NFS, Linstor and Ceph primary storages Nas backup: Fix restore-and-attach of a backed up volume on NFS, Linstor and Ceph primary storages Sep 3, 2026
@weizhouapache weizhouapache self-assigned this Sep 7, 2026
@weizhouapache

Copy link
Copy Markdown
Member

@blueorangutan package

@blueorangutan

Copy link
Copy Markdown

@weizhouapache a [SL] Jenkins job has been kicked to build packages. It will be bundled with KVM, XenServer and VMware SystemVM templates. I'll keep you posted as I make progress.

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 19153

@weizhouapache

Copy link
Copy Markdown
Member

@blueorangutan test

@blueorangutan

Copy link
Copy Markdown

@weizhouapache a [SL] Trillian-Jenkins test job (ol8 mgmt + kvm-ol8) has been kicked to run smoke tests

weizhouapache added a commit to weizhouapache/cloudstack that referenced this pull request Sep 9, 2026
test_backup_recovery_nas.py only allowed NFS primary storage, since it
reused the primary storage pool's own path as the NAS backup repository
address, and always required incremental-backup semantics that only
qcow2/NFS storage can provide. Neither holds on Ceph/RBD.

- setUpClass now accepts RBD alongside NFS as the primary storage pool
  type, picking a pool that's actually Up rather than list()[0] --
  environments that added Ceph/RBD after the zone's original NFS
  primary storage keep that old pool around in Disabled state, and it
  still sorts first, silently exercising its path as if it were the
  storage VMs actually deploy on.
- The NAS backup repository's NFS export address is resolved
  independently of the primary storage: when the primary pool isn't NFS,
  reuse the nfs test data entry (services[nfs][url]) -- the same
  temporary NFS mount point test_primary_storage.py uses for its
  temporary NFS primary storage pool, and something every marvin
  environment already has configured. An explicit
  nas_backup_repository_address test data entry or
  NAS_BACKUP_REPO_ADDRESS environment variable, if set, takes precedence.
- The external offering imported in setUpClass is matched to the
  repository just created by externalid (== the repository's own id
  for the nas provider) rather than blindly taking index 0 -- a stray
  repository left over from an earlier interrupted run, whose backups
  didn't get cleaned up so its own teardown couldn't remove it either,
  sorts alongside the new one with no guarantee of which comes first.
- Incremental NAS backups require QEMU dirty bitmaps / libvirt
  checkpoints, which only exist on file-based qcow2 storage
  (NASBackupProvider.allVolumesOnCheckpointCapableStorage). The six
  incremental-chain tests now skip on RBD/Ceph, where the provider
  always falls back to full-only backups server-side, rather than
  failing on assertions that storage type can never satisfy.
- Added test_restore_volume_and_attach_to_vm, which exercises
  restoreVolumeFromBackupAndAttachToVM end-to-end (restoring a backed-up
  ROOT and DATADISK volume onto a second, stopped Instance) -- the API
  that drives the restore-and-attach code fixed by the previous commit
  (apache#14007). The target Instance is stopped with
  forced=True: a graceful ACPI stop was observed to time out (~2
  minutes) before falling back to a hard destroy anyway, and once
  forced to a hard destroy the domain drops out of libvirt entirely,
  so the periodic ping-based PowerState sync the restore call depends
  on falls back to a much slower heuristic well past any reasonable
  wait. A forced stop destroys the domain immediately and
  deterministically.
@weizhouapache

Copy link
Copy Markdown
Member

tested ok on ceph and NFS

for 4.23/main, #14094 is required

added a smoke test: fff8e56

@blueorangutan

blueorangutan commented Sep 9, 2026 •

Copy link
Copy Markdown

[SF] Trillian test result (tid-16932)
Environment: kvm-ol8 (x2), zone: Advanced Networking with Mgmt server ol8
Total time taken: 55405 seconds
Marvin logs: [archive removed]
Smoke tests completed. 149 look OK, 0 have errors, 0 did not run
Only failed and skipped tests results shown below:

Test Result Time (s) Test File

@weizhouapache
weizhouapache merged commit c7f2efa into apache:4.22 Sep 9, 2026
42 of 43 checks passed
@github-project-automation github-project-automation Bot moved this from Ready to Done in CloudStack Testing Sep 9, 2026
@abh1sar
abh1sar deleted the restore-single-volume branch September 30, 2026 15:45
weizhouapache pushed a commit to weizhouapache/cloudstack that referenced this pull request Oct 12, 2026
Restoring a volume from a backup and attaching it to a VM has been broken
since the restore commands were changed to run without a shell, in three
independent ways.

getDeviceToAttachDisk pipes virsh domblklist through awk, but passes the awk
program still wrapped in the single quotes a shell would have stripped. Run
directly, awk fails with "invalid char" and returns nothing, so the device
name is empty and charAt throws StringIndexOutOfBoundsException before any
attach is attempted. This affects every storage type. The exit value was also
never checked, and the output not trimmed, so even a working awk would leave
the trailing line separator and increment that instead of the device letter.

The RBD branch passes the literal string "<<EOF%sEOF" as a virsh argument. The
placeholder is never substituted with the disk XML, and a here-document cannot
work without a shell, so virsh is handed a bogus argument and fails. The XML is
now written to a temporary file that virsh reads.

The Linstor branch declares "--subdriver qcow2", inverting the previous
behaviour where Linstor got a raw attach and every other pool got qcow2. A
Linstor volume is a raw DRBD block device, so libvirt rejects it with "Image is
not in qcow2 format". The condition is restored, along with the "--driver qemu"
that was dropped.
weizhouapache added a commit to weizhouapache/cloudstack that referenced this pull request Oct 12, 2026
test_backup_recovery_nas.py only allowed NFS primary storage, since it
reused the primary storage pool's own path as the NAS backup repository
address, and always required incremental-backup semantics that only
qcow2/NFS storage can provide. Neither holds on Ceph/RBD.

- setUpClass now accepts RBD alongside NFS as the primary storage pool
  type, picking a pool that's actually Up rather than list()[0] --
  environments that added Ceph/RBD after the zone's original NFS
  primary storage keep that old pool around in Disabled state, and it
  still sorts first, silently exercising its path as if it were the
  storage VMs actually deploy on.
- The NAS backup repository's NFS export address is resolved
  independently of the primary storage: when the primary pool isn't NFS,
  reuse the nfs test data entry (services[nfs][url]) -- the same
  temporary NFS mount point test_primary_storage.py uses for its
  temporary NFS primary storage pool, and something every marvin
  environment already has configured. An explicit
  nas_backup_repository_address test data entry or
  NAS_BACKUP_REPO_ADDRESS environment variable, if set, takes precedence.
- The external offering imported in setUpClass is matched to the
  repository just created by externalid (== the repository's own id
  for the nas provider) rather than blindly taking index 0 -- a stray
  repository left over from an earlier interrupted run, whose backups
  didn't get cleaned up so its own teardown couldn't remove it either,
  sorts alongside the new one with no guarantee of which comes first.
- Incremental NAS backups require QEMU dirty bitmaps / libvirt
  checkpoints, which only exist on file-based qcow2 storage
  (NASBackupProvider.allVolumesOnCheckpointCapableStorage). The six
  incremental-chain tests now skip on RBD/Ceph, where the provider
  always falls back to full-only backups server-side, rather than
  failing on assertions that storage type can never satisfy.
- Added test_restore_volume_and_attach_to_vm, which exercises
  restoreVolumeFromBackupAndAttachToVM end-to-end (restoring a backed-up
  ROOT and DATADISK volume onto a second, stopped Instance) -- the API
  that drives the restore-and-attach code fixed by the previous commit
  (apache#14007). The target Instance is stopped with
  forced=True: a graceful ACPI stop was observed to time out (~2
  minutes) before falling back to a hard destroy anyway, and once
  forced to a hard destroy the domain drops out of libvirt entirely,
  so the periodic ping-based PowerState sync the restore call depends
  on falls back to a much slower heuristic well past any reasonable
  wait. A forced stop destroys the domain immediately and
  deterministically.
weizhouapache added a commit that referenced this pull request Nov 24, 2026
* smoke test: support ceph storage pools

* test: fix test failures

* test: add volume migration which has been fixed

* test: support Ceph/RBD primary storage in NAS backup smoke test

test_backup_recovery_nas.py only allowed NFS primary storage, since it
reused the primary storage pool's own path as the NAS backup repository
address, and always required incremental-backup semantics that only
qcow2/NFS storage can provide. Neither holds on Ceph/RBD.

- setUpClass now accepts RBD alongside NFS as the primary storage pool
  type, picking a pool that's actually Up rather than list()[0] --
  environments that added Ceph/RBD after the zone's original NFS
  primary storage keep that old pool around in Disabled state, and it
  still sorts first, silently exercising its path as if it were the
  storage VMs actually deploy on.
- The NAS backup repository's NFS export address is resolved
  independently of the primary storage: when the primary pool isn't NFS,
  reuse the nfs test data entry (services[nfs][url]) -- the same
  temporary NFS mount point test_primary_storage.py uses for its
  temporary NFS primary storage pool, and something every marvin
  environment already has configured. An explicit
  nas_backup_repository_address test data entry or
  NAS_BACKUP_REPO_ADDRESS environment variable, if set, takes precedence.
- The external offering imported in setUpClass is matched to the
  repository just created by externalid (== the repository's own id
  for the nas provider) rather than blindly taking index 0 -- a stray
  repository left over from an earlier interrupted run, whose backups
  didn't get cleaned up so its own teardown couldn't remove it either,
  sorts alongside the new one with no guarantee of which comes first.
- Incremental NAS backups require QEMU dirty bitmaps / libvirt
  checkpoints, which only exist on file-based qcow2 storage
  (NASBackupProvider.allVolumesOnCheckpointCapableStorage). The six
  incremental-chain tests now skip on RBD/Ceph, where the provider
  always falls back to full-only backups server-side, rather than
  failing on assertions that storage type can never satisfy.
- Added test_restore_volume_and_attach_to_vm, which exercises
  restoreVolumeFromBackupAndAttachToVM end-to-end (restoring a backed-up
  ROOT and DATADISK volume onto a second, stopped Instance) -- the API
  that drives the restore-and-attach code fixed by the previous commit
  (#14007). The target Instance is stopped with
  forced=True: a graceful ACPI stop was observed to time out (~2
  minutes) before falling back to a hard destroy anyway, and once
  forced to a hard destroy the domain drops out of libvirt entirely,
  so the periodic ping-based PowerState sync the restore call depends
  on falls back to a much slower heuristic well past any reasonable
  wait. A forced stop destroys the domain immediately and
  deterministically.

* test: fix test_10_list_volumes for zone-wide storage pools

A zone-wide storage pool (e.g. RBD configured with scope=ZONE) isn't
bound to a single pod/cluster, so a volume on it has no clustername/
clusterid/podid/podname. test_10_list_volumes asserted these were
always non-None, which fails whenever storage is zone-scoped rather
than cluster-scoped. Now look up the volume's actual storage pool and
only assert pod/cluster attributes when its scope isn't ZONE.

* test_host_tags: fix cleanup to handle None host tags

When a host has no explicit tags initially, cls.host.hosttags is None.
Passing None to the API does not set the hosttags parameter, so tags
are never cleared during cleanup. Convert None to empty string to properly
clear tags that were set during the test.

* test: support zone-wide storage pools in test_list_storage_pools

Zone-wide storage pools (scope=ZONE) are not bound to clusters or pods.
When filtering by clusterid/podid, these pools may be included in results
with clusterid=None and podid=None. Updated tests to:

- test_01: Accept zone-wide pools in clusterid filter results
- test_07: Accept zone-wide pools in podid filter results
- test_12: New test validating zone-wide vs cluster-scoped pools

Both invalid clusterid/podid filters now correctly return zone-wide pools,
and assertions skip None values for zone-wide pools while validating
cluster-scoped pools have their expected scope identifiers.

Validated on two environments:
- Zone-wide only (10.1.112.155): 12/12 tests passed
- Cluster-scoped only (10.0.112.202): 12/12 tests passed

* smoke test: cover RBD/librbd volume encryption in TestVolumeEncryption

TestVolumeEncryption previously skipped entirely on RBD storage pools.
Now that RBD encryption is supported (PR #13556), extend it instead of
skipping:

- setUpClass no longer hard-skips RBD pools; records storage_pool_type
  for use by the assertions below.
- check_volume_encryption() branches on pool type: RBD volumes are
  encrypted natively by librbd, so the domain XML carries
  <encryption format='luks2' engine='librbd'>; other pool types keep
  the existing qemu-native <encryption format='luks'> check.
- does_host_with_encryption_support_exists() gained an RBD-specific
  path: the API's "encryptionsupported" field only reflects qemu-native
  LUKS support, so librbd capability is read from the host_details
  table (host.volume.encryption.rbd), joined on the host's uuid.
- get_expected_guest_visible_size() centralizes the existing PowerFlex
  size-overhead adjustment and adds the equivalent for RBD: encrypted
  RBD volumes reserve a 16 MiB LUKS2 header out of the volume's own
  reported size, so the guest sees size - header.
- test_03_root_and_data_volume_encryption now also exercises resize of
  the attached encrypted data volume, reusing its VM instead of
  spinning up a separate one:
  - online (VM stays running): verified via the volume's own API state
    and size, since picking up a live virtio-blk capacity change in the
    guest depends on the guest OS/kernel (the CentOS 5.5 template used
    here predates reliable live-resize notification) and is orthogonal
    to whether CloudStack/libvirt/qemu actually grew the volume.
  - offline (detach, resize, reattach): verified against the guest's
    fdisk output, matched by the expected byte count rather than a
    device letter derived from deviceid, since libvirt is not
    guaranteed to reuse the same target letter after a detach then
    reattach.

* test: run unmanage/import VM lifecycle test on KVM too

* test: merge the direct download deploy tests into one test

Deploy a VM from the direct download template on each type of storage found
(NFS, RBD, SharedMountPoint and local) in a single test, using the storage
pool type as the storage tag.

* test: sync the data to disk before taking the VM snapshot

A disk-only VM snapshot does not contain the guest page cache, so the file
written by the test may be missing after the revert.

* test: address review comments on the Ceph smoke tests

Assert that the encryption format and passphrase secret lists of TestVolumeEncryption are not empty, instead of asserting they are not None, which findall() never returns. Compare the storage pool type case-insensitively, give the direct download test a unique storage tag, skip the live VM migration test for every RBD source pool, and drop an unused variable in test_list_storage_pools.
weizhouapache added a commit that referenced this pull request Nov 25, 2026
* test: support Ceph/RBD primary storage in NAS backup smoke test

test_backup_recovery_nas.py only allowed NFS primary storage, since it
reused the primary storage pool's own path as the NAS backup repository
address, and always required incremental-backup semantics that only
qcow2/NFS storage can provide. Neither holds on Ceph/RBD.

- setUpClass now accepts RBD alongside NFS as the primary storage pool
  type, picking a pool that's actually Up rather than list()[0] --
  environments that added Ceph/RBD after the zone's original NFS
  primary storage keep that old pool around in Disabled state, and it
  still sorts first, silently exercising its path as if it were the
  storage VMs actually deploy on.
- The NAS backup repository's NFS export address is resolved
  independently of the primary storage: when the primary pool isn't NFS,
  reuse the nfs test data entry (services[nfs][url]) -- the same
  temporary NFS mount point test_primary_storage.py uses for its
  temporary NFS primary storage pool, and something every marvin
  environment already has configured. An explicit
  nas_backup_repository_address test data entry or
  NAS_BACKUP_REPO_ADDRESS environment variable, if set, takes precedence.
- The external offering imported in setUpClass is matched to the
  repository just created by externalid (== the repository's own id
  for the nas provider) rather than blindly taking index 0 -- a stray
  repository left over from an earlier interrupted run, whose backups
  didn't get cleaned up so its own teardown couldn't remove it either,
  sorts alongside the new one with no guarantee of which comes first.
- Incremental NAS backups require QEMU dirty bitmaps / libvirt
  checkpoints, which only exist on file-based qcow2 storage
  (NASBackupProvider.allVolumesOnCheckpointCapableStorage). The six
  incremental-chain tests now skip on RBD/Ceph, where the provider
  always falls back to full-only backups server-side, rather than
  failing on assertions that storage type can never satisfy.
- Added test_restore_volume_and_attach_to_vm, which exercises
  restoreVolumeFromBackupAndAttachToVM end-to-end (restoring a backed-up
  ROOT and DATADISK volume onto a second, stopped Instance) -- the API
  that drives the restore-and-attach code fixed by the previous commit
  (#14007). The target Instance is stopped with
  forced=True: a graceful ACPI stop was observed to time out (~2
  minutes) before falling back to a hard destroy anyway, and once
  forced to a hard destroy the domain drops out of libvirt entirely,
  so the periodic ping-based PowerState sync the restore call depends
  on falls back to a much slower heuristic well past any reasonable
  wait. A forced stop destroys the domain immediately and
  deterministically.

* KVM: support incremental NAS backups of RBD volumes

Incremental NAS backups so far relied on QEMU dirty bitmaps / libvirt
checkpoints, which only exist on file-based qcow2 storage. RBD images are
raw and have nowhere to persist a bitmap, so any VM with a volume on Ceph
was forced onto the full-only path and re-uploaded the whole image on every
cycle.

Ceph provides the equivalent natively, and this adds a second chain format
that uses it: an `rbd snap` per cycle as the anchor plus
`rbd export-diff --from-snap`, which computes the changed extents inside
Ceph from the image object-map. NASBackupProvider now selects the mechanism
per VM via getIncrementalFlavor() - QCOW2 for checkpoint-capable pools, RBD
for Ceph, UNSUPPORTED (legacy full-only) for mixed or other storage, since
the two formats cannot be mixed inside one backup. Everything else - chain
identity, the nas.backup.full.every cadence, delete/tombstone semantics and
resource accounting - is shared unchanged.

Restore differs because an export-diff stream carries no pointer to the diff
before it, unlike a rebased qcow2. The provider therefore sends the whole
chain from its full anchor up to the backup being restored, and the agent
recreates the image and replays each diff with `rbd import-diff` in order.
The image has to be recreated: a full diff only carries the extents that
were allocated when it was taken, so any block still allocated in the target
would otherwise show through as stale data. That also drops RBD snapshots
the volume carried, which is inherent to rewinding a volume wholesale.

Two behaviours follow from the anchor living in Ceph rather than in the QEMU
process: a stopped VM keeps its incremental cadence (no live QEMU needed),
and a chain survives a VM restart or host migration. Only the newest anchor
is kept per image; a full additionally sweeps every older snapshot carrying
the csbackup- prefix, so a deleted chain, an unassigned offering or a
restore cannot leak snapshots.

The feature stays behind the existing nas.backup.incremental.enabled zone
setting, which still defaults to false.

Note: the agent drives the `rbd` CLI, so KVM hosts backing up Ceph volumes
need ceph-common installed.

Verified on a Ceph Reef 18.2.8 cluster with KVM hosts on Ceph Quincy
17.2.7 clients: FULL 1.86 GB followed by incrementals of 71 KB - 2.6 MB,
restores replaying 2- and 3-diff chains across two RBD pools including
through a tombstoned ancestor.

test_backup_recovery_nas.py: the blanket RBD skip is replaced by an
_is_rbd_storage() predicate, so the five chain tests now run on Ceph.
test_stopped_vm_falls_back_to_full keeps a targeted skip because RBD has the
opposite behaviour by design, and a new
test_stopped_rbd_vm_keeps_incremental_cadence asserts that other side.

* test: run the NAS backup smoke test on a cloud-init template

The suite registered the legacy CentOS 5.5 tiny template via get_template().
Its kernel/udev does not reliably enumerate hot-attached virtio disks and it
ships no mkfs.ext4, so the chain tests needed guest-side workarounds to reach
the data they back up and restore.

Register the Ubuntu 24.04 cloud-init template instead, which enumerates
hot-attached disks, carries the usual filesystem tools and grows its root
filesystem on first boot by itself.

The cloud image disables SSH password authentication outright
(60-cloudimg-settings.conf), so guest access moves to an SSH keypair and the
stock "ubuntu" user. That user lands unprivileged, so commands touching /root
or a raw block device now go through a _sudo() helper which wraps the whole
command in `sh -c` under sudo, keeping redirects and ';'-separated commands
root-privileged rather than just the first word.

Cleanup ordering changes with it: a template cannot be deleted while a VM
still uses it, so it is appended to _cleanup after the account that owns the
VM, since cleanup_resources() deletes in list order.

The in-place multi-disk restore regression test that accompanied this change
upstream is left out: it asserts the uuid-based volume mapping in
LibvirtRestoreBackupCommandWrapper, which this branch does not carry.

* test: validate a whole backup chain, including across a mid-chain delete

The existing chain tests each check one property of one backup: the full/incremental
cadence, a restore from the tip, a delete that repairs or defers. None of them walks
the chain as a whole, and none asserts on backup size.

Add a test that builds FULL + 3 INCREMENTALs with a marker file per backup, restores
from every backup and creates a VM from every backup, then deletes the 2nd incremental
and repeats both sweeps over what survives.

The mid-chain delete is what earns the runtime on RBD. An `rbd export-diff` stream
carries no pointer to the diff before it, so a restore replays the whole sequence from
the full anchor, and a diff whose descendant still needs it cannot be dropped when it
is deleted, only hidden. Restoring the tip across that gap is what breaks if the
provider ever sends a chain with a hole in it, and nothing else covered it.

Sizes are asserted throughout: an incremental must be a small fraction of the full.
That is what distinguishes a real export-diff delta from the whole image being
re-exported every cycle, and no other test in this file looks at size at all, so a
provider that silently fell back to full-every-time still passed.

Each restore also asserts that markers written after that backup are gone. Checking
only that the expected markers are present would pass even if the restore had quietly
done nothing.

VMs built from backups are expunged as the test goes rather than through _cleanup:
seven of them are created, and holding them all to the end risks exhausting the
environment's capacity partway through a run.

* test: verify the guest of a VM created from a backup, not just that it boots

The chain test checked an Instance created from a backup only for reaching
Running. That proves the image boots; it says nothing about whether the diff
chain was replayed into the new volume correctly, so a create-from-backup that
produced a stale or empty image would still have passed.

Check the guest the same way an in-place restore is checked: the markers taken
up to that backup must be present, and markers written after it must be absent.
The absent half matters as much as the present half -- without it, a VM that
somehow came up with the source Instance's current disk would pass.

Access uses the pattern already proven by test_incremental_after_vm_restart: the
backup carries the source Instance's authorized_keys, so the new VM accepts the
same keypair and the stock cloud-image "ubuntu" user.

* nasbackup: carry the backup method separately from the mode

The RBD path overloaded ChainDecision.mode with rbd-full and rbd-incremental,
the same way the content-based path upstream overloaded it with content-full
and content-incremental. Split the two concerns as that path already did: mode
stays full or incremental, and a new method field says how the backup is taken
-- qcow2 (push mode with dirty bitmaps) or rbd (Ceph-native, anchored on an rbd
snapshot and exported with rbd export-diff).

TakeBackupCommand gets a method field and nasbackup.sh a --method option. Both
default to qcow2 when absent, so a management server that does not send a method
keeps working against an upgraded agent. legacy-full is unchanged: rewriting it
as full plus a "none" method would break incremental-disabled backups on agents
that have not been upgraded yet.

CHAIN_FORMAT stays as it is. The method says how a backup is taken and lives
only for the duration of the request; the chain format is persisted and says
what is on the repository, which is what restore and delete read later. The two
coincide for the rbd method today but answer different questions.

This mirrors c144d09 from #14194, which
introduced the method for the content path and named an RBD diff as the next
one to adopt it. Kept as close to that commit as the branch allows so the two
merge cleanly: this branch carries the RBD path but not the content one, so the
METHOD_CONTENT token is defined without a user here.

* utils: add RbdUtils for the Ceph monitors of an RBD pool

Everything that talks to Ceph needs the pool's monitors as a list the client
can parse, and the rules are the same wherever that list is built: give each
monitor the pool's port unless it names one already, and put a bare IPv6
address in square brackets so its own colons stay distinguishable from the
separator before the port.

The mon_host option of a disk's rbd: string wants the same list again, with
':' and ';' escaped, because those two separate the options of that string and
its monitors.

None of it depends on a storage pool, so collect it in RbdUtils as static
methods with their unit tests, rather than leaving each caller to grow a copy
that is right in a different set of cases.

* kvm: build the Ceph monitors of the restore backup command with RbdUtils

The monitors with a port, and the IPv6 monitors, are not valid arguments of
rbd -m when the brackets are removed and the port is added to each monitor.

* backup: name the rbd method in the TakeBackupCommand comment

The field listed qcow2 and content but not rbd, the method this branch adds,
so the one method a reader of this command is most likely to be chasing was
the one the comment left out.

* Add package dependencies

* Add ceph-common as dependencies

* kvm: refuse an RBD restore that would destroy a snapshot we did not take

A restore rewinds the volume wholesale: the image is removed and rebuilt from
its diff chain, so every snapshot it carried goes with it. The chain anchors
this path takes are its own to drop, but a CloudStack volume snapshot kept on
primary storage, or anything else taken outside this path, is content someone
asked to keep, and destroying it quietly is not a trade the operator was
offered.

Ask what the image carries before touching it. A snapshot that is not one of
ours refuses the restore, naming the ones in the way so they can be deleted or
the backup restored into a new volume. Anything else is purged as before,
except that an image which carries nothing is no longer handed a purge with
nothing to do; when the listing itself fails we cannot tell, so it is purged
as it always was.

The failure to remove the image goes back to saying only that. Explaining it
by a snapshot with clones made sense while a restore purged whatever it found,
but the snapshot those clones belong to is now refused earlier, so a removal
that still fails is failing for some other reason.

The test that replays a whole chain stubbed every piped rbd call with the
output of `rbd info`, whose "name" field would now read as a snapshot; tell
the two commands apart there, and cover the refusal.

* kvm: drop the cephx key file from a trap in nasbackup.sh

The key the script hands the rbd CLI lives in a temporary file for the length
of a call. cleanup() removes it, but only the failure paths call cleanup, so
an exit that does not reach it left the key behind. Leave its removal to the
shell as well, which covers every exit it still gets to run code on.

* utils: test the escaped colons of an IPv6 Ceph monitor without a port

composeOptionForMonHosts escapes every ':' of a monitor, because the colons
separate the options of the rbd: string. That includes the colons of an IPv6
address, also when the pool has no port to add. Test that case, and make
addPortToRbdMonitor, which is only used by RbdUtils itself, protected.

* kvm: remove the backup anchor once the chain it anchors is gone

An RBD chain is exported from a snapshot of every volume, the anchor, named
csbackup-<id>. Each backup drops the previous anchor once its delta has been
exported, so one anchor per volume is kept: the one the next incremental reads
from. Nothing removed the last one. When the last backup of a chain was deleted,
or the Instance was taken out of its backup offering, the anchor stayed on the
image for as long as the volume lived, and with it the data it references: the
next backup is a full one either way, so nothing ever read it again.

Remove the anchors of an Instance's volumes wherever the chain ends, next to
where the Instance's active checkpoint is already cleared. nasbackup.sh takes a
removeanchors operation, which sweeps every snapshot carrying the backup prefix
off the volumes it is given: only the snapshots this tool creates carry it, so a
user or volume snapshot is never touched.

The removal is best effort. The chain is gone either way, and a host that cannot
be reached must not fail the delete of a backup or the removal of an offering,
so a failure is logged rather than thrown. An Instance with no volume on an RBD
pool carries no anchor and is left alone.

* nas: decide a chain from its flavour rather than from an rbd flag

decideChain carried a boolean telling the RBD flavour apart from the QCOW2 one,
and every branch that differs between the two read it: the prefix of the anchor
it names, the on-NAS format it requires of the parent, the decision it returns,
and whether a stopped Instance can continue the chain at all. A third flavour
would have to be threaded through each of them separately.

Ask the flavour instead. anchorPrefixOf, flavorToFormat and
flavorSupportsIncrementalWhileStopped answer the three questions the branches
were asking, incrementalDecision builds the next link of a chain as fullDecision
already built the first one, and both take the flavour. The prefix of a QCOW2
anchor is named alongside the RBD one rather than written in place.

Behaviour is unchanged: a stopped Instance only reaches the full it took before
when its flavour cannot continue a chain while stopped, which is every flavour
but RBD, so the decision it returns is the same one.

Also rename applyBackupFormat to applyBackupFormatToRestoreCommand, which says
what it applies the format to.

* packaging: suggest ceph-common instead of requiring it

The agent only needs the rbd command line tools for RBD backups and
migrations; python3-rados and python3-rbd stay required.

* nas: address review of the RBD incremental backups

- restore: check every target volume (RBD storage, no foreign snapshots) before
  removing any image, so a later volume cannot fail after an earlier one was
  already rewound
- restore: replay each rbd import-diff with the restore timeout instead of the
  one hour default
- backup: pause a running multi-disk VM around the RBD snapshots when the
  filesystems were not frozen, so the set is crash consistent
- drop em-dashes from log and exception messages

* nas: run RBD backups on a host that has the rbd command

ceph-common is only suggested by the agent package, so not every KVM host has
the rbd command. The agent now reports whether it does (host.rbd.cli) and an
RBD backup runs on a host that has it: the Instance's own host, or for a
stopped Instance any other Up host of its cluster. When there is none, a plain
full backup is taken instead of failing on the missing command.

* nas: restore RBD backups on a host that has the rbd command

Restoring an RBD chain recreates the image and replays the diffs with the rbd
command, which a host may lack as ceph-common is only suggested. Restore on
the Instance's host when it has the command, otherwise on another host of its
cluster that has it. A volume restore that attaches to a running Instance has
to stay on that Instance's host. When no usable host has the command, fail
with a message that says so.

* import com.cloud.utils.exception.CloudRuntimeException

* nasbackup.sh: bring back the quiesce fixes of #14305 dropped by the merges

The merges of main into this branch lost most of #14305 in nasbackup.sh:
- --quiesce-timeout was no longer parsed, so a quiesced backup, for which the
  agent passes it by default, failed with an invalid option on every storage
- abort_backup_job() was gone, though the pull mode path of the Linstor backup
  still calls it, so a failed pull job kept the scratch devices busy
- the push mode path lost the freeze timeout, the thaw after every freeze
  attempt, the thaw retries, the abort of the job in cleanup() and the retry
  of the domjobinfo query

The script is main's again, plus what the rbd method adds. The rbd path now
freezes and thaws the guest with the same helpers, resuming a paused Instance
before it thaws.

* nas: tell the user why a restore of an Instance from a backup failed

When the host refuses or fails the restore, the NAS provider returned only false and the backup manager answered with the generic error, so the reason the host gave, such as an RBD image carrying snapshots the backup path did not take, never reached the user. Throw a BackupProviderException with the details of the answer, which the backup manager hands to the user as it is.

* nas: check for volume snapshots on RBD before restoring an Instance from a backup

Restoring an RBD volume from a backup rewinds the image wholesale, which removes every snapshot it carries, so the host refuses it when the image carries a snapshot the backup path did not take. Check the volume snapshots kept on primary storage in the management server first, and refuse before anything is sent to the host with the names of the volume and of its snapshots. The host still checks the image, which also catches snapshots CloudStack does not know about.

* nas: remove a duplicate import of DataStoreRole in the test

NASBackupProviderTest imported com.cloud.storage.DataStoreRole twice, which the checkstyle check of the build refuses.

* test: release the public IP of each Instance the NAS backup tests create

Marvin gives every Instance created by VirtualMachine.create or
Backup.createVMFromBackup its own public IP, with a port forwarding rule
for SSH, and destroying the Instance does not release that IP. The class
only got them back when its account was removed, so the tests which create
Instances from backups ran out of the 13 free addresses of the public range
and failed with "Insufficient address capacity", after which Marvin silently
left ssh_ip unset.

Add release_publicIP() to marvin.lib.common, which releases a public IP
unless it is the source NAT address of the network, and call it for the
Instances of each test in tearDown, for the target Instance of
test_restore_volume_and_attach_to_vm, and for each Instance which
test_full_chain_restore_and_create_vm_survive_mid_chain_delete destroys as
it goes. The Instance shared by the class keeps its IP until the class ends.

* kvm: build every Ceph monitor list with RbdUtils

The agent assembled the monitor list in several places, each with its own idea
of the rules. Opening a RADOS connection, or writing a ceph.conf for one,
appended the pool's port to the host string as a whole, so with several
monitors only the last was given it and a monitor that already named its port
was handed a second. The rbd: option string of a disk escaped the colons of an
IPv6 address only when it was bracketed already, which left a bare one reading
as though it carried options of its own.

Use the shared helpers for all of them. Two inputs therefore come out
differently, both previously wrong: a monitor that names its port keeps just
that one, and a bare IPv6 address is bracketed before anything is appended to
it or escaped in it.

The iscsiadm portals in IscsiAdmStorageAdaptor read the same way but are not
monitor lists, so they keep their own formatting.

* nas: address the second review of the RBD incremental backups

- restore: fail closed when the snapshots of an RBD image can not be listed, so a restore
  never removes snapshots it could not see; a missing image (exit code 2) has none.
- removing the offering sends the anchor cleanup to a host which has the rbd command, and
  sends none when no host has it.
- build the Ceph monitor list of an RBD disk string with RbdUtils, so a bare IPv6 monitor
  is bracketed, carries its port and survives nasbackup.sh's parser.
- RBD backup: bound the freeze, pause and snapshot steps with timeouts and keep a state file
  in /run/csbackup while the guest is held. The guest is released by a TERM/HUP/INT trap of
  the script, by the take-backup wrapper when the script failed or was killed, and by the
  agent for every state file left when it starts (RbdBackupGuestReleaser), which covers
  SIGKILL, a crash and a restart of the agent.
- nasbackup.sh holds a per-VM flock during the RBD backup, so two backups of a VM can not
  freeze the guest and share the state file at once. A refused backup exits with 21 and the
  wrapper then leaves the guest to the backup which holds the lock.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Development

Successfully merging this pull request may close these issues.

6 participants