Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -225,12 +225,15 @@ protected Host getVMHypervisorHost(VirtualMachine vm) {

if (hostId != null) {
Host host = hostDao.findById(hostId);
if (host.getStatus() == Status.Up) {
return host;
if (host != null) {
if (host.getStatus() == Status.Up) {
return host;
}
// Try to find any Up host in the same cluster
clusterId = host.getClusterId();
}
// Try to find any Up host in the same cluster
clusterId = host.getClusterId();
} else {
}
if (clusterId == null) {
// Try to find any Up host in the same cluster as the root volume
clusterId = getClusterIdFromRootVolume(vm);
}
Expand Down Expand Up @@ -851,7 +854,7 @@ protected void removeBackupAnchors(VirtualMachine vm) {
LOG.warn("Failed to remove the backup anchors of VM id={}: {}", vmId,
answer != null ? answer.getDetails() : "no answer received");
}
} catch (AgentUnavailableException | OperationTimedoutException | CloudRuntimeException e) {
} catch (AgentUnavailableException | OperationTimedoutException | RuntimeException e) {
LOG.warn("Unable to remove the backup anchors of VM id={}: {}", vmId, e.getMessage());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,36 @@ public void testGetVMHypervisorHostFallbackToZoneWideKVMHost() {
Mockito.verify(resourceManager).findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, zoneId);
}

@Test
public void testGetVMHypervisorHostWhenLastHostWasRemoved() {
Long hostId = 1L;
Long vmId = 1L;
Long clusterId = 2L;
Long poolId = 3L;

VMInstanceVO vm = mock(VMInstanceVO.class);
Mockito.when(vm.getLastHostId()).thenReturn(hostId);
Mockito.when(vm.getId()).thenReturn(vmId);
Mockito.when(hostDao.findById(hostId)).thenReturn(null);

VolumeVO rootVolume = mock(VolumeVO.class);
Mockito.when(rootVolume.getPoolId()).thenReturn(poolId);
Mockito.when(volumeDao.getInstanceRootVolume(vmId)).thenReturn(rootVolume);
StoragePoolVO storagePool = mock(StoragePoolVO.class);
Mockito.when(storagePool.getClusterId()).thenReturn(clusterId);
Mockito.when(storagePoolDao.findById(poolId)).thenReturn(storagePool);

HostVO upHostInCluster = mock(HostVO.class);
Mockito.when(upHostInCluster.getId()).thenReturn(4L);
Mockito.when(upHostInCluster.getStatus()).thenReturn(Status.Up);
Mockito.when(hostDao.findHypervisorHostInCluster(clusterId)).thenReturn(List.of(upHostInCluster));

Host result = nasBackupProvider.getVMHypervisorHost(vm);

Assert.assertNotNull(result);
Assert.assertEquals(4L, result.getId());
}

private VolumeVO volume(String uuid, String path, long deviceId) {
VolumeVO volume = mock(VolumeVO.class);
Mockito.lenient().when(volume.getUuid()).thenReturn(uuid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
package com.cloud.hypervisor.kvm.resource.wrapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

Expand Down Expand Up @@ -51,7 +50,10 @@ public Answer execute(RemoveBackupAnchorsCommand command, LibvirtComputingResour

// Only an RBD volume carries an anchor, so the volumes of every other pool type are left out
// rather than passed to a script which would have nothing to ask about them.
// diskPaths are RBDStringBuilder strings, which carry the cephx key: they go to the script and
// never into a log, whose volumePaths counterpart names the same volumes without the secret
List<String> diskPaths = new ArrayList<>();
List<String> rbdVolumePaths = new ArrayList<>();
if (Objects.nonNull(volumePaths)) {
for (int idx = 0; idx < volumePaths.size(); idx++) {
PrimaryDataStoreTO volumePool = volumePools.get(idx);
Expand All @@ -60,6 +62,7 @@ public Answer execute(RemoveBackupAnchorsCommand command, LibvirtComputingResour
}
KVMStoragePool volumeStoragePool = storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid());
diskPaths.add(KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool, volumePaths.get(idx)));
rbdVolumePaths.add(volumePaths.get(idx));
}
}

Expand All @@ -77,10 +80,10 @@ public Answer execute(RemoveBackupAnchorsCommand command, LibvirtComputingResour
Pair<Integer, String> result = Script.executePipedCommands(commands, libvirtComputingResource.getCmdsTimeout());

logger.debug("Removing the backup anchors of {} returned: {}, exit code: {}",
() -> Arrays.toString(diskPaths.toArray()), result::second, result::first);
() -> rbdVolumePaths, result::second, result::first);

if (result.first() != 0) {
logger.warn("Failed to remove the backup anchors of {}: {}", Arrays.toString(diskPaths.toArray()), result.second());
logger.warn("Failed to remove the backup anchors of {}: {}", rbdVolumePaths, result.second());
return new BackupAnswer(command, false, result.second());
}
return new BackupAnswer(command, true, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,19 @@ private boolean restoreRbdImageFromDiffChain(KVMStoragePoolManager storagePoolMg
}
}

// import-diff resizes the image to the size recorded in each diff, which is the size the
// volume had when that backup was taken. The volume may have been grown since, and the
// database keeps the size it has now, so bring the image back to the size it was
// recreated with.
Long restoredSize = rbdImageSize(connection, image);
if (!imageSize.equals(restoredSize)) {
logger.debug("Resizing RBD image {} from {} to {} bytes after applying the backup diff(s)", image, restoredSize, imageSize);
if (Script.executeCommandForExitValue(rbdCommand(connection, "resize", image, "--size", imageSize + "B", "--allow-shrink")) != 0) {
logger.error("Failed to resize RBD image {} to {} bytes after applying the backup diff(s)", image, imageSize);
return false;
}
}

// The snapshots import-diff recreated only existed to chain the diffs together; the
// restored volume should look like any other, so drop them.
if (Script.executeCommandForExitValue(rbdCommand(connection, "snap", "purge", image)) != 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,119 @@ public void testExecuteRestoresRbdVolumeByReplayingTheWholeDiffChain() throws Ex
Arrays.asList(60000L, 60000L), importTimeouts);
}

/**
* {@code rbd import-diff} resizes the image to the size recorded in the diff, the size the volume
* had when it was backed up. A volume grown since then keeps its new size in the database, so the
* image has to be brought back to the size it was recreated with.
*/
@Test
public void testExecuteResizesRbdImageBackToItsSizeAfterReplayingTheDiffChain() throws Exception {
when(command.getVmName()).thenReturn("test-vm");
lenient().when(command.getBackupPath()).thenReturn("test-vm/inc1");
when(command.getBackupFormat()).thenReturn("rbddiff");
when(command.getBackupChainPaths()).thenReturn(Arrays.asList("test-vm/full", "test-vm/inc1"));
when(command.getBackupRepoAddress()).thenReturn("192.168.1.100:/backup");
when(command.getBackupRepoType()).thenReturn("nfs");
when(command.getMountOptions()).thenReturn("rw");
when(command.isVmExists()).thenReturn(true);
when(command.getWait()).thenReturn(60);
when(command.getMountTimeout()).thenReturn(30);
PrimaryDataStoreTO primaryDataStore = Mockito.mock(PrimaryDataStoreTO.class);
when(primaryDataStore.getPoolType()).thenReturn(Storage.StoragePoolType.RBD);
when(primaryDataStore.getUuid()).thenReturn("ceph-pool-uuid");
when(command.getRestoreVolumePools()).thenReturn(Arrays.asList(primaryDataStore));
when(command.getRestoreVolumePaths()).thenReturn(Arrays.asList("cephpool/vol-uuid"));
when(command.getBackupVolumesUUIDs()).thenReturn(Arrays.asList("vol-uuid"));
when(command.getBackupFiles()).thenReturn(Arrays.asList("vol-uuid"));

KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
KVMStoragePool pool = Mockito.mock(KVMStoragePool.class);
when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(storagePoolMgr.getStoragePool(any(), anyString())).thenReturn(pool);
lenient().when(pool.getSourceHost()).thenReturn("10.0.1.2");
lenient().when(pool.getSourcePort()).thenReturn(6789);

List<String[]> executed = new ArrayList<>();
boolean[] imported = {false};

try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
Path tempPath = Mockito.mock(Path.class);
when(tempPath.toString()).thenReturn("/tmp/csbackup.abc123");
filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath);
filesMock.when(() -> Files.deleteIfExists(any(Path.class))).thenReturn(true);

try (MockedStatic<Script> scriptMock = mockStatic(Script.class)) {
scriptMock.when(() -> Script.getExecutableAbsolutePath(anyString()))
.thenAnswer(invocation -> invocation.getArgument(0));
scriptMock.when(() -> Script.executeCommand(any(String[].class))).thenReturn(null);
scriptMock.when(() -> Script.runSimpleBashScriptForExitValue(anyString())).thenReturn(0);
scriptMock.when(() -> Script.executeCommandForExitValue(any(String[].class)))
.thenAnswer(invocation -> {
Object[] raw = invocation.getArguments();
if (raw.length == 1 && raw[0] instanceof String[]) {
executed.add((String[]) raw[0]);
} else {
String[] parts = new String[raw.length];
for (int i = 0; i < raw.length; i++) {
parts[i] = String.valueOf(raw[i]);
}
executed.add(parts);
}
return 0;
});
scriptMock.when(() -> Script.executeCommandForExitValue(anyLong(), any(String[].class)))
.thenAnswer(invocation -> {
Object[] raw = invocation.getArguments();
String[] parts = new String[raw.length - 1];
if (raw.length == 2 && raw[1] instanceof String[]) {
parts = (String[]) raw[1];
} else {
for (int i = 1; i < raw.length; i++) {
parts[i - 1] = String.valueOf(raw[i]);
}
}
executed.add(parts);
if (Arrays.asList(parts).contains("import-diff")) {
imported[0] = true;
}
return 0;
});
// The image is 2 GiB when the restore starts (it was grown after the backup was
// taken); once a diff has been replayed it has the 1 GiB the diff recorded.
scriptMock.when(() -> Script.executePipedCommands(anyList(), anyLong()))
.thenAnswer(invocation -> {
List<String[]> commands = invocation.getArgument(0);
List<String> args = Arrays.asList(commands.get(0));
if (args.contains("snap") && args.contains("ls")) {
return new Pair<>(0, "[]");
}
return new Pair<>(0, imported[0] ? "{\"name\":\"vol-uuid\",\"size\":1073741824}"
: "{\"name\":\"vol-uuid\",\"size\":2147483648}");
});

Answer result = wrapper.execute(command, libvirtComputingResource);
Assert.assertTrue(((BackupAnswer) result).getResult());
}
}

boolean replayed = false;
boolean resized = false;
for (String[] cmd : executed) {
List<String> args = Arrays.asList(cmd);
if (args.contains("import-diff")) {
replayed = true;
} else if (args.contains("resize")) {
Assert.assertTrue("the image must be resized only once the chain has been replayed", replayed);
Assert.assertTrue("the image must go back to the size it was recreated with, in bytes",
args.contains("2147483648B"));
Assert.assertTrue("the image may have to shrink back if the diff recorded a larger size",
args.contains("--allow-shrink"));
resized = true;
}
}
Assert.assertTrue("the image must be resized back after the chain is replayed", resized);
}

private static final String SNAPSHOT_LISTING_FAILS = "rbd snap ls fails";
private static final String IMAGE_DOES_NOT_EXIST = "rbd snap ls finds no image";

Expand Down
59 changes: 38 additions & 21 deletions scripts/vm/hypervisor/kvm/nasbackup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ get_linstor_uuid_from_device() {
RBD_IMAGE="" # "<pool>/<image>"
RBD_ARGS=() # connection arguments to pass to every rbd invocation
RBD_KEYFILE="" # temporary cephx keyfile, removed by rbd_cleanup_keyfile
RBD_NEW_ANCHOR_DISKS=() # the disks this run tried to create the new anchor on, for on_rbd_backup_exit
# Prefix NASBackupProvider names every chain anchor with. Snapshots carrying it belong to this
# tool and no other, which is what makes the stale-anchor sweep safe.
RBD_SNAPSHOT_PREFIX="csbackup-"
Expand Down Expand Up @@ -287,6 +288,23 @@ for s in snaps or []:
rbd_cleanup_keyfile
}

# EXIT trap of the RBD backup, armed once the NAS is mounted and cleared once the backup is
# complete. Any exit in between -- an explicit failure, an unexpected error under "set -e", or
# TERM/HUP/INT, as when the agent restarts or kills the script on a timeout -- has to let go of the
# guest, drop the anchor this run created and remove the partial backup before unmounting the NAS,
# or the Instance stays frozen or paused and the NAS stays mounted with half a backup on it.
# SIGKILL cannot be trapped: the agent then releases the guest from the state file, see
# RBD_GUEST_STATE_FILE.
on_rbd_backup_exit() {
local rc=$?
trap - EXIT INT TERM HUP
[[ $rc -ne 0 ]] || rc=1
rbd_release_guest
rbd_remove_snapshots "$BITMAP_NEW" "${RBD_NEW_ANCHOR_DISKS[@]}"
cleanup
exit $rc
}

rbd_snapshot_exists() {
local snapName="$1"
rbd "${RBD_ARGS[@]}" snap ls "$RBD_IMAGE" --format json 2>>"$logFile" | python3 -c '
Expand Down Expand Up @@ -379,6 +397,10 @@ backup_rbd_vm() {
fi

mount_operation
trap on_rbd_backup_exit EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
mkdir -p "$dest" || { echo "Failed to create backup directory $dest"; exit 1; }

# Freezing the guest filesystems makes the snapshot set filesystem-consistent instead of merely
Expand All @@ -391,7 +413,6 @@ backup_rbd_vm() {
local resume=0
local vm_state
vm_state=$(virsh -c qemu:///system domstate "$VM" 2>/dev/null || true)
trap 'rbd_release_guest; rbd_cleanup_keyfile; exit 143' TERM HUP INT
if [[ ${QUIESCE} == "true" && "$vm_state" == "running" ]]; then
# Always thaw after a freeze attempt: a freeze that times out on the host can still
# complete inside the guest, and nothing else would unfreeze it.
Expand All @@ -410,51 +431,48 @@ backup_rbd_vm() {
# disk needs no pause: one snapshot is already a single point in time.
if [[ $freeze_ok -eq 0 && "$vm_state" == "running" && ${#disks[@]} -gt 1 ]]; then
echo "suspended" >> "$guest_state"
if timeout "$RBD_GUEST_TIMEOUT" virsh -c qemu:///system suspend "$VM" > /dev/null 2>&1; then
resume=1
else
# A suspend which timed out can still complete in libvirt after the client was killed, as a
# freeze can in the guest, so a resume is attempted whenever a suspend was.
resume=1
if ! timeout "$RBD_GUEST_TIMEOUT" virsh -c qemu:///system suspend "$VM" > /dev/null 2>&1; then
log -ne "WARNING: unable to pause VM $VM, the disk snapshots will not be taken at the same instant"
fi
fi

# Create this cycle's anchor on every disk back to back, so the set is as close to a single
# point in time for the VM as a whole as Ceph allows.
local -a snapped=()
# A disk is listed before its snapshot is attempted: one which timed out can still be created
# by Ceph afterwards, and the exit trap removes the anchor from every disk listed.
local snap_failed=0
for d in "${disks[@]}"; do
parse_rbd_opts "$d"
if timeout "$RBD_SNAPSHOT_TIMEOUT" rbd "${RBD_ARGS[@]}" snap create "$RBD_IMAGE@$BITMAP_NEW" >> "$logFile" 2>&1; then
snapped+=("$d")
else
RBD_NEW_ANCHOR_DISKS+=("$d")
if ! timeout "$RBD_SNAPSHOT_TIMEOUT" rbd "${RBD_ARGS[@]}" snap create "$RBD_IMAGE@$BITMAP_NEW" >> "$logFile" 2>&1; then
log -e "Failed to create RBD snapshot $RBD_IMAGE@$BITMAP_NEW"
snap_failed=1
break
fi
done
rbd_cleanup_keyfile

# Resume before thawing: the guest agent does not answer while the VM is paused.
# Resume before thawing: the guest agent does not answer while the VM is paused. The resume
# fails on a VM which is not paused, as when the suspend never took effect: only a VM which is
# still paused afterwards is an error.
if [[ $resume -eq 1 ]]; then
if ! timeout "$RBD_GUEST_TIMEOUT" virsh -c qemu:///system resume "$VM" > /dev/null 2>&1; then
if ! timeout "$RBD_GUEST_TIMEOUT" virsh -c qemu:///system resume "$VM" > /dev/null 2>&1 \
&& [[ "$(timeout 20 virsh -c qemu:///system domstate "$VM" 2>/dev/null || true)" == "paused" ]]; then
echo "Failed to resume vm $VM after taking the disk snapshots"
rbd_remove_snapshots "$BITMAP_NEW" "${snapped[@]}"
cleanup
exit 1
fi
fi

if [[ $thaw -eq 1 ]] && ! thaw_guest "$freeze_ok"; then
rbd_remove_snapshots "$BITMAP_NEW" "${snapped[@]}"
cleanup
exit 1
fi
rm -f "$guest_state"
trap - TERM HUP INT

if [[ $snap_failed -eq 1 ]]; then
echo "Failed to create RBD snapshot $BITMAP_NEW for vm $VM"
rbd_remove_snapshots "$BITMAP_NEW" "${snapped[@]}"
cleanup
exit 1
fi

Expand All @@ -469,15 +487,11 @@ backup_rbd_vm() {
if [[ "$effective_mode" == "incremental" ]]; then
if ! rbd "${RBD_ARGS[@]}" export-diff --from-snap "$BITMAP_PARENT" "$RBD_IMAGE@$BITMAP_NEW" "$output" >> "$logFile" 2>&1; then
echo "rbd export-diff --from-snap $BITMAP_PARENT failed for $RBD_IMAGE"
rbd_remove_snapshots "$BITMAP_NEW" "${snapped[@]}"
cleanup
exit 1
fi
else
if ! rbd "${RBD_ARGS[@]}" export-diff "$RBD_IMAGE@$BITMAP_NEW" "$output" >> "$logFile" 2>&1; then
echo "rbd export-diff failed for $RBD_IMAGE"
rbd_remove_snapshots "$BITMAP_NEW" "${snapped[@]}"
cleanup
exit 1
fi
fi
Expand Down Expand Up @@ -505,6 +519,9 @@ backup_rbd_vm() {
rbd_sweep_stale_anchors "$BITMAP_NEW" "${disks[@]}"
fi

# The backup is complete: the trap must not undo it, what is left is to unmount.
trap - EXIT INT TERM HUP

local backup_size
backup_size=$(du -sb "$dest" 2>>"$logFile" | cut -f1) || { log -ne "WARNING: du failed for $dest, reporting size as 0"; backup_size=0; }
timeout "$UNMOUNT_TIMEOUT" umount "$mount_point" 2>>"$logFile" || { log "WARNING: umount of $mount_point failed or timed out"; true; }
Expand Down
Loading