Skip to content

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

Open
abh1sar wants to merge 1 commit into
apache:4.22from
shapeblue:restore-single-volume
Open

Fix restore-and-attach of a backed up volume on NFS, Linstor and Ceph primary storages#14007
abh1sar wants to merge 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).

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.

Comment on lines +402 to +405
String currentDevice = result.second() == null ? "" : result.second().trim();
if (result.first() == null || result.first() != 0 || StringUtils.isBlank(currentDevice)) {
throw new CloudRuntimeException(String.format("Failed to determine the device to attach the restored volume to on VM [%s].", vmName));
}
Comment on lines +613 to +625
try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
scriptMock.when(() -> Script.getExecutableAbsolutePath(anyString()))
.thenAnswer(invocation -> invocation.getArgument(0));
scriptMock.when(() -> Script.executePipedCommands(anyList(), anyLong()))
.thenReturn(new Pair<>(0, "vda" + System.lineSeparator()));
scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
.thenAnswer(invocation -> {
// Mockito expands varargs, so the command comes back as individual arguments.
captured[0] = Arrays.stream(invocation.getArguments()).map(String::valueOf).toArray(String[]::new);
return 0;
});
method.invoke(wrapper, storagePoolMgr, "test-vm", volumePool, "/path/to/volume");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants