abh1sar commented on code in PR #14386:
URL: https://github.com/apache/cloudstack/pull/14386#discussion_r4699073725
##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java:
##########
@@ -392,6 +504,217 @@ private boolean
replaceBlockDeviceWithBackup(KVMStoragePoolManager storagePoolMg
return true;
}
+ /**
+ * Rebuild an RBD image by replaying a chain of {@code rbd export-diff}
streams into it: the
+ * chain's full anchor first, then each incremental in the order it was
taken.
+ *
+ * <p>RBD images are raw and cannot hold a backing-file reference, so —
unlike the qcow2 path —
+ * a diff carries no pointer to the one before it and the chain cannot be
flattened by
+ * {@code qemu-img}. Ceph applies the deltas natively instead: each diff
ends at the snapshot
+ * the backup was taken from, {@code import-diff} recreates that snapshot
on the target, and the
+ * next diff in the chain is validated against it. A truncated or
out-of-order diff is therefore
+ * rejected by Ceph rather than silently producing a half-restored
image.</p>
+ *
+ * <p>The image is recreated first. A full diff only carries the extents
that were allocated
+ * when it was taken, so any block still allocated in the current image
would otherwise show
+ * through the restore as stale data. Recreating the image also drops
every RBD snapshot it
+ * carried: a restore rewinds the volume wholesale, and snapshots of
content that is being
+ * replaced cannot be kept. The chain anchors this path takes are ours to
drop, but a snapshot
+ * taken outside it — a CloudStack volume snapshot kept on primary
storage, say — is not, so an
+ * image carrying one is refused rather than rewound.</p>
+ */
+ private boolean restoreRbdImageFromDiffChain(KVMStoragePoolManager
storagePoolMgr, PrimaryDataStoreTO volumePool,
+ String volumePath,
List<String> diffFiles, Long size, int timeout) {
+ if (!Storage.StoragePoolType.RBD.equals(volumePool.getPoolType())) {
+ logger.error("Backup [{}] holds RBD diffs but volume [{}] is on {}
storage; it cannot be restored there.",
+ diffFiles.get(0), volumePath, volumePool.getPoolType());
+ return false;
+ }
+ KVMStoragePool pool =
storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid());
+ Path keyFile = null;
+ try {
+ keyFile = writeCephKeyFile(pool.getAuthSecret());
+ List<String> connection = rbdConnectionArgs(pool, keyFile);
+ // Volume paths of RBD volumes are already "<ceph pool>/<image>".
+ String image = volumePath;
+
+ // Prefer the current image's own size: it is what the VM's disk
was sized to. Only a
+ // restore that creates a brand new volume has no image to read it
from.
+ Long imageSize = rbdImageSize(connection, image);
+ if (imageSize == null) {
+ imageSize = size;
+ }
+ if (imageSize == null || imageSize <= 0) {
+ logger.error("Unable to determine the size to recreate RBD
image {} with", image);
+ return false;
+ }
+
+ if (!recreateRbdImage(connection, image, imageSize,
rbdDataPool(pool))) {
+ return false;
+ }
+
+ for (String diff : diffFiles) {
+ logger.debug("Applying backup diff {} to RBD image {}", diff,
image);
+ if (Script.executeCommandForExitValue(timeout,
rbdCommand(connection, "import-diff", diff, image)) != 0) {
+ logger.error("Failed to apply backup diff {} to RBD image
{}", diff, image);
+ return false;
+ }
+ }
+
Review Comment:
`rbd import-diff` resizes the image to the size recorded in each diff
(`do_image_resize` in Ceph's `Import.cc`), so an in-place restore after the
volume was grown, or `createVMFromBackup` onto a larger disk, would leave the
image at its backup-time size while the DB keeps the new size; I think it needs
an `rbd resize` back to `imageSize` after this loop.
##########
plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java:
##########
@@ -648,6 +807,60 @@ private void clearVmActiveCheckpoint(long vmId) {
}
}
+ /**
+ * Remove the backup anchors of {@code vmId}'s volumes on the host: the
RBD snapshots the chain
+ * was exported from. Called wherever the chain itself is gone, so that
the next backup is a full
+ * one and the anchor would only keep the data it references allocated in
the pool. Best effort:
+ * the chain is already gone either way, so a host which cannot be reached
is logged, not thrown.
+ */
+ protected void removeBackupAnchors(long vmId) {
+ VirtualMachine vm = vmInstanceDao.findByIdIncludingRemoved(vmId);
+ if (vm != null) {
+ removeBackupAnchors(vm);
+ }
+ }
+
+ protected void removeBackupAnchors(VirtualMachine vm) {
+ long vmId = vm.getId();
+ List<VolumeVO> volumes = volumeDao.findByInstance(vmId);
+ if (CollectionUtils.isEmpty(volumes)) {
+ return;
+ }
+ // Only an RBD volume carries an anchor, so an Instance without one is
left alone rather
+ // than sent a command that would find nothing to remove.
+ if (volumes.stream().noneMatch(this::isOnRbdPool)) {
+ return;
+ }
+ volumes.sort(Comparator.comparing(Volume::getDeviceId));
+ try {
+ Host host = getVMHypervisorHost(vm);
Review Comment:
`getVMHypervisorHost()` dereferences `hostDao.findById(vm.getLastHostId())`
without a null check and `findById` returns null for a removed host, so for an
Instance with an RBD volume this throws an NPE that the catch below does not
cover and `removeVMFromBackupOffering` now fails, which it could not before
since it did not look up a host.
##########
scripts/vm/hypervisor/kvm/nasbackup.sh:
##########
@@ -144,6 +149,369 @@ get_linstor_uuid_from_device() {
return 1
}
+# Globals populated by parse_rbd_opts() for the disk it was last called with.
+RBD_IMAGE="" # "<pool>/<image>"
+RBD_ARGS=() # connection arguments to pass to every rbd invocation
+RBD_KEYFILE="" # temporary cephx keyfile, removed by rbd_cleanup_keyfile
+# 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-"
+# The guest is frozen or paused while the snapshots are taken, so none of the
steps in between may
+# wait for ever. A TERM/HUP/INT trap releases the guest, and the agent does it
for a script it had to
+# kill with SIGKILL or lost in a restart, see RBD_GUEST_STATE_FILE.
+RBD_GUEST_TIMEOUT=60
+RBD_SNAPSHOT_TIMEOUT=120
+# Written while the script holds the guest ("frozen" and/or "suspended"),
removed once it let go.
+# LibvirtTakeBackupCommandWrapper reads it to release a guest of a script it
had to kill: an EXIT
+# trap does not run on SIGKILL.
+RBD_STATE_DIR="/run/csbackup"
+RBD_GUEST_STATE_FILE="$RBD_STATE_DIR/%s.guest"
+# Held for the whole RBD backup of a VM, so two backups of it (a scheduled one
started by a management
+# server which just restarted, while the old one still runs here) cannot
freeze the guest and share
+# the state file at the same time. The kernel drops the lock with the script,
even on SIGKILL.
+RBD_BACKUP_LOCK_FILE="$RBD_STATE_DIR/%s.lock"
+
+# Let go of a guest this script holds, as its state file says. Run by the
TERM/HUP/INT trap, so a
+# restart of the agent, which signals the script, does not leave the guest
frozen or paused. SIGKILL
+# cannot be trapped; the agent then releases the guest from the state file
when it starts.
+rbd_release_guest() {
+ local state_file
+ state_file=$(printf "$RBD_GUEST_STATE_FILE" "$VM")
+ [[ -f "$state_file" ]] || return 0
+ local state
+ state=$(cat "$state_file" 2>/dev/null)
+ local ok=1
+ if [[ "$state" == *suspended* && "$(virsh -c qemu:///system domstate "$VM"
2>/dev/null)" == "paused" ]]; then
+ timeout 20 virsh -c qemu:///system resume "$VM" > /dev/null 2>&1 || ok=0
+ fi
+ if [[ "$state" == *frozen* ]]; then
+ timeout 20 virsh -c qemu:///system qemu-agent-command "$VM"
'{"execute":"guest-fsfreeze-thaw"}' > /dev/null 2>&1 || true
+ fi
+ [[ $ok -eq 1 ]] && rm -f "$state_file"
+ return 0
+}
+
+rbd_cleanup_keyfile() {
+ if [[ -n "$RBD_KEYFILE" ]]; then
+ rm -f "$RBD_KEYFILE"
+ RBD_KEYFILE=""
+ fi
+}
+
+# Split an RBD disk string produced by KVMPhysicalDisk.RBDStringBuilder into
the image name and
+# the connection arguments the rbd CLI needs:
+#
rbd:<pool>/<image>:mon_host=<h1>\;<h2>:auth_client_required=cephx:id=<user>:key=<secret>:...
+# ':' and ';' are backslash-escaped inside mon_host so that option splitting
stays unambiguous;
+# they are masked before the split and restored afterwards.
+parse_rbd_opts() {
+ local s="${1#rbd:}"
+ s="${s//\\:/$'\x01'}"
+ s="${s//\\;/$'\x02'}"
+ local -a parts=()
+ IFS=':' read -ra parts <<< "$s"
+
+ rbd_cleanup_keyfile
+ RBD_IMAGE="${parts[0]}"
+ RBD_ARGS=()
+
+ local p monHost="" authId="" authKey=""
+ for p in "${parts[@]:1}"; do
+ case "$p" in
+ mon_host=*) monHost="${p#mon_host=}" ;;
+ id=*) authId="${p#id=}" ;;
+ key=*) authKey="${p#key=}" ;;
+ esac
+ done
+ monHost="${monHost//$'\x01'/:}" # host\:port -> host:port
+ monHost="${monHost//$'\x02'/,}" # monitor list -> the comma-separated form
rbd -m accepts
+
+ if [[ -n "$monHost" ]]; then
+ RBD_ARGS+=(-m "$monHost")
+ fi
+ if [[ -n "$authId" ]]; then
+ RBD_ARGS+=(--id "$authId")
+ if [[ -n "$authKey" ]]; then
+ RBD_KEYFILE=$(mktemp -t csbackup-ceph.XXXXXX)
+ chmod 600 "$RBD_KEYFILE"
+ printf '%s' "$authKey" > "$RBD_KEYFILE"
+ RBD_ARGS+=(--keyfile "$RBD_KEYFILE")
+ fi
+ fi
+}
+
+# Best-effort removal of snapshot $1 from each of the remaining disk
arguments. Used both to roll
+# back a half-created anchor and to drop the previous anchor once its delta
has been exported.
+rbd_remove_snapshots() {
+ local snapName="$1"
+ shift
+ local d
+ for d in "$@"; do
+ [[ -z "$d" ]] && continue
+ parse_rbd_opts "$d"
+ if ! rbd "${RBD_ARGS[@]}" snap rm "$RBD_IMAGE@$snapName" >> "$logFile"
2>&1; then
+ log -e "cleanup: failed to remove RBD snapshot $RBD_IMAGE@$snapName
(non-fatal)"
+ fi
+ done
+ rbd_cleanup_keyfile
+}
+
+# Remove every snapshot carrying the backup prefix except $1, across the
remaining disk arguments.
+# Only snapshots this tool created are ever touched: user and CloudStack
volume snapshots do not
+# use the prefix.
+rbd_sweep_stale_anchors() {
+ local keepSnap="$1"
+ shift
+ local d stale
+ for d in "$@"; do
+ [[ -z "$d" ]] && continue
+ parse_rbd_opts "$d"
+ while read -r stale; do
+ [[ -z "$stale" || "$stale" == "$keepSnap" ]] && continue
+ if ! rbd "${RBD_ARGS[@]}" snap rm "$RBD_IMAGE@$stale" >> "$logFile"
2>&1; then
+ log -e "cleanup: failed to remove stale RBD snapshot $RBD_IMAGE@$stale
(non-fatal)"
+ fi
+ done < <(
+ rbd "${RBD_ARGS[@]}" snap ls "$RBD_IMAGE" --format json 2>>"$logFile" |
python3 -c '
+import sys, json
+try:
+ snaps = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+for s in snaps or []:
+ name = (s or {}).get("name") or ""
+ if name.startswith(sys.argv[1]):
+ print(name)
+' "$RBD_SNAPSHOT_PREFIX" 2>/dev/null || true
+ )
+ done
+ rbd_cleanup_keyfile
+}
+
+rbd_snapshot_exists() {
+ local snapName="$1"
+ rbd "${RBD_ARGS[@]}" snap ls "$RBD_IMAGE" --format json 2>>"$logFile" |
python3 -c '
+import sys, json
+try:
+ snaps = json.load(sys.stdin)
+except Exception:
+ sys.exit(1)
+sys.exit(0 if any((s or {}).get("name") == sys.argv[1] for s in snaps or [])
else 1)
+' "$snapName"
+}
+
+# Incremental backup of Ceph/RBD volumes.
+#
+# RBD images are raw, so they have nowhere to persist a QEMU dirty bitmap and
cannot take part in
+# the libvirt-checkpoint scheme backup_running_vm uses. Ceph provides the
equivalent natively: an
+# `rbd snap` per cycle as the anchor, and `rbd export-diff --from-snap` to
stream out exactly the
+# extents that changed between two anchors (computed inside Ceph from the
image object-map).
+#
+# Because the snapshot lives in Ceph rather than in the QEMU process, this
works identically for
+# running and stopped VMs, and survives a live migration of the VM between
hosts.
+#
+# Only the newest anchor is kept on each image: once this run's delta is
exported, the parent
+# snapshot is removed. A full additionally sweeps every other snapshot
carrying the backup prefix,
+# so anchors abandoned by a deleted chain, an unassigned offering or a restore
cannot accumulate.
+backup_rbd_vm() {
+ if [[ -z "$DISK_PATHS" ]]; then
+ echo "RBD backup mode requires the volume paths (-d|--diskpaths)"
+ exit 1
+ fi
+ if [[ -z "$BITMAP_NEW" ]]; then
+ echo "RBD backup mode requires --bitmap-new (the snapshot to create)"
+ exit 1
+ fi
+
+ if ! command -v rbd > /dev/null 2>&1; then
+ echo "RBD backup mode requires the rbd command (ceph-common) on this host"
+ exit 1
+ fi
+
+ mkdir -p "$RBD_STATE_DIR" || { echo "Failed to create $RBD_STATE_DIR"; exit
1; }
+ if command -v flock > /dev/null 2>&1; then
+ local lock_file
+ lock_file=$(printf "$RBD_BACKUP_LOCK_FILE" "$VM")
+ if ! { exec {RBD_LOCK_FD}>"$lock_file"; } 2>/dev/null; then
+ log -ne "WARNING: unable to open $lock_file, taking the backup of vm $VM
without a lock"
+ elif ! flock -n "$RBD_LOCK_FD"; then
+ echo "Another backup of vm $VM is already running on this host"
+ exit $EXIT_BACKUP_IN_PROGRESS
+ fi
+ else
+ log -ne "WARNING: flock is not installed, taking the backup of vm $VM
without a lock"
+ fi
+
+ local effective_mode="$MODE"
+ case "$effective_mode" in
+ full|incremental)
+ ;;
+ *)
+ echo "Mode $effective_mode is not supported by the rbd method"
+ cleanup
+ exit 1
+ ;;
+ esac
+ local -a disks=()
+ IFS=',' read -ra disks <<< "$DISK_PATHS"
+
+ local d
+ for d in "${disks[@]}"; do
+ if [[ "$d" != rbd:* ]]; then
+ echo "RBD backup mode was requested but disk $d is not an RBD volume"
+ exit 1
+ fi
+ done
+
+ # The parent anchor must still be present on EVERY disk. A volume migration
or an out-of-band
+ # snapshot purge can drop it; fall back to a full rather than letting
export-diff fail. Checked
+ # before anything is mounted or created so the fallback costs nothing.
+ if [[ "$effective_mode" == "incremental" ]]; then
+ for d in "${disks[@]}"; do
+ parse_rbd_opts "$d"
+ if ! rbd_snapshot_exists "$BITMAP_PARENT"; then
+ log -e "rbd incremental: parent snapshot $BITMAP_PARENT missing on
$RBD_IMAGE - falling back to full"
+ echo "INCREMENTAL_FALLBACK=true"
+ effective_mode="full"
+ break
+ fi
+ done
+ rbd_cleanup_keyfile
+ fi
+
+ mount_operation
+ 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
+ # crash-consistent. Only possible while the VM runs and its guest agent
answers.
+ local guest_state
+ guest_state=$(printf "$RBD_GUEST_STATE_FILE" "$VM")
+ rm -f "$guest_state"
+ local thaw=0
+ local freeze_ok=0
+ 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.
+ echo "frozen" >> "$guest_state"
+ thaw=1
+ if freeze_err=$(qemu_agent_command '{"execute":"guest-fsfreeze-freeze"}'
2>&1 > /dev/null); then
+ freeze_ok=1
+ else
+ log -e "Failed to freeze the filesystem for vm $VM, continuing without
quiescing: $freeze_err"
+ fi
+ fi
+
+ # Without a freeze the snapshots of a VM with several disks are taken one
after another while
+ # the guest keeps writing, so the set would not be crash consistent. Pausing
the VM for the few
+ # moments the snapshots take restores that, much as a backup-begin
checkpoint does. A single
+ # 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
+ 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=()
+ 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
+ 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.
+ if [[ $resume -eq 1 ]]; then
+ if ! timeout "$RBD_GUEST_TIMEOUT" virsh -c qemu:///system resume "$VM" >
/dev/null 2>&1; 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
Review Comment:
Once this trap is cleared, the RBD path only has the key-file EXIT trap, so
a script killed mid-export (agent restart, or `destroyForcibly()` from
`Script.executePipedCommands` on timeout) leaves the NAS mounted plus the
partial backup dir and the new anchor snapshot behind; pull mode covers this
with `on_pull_backup_exit` and `abortPullBackupJob`, could the RBD path get the
same?
##########
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRemoveBackupAnchorsCommandWrapper.java:
##########
@@ -0,0 +1,88 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.cloudstack.backup.BackupAnswer;
+import org.apache.cloudstack.backup.RemoveBackupAnchorsCommand;
+import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
+import org.apache.commons.collections.CollectionUtils;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+import com.cloud.storage.Storage;
+import com.cloud.utils.Pair;
+import com.cloud.utils.script.Script;
+
+@ResourceWrapper(handles = RemoveBackupAnchorsCommand.class)
+public class LibvirtRemoveBackupAnchorsCommandWrapper extends
CommandWrapper<RemoveBackupAnchorsCommand, Answer, LibvirtComputingResource> {
+
+ @Override
+ public Answer execute(RemoveBackupAnchorsCommand command,
LibvirtComputingResource libvirtComputingResource) {
+ final List<PrimaryDataStoreTO> volumePools = command.getVolumePools();
+ final List<String> volumePaths = command.getVolumePaths();
+ final KVMStoragePoolManager storagePoolMgr =
libvirtComputingResource.getStoragePoolMgr();
+
+ // 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.
+ List<String> diskPaths = new ArrayList<>();
+ if (Objects.nonNull(volumePaths)) {
+ for (int idx = 0; idx < volumePaths.size(); idx++) {
+ PrimaryDataStoreTO volumePool = volumePools.get(idx);
+ if (volumePool == null || volumePool.getPoolType() !=
Storage.StoragePoolType.RBD) {
+ continue;
+ }
+ KVMStoragePool volumeStoragePool =
storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid());
+
diskPaths.add(KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool,
volumePaths.get(idx)));
+ }
+ }
+
+ if (CollectionUtils.isEmpty(diskPaths)) {
+ return new BackupAnswer(command, true, null);
+ }
+
+ List<String[]> commands = new ArrayList<>();
+ commands.add(new String[]{
+ libvirtComputingResource.getNasBackupPath(),
+ "-o", "removeanchors",
+ "-d", String.join(",", diskPaths)
+ });
+
+ 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);
+
+ if (result.first() != 0) {
+ logger.warn("Failed to remove the backup anchors of {}: {}",
Arrays.toString(diskPaths.toArray()), result.second());
Review Comment:
`diskPaths` holds the `KVMPhysicalDisk.RBDStringBuilder()` strings, which
include `:key=<cephx secret>`, so this debug line and the warn below write the
Ceph key to agent.log; could they log `volumePaths` instead?
##########
scripts/vm/hypervisor/kvm/nasbackup.sh:
##########
@@ -144,6 +149,369 @@ get_linstor_uuid_from_device() {
return 1
}
+# Globals populated by parse_rbd_opts() for the disk it was last called with.
+RBD_IMAGE="" # "<pool>/<image>"
+RBD_ARGS=() # connection arguments to pass to every rbd invocation
+RBD_KEYFILE="" # temporary cephx keyfile, removed by rbd_cleanup_keyfile
+# 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-"
+# The guest is frozen or paused while the snapshots are taken, so none of the
steps in between may
+# wait for ever. A TERM/HUP/INT trap releases the guest, and the agent does it
for a script it had to
+# kill with SIGKILL or lost in a restart, see RBD_GUEST_STATE_FILE.
+RBD_GUEST_TIMEOUT=60
+RBD_SNAPSHOT_TIMEOUT=120
+# Written while the script holds the guest ("frozen" and/or "suspended"),
removed once it let go.
+# LibvirtTakeBackupCommandWrapper reads it to release a guest of a script it
had to kill: an EXIT
+# trap does not run on SIGKILL.
+RBD_STATE_DIR="/run/csbackup"
+RBD_GUEST_STATE_FILE="$RBD_STATE_DIR/%s.guest"
+# Held for the whole RBD backup of a VM, so two backups of it (a scheduled one
started by a management
+# server which just restarted, while the old one still runs here) cannot
freeze the guest and share
+# the state file at the same time. The kernel drops the lock with the script,
even on SIGKILL.
+RBD_BACKUP_LOCK_FILE="$RBD_STATE_DIR/%s.lock"
+
+# Let go of a guest this script holds, as its state file says. Run by the
TERM/HUP/INT trap, so a
+# restart of the agent, which signals the script, does not leave the guest
frozen or paused. SIGKILL
+# cannot be trapped; the agent then releases the guest from the state file
when it starts.
+rbd_release_guest() {
+ local state_file
+ state_file=$(printf "$RBD_GUEST_STATE_FILE" "$VM")
+ [[ -f "$state_file" ]] || return 0
+ local state
+ state=$(cat "$state_file" 2>/dev/null)
+ local ok=1
+ if [[ "$state" == *suspended* && "$(virsh -c qemu:///system domstate "$VM"
2>/dev/null)" == "paused" ]]; then
+ timeout 20 virsh -c qemu:///system resume "$VM" > /dev/null 2>&1 || ok=0
+ fi
+ if [[ "$state" == *frozen* ]]; then
+ timeout 20 virsh -c qemu:///system qemu-agent-command "$VM"
'{"execute":"guest-fsfreeze-thaw"}' > /dev/null 2>&1 || true
+ fi
+ [[ $ok -eq 1 ]] && rm -f "$state_file"
+ return 0
+}
+
+rbd_cleanup_keyfile() {
+ if [[ -n "$RBD_KEYFILE" ]]; then
+ rm -f "$RBD_KEYFILE"
+ RBD_KEYFILE=""
+ fi
+}
+
+# Split an RBD disk string produced by KVMPhysicalDisk.RBDStringBuilder into
the image name and
+# the connection arguments the rbd CLI needs:
+#
rbd:<pool>/<image>:mon_host=<h1>\;<h2>:auth_client_required=cephx:id=<user>:key=<secret>:...
+# ':' and ';' are backslash-escaped inside mon_host so that option splitting
stays unambiguous;
+# they are masked before the split and restored afterwards.
+parse_rbd_opts() {
+ local s="${1#rbd:}"
+ s="${s//\\:/$'\x01'}"
+ s="${s//\\;/$'\x02'}"
+ local -a parts=()
+ IFS=':' read -ra parts <<< "$s"
+
+ rbd_cleanup_keyfile
+ RBD_IMAGE="${parts[0]}"
+ RBD_ARGS=()
+
+ local p monHost="" authId="" authKey=""
+ for p in "${parts[@]:1}"; do
+ case "$p" in
+ mon_host=*) monHost="${p#mon_host=}" ;;
+ id=*) authId="${p#id=}" ;;
+ key=*) authKey="${p#key=}" ;;
+ esac
+ done
+ monHost="${monHost//$'\x01'/:}" # host\:port -> host:port
+ monHost="${monHost//$'\x02'/,}" # monitor list -> the comma-separated form
rbd -m accepts
+
+ if [[ -n "$monHost" ]]; then
+ RBD_ARGS+=(-m "$monHost")
+ fi
+ if [[ -n "$authId" ]]; then
+ RBD_ARGS+=(--id "$authId")
+ if [[ -n "$authKey" ]]; then
+ RBD_KEYFILE=$(mktemp -t csbackup-ceph.XXXXXX)
+ chmod 600 "$RBD_KEYFILE"
+ printf '%s' "$authKey" > "$RBD_KEYFILE"
+ RBD_ARGS+=(--keyfile "$RBD_KEYFILE")
+ fi
+ fi
+}
+
+# Best-effort removal of snapshot $1 from each of the remaining disk
arguments. Used both to roll
+# back a half-created anchor and to drop the previous anchor once its delta
has been exported.
+rbd_remove_snapshots() {
+ local snapName="$1"
+ shift
+ local d
+ for d in "$@"; do
+ [[ -z "$d" ]] && continue
+ parse_rbd_opts "$d"
+ if ! rbd "${RBD_ARGS[@]}" snap rm "$RBD_IMAGE@$snapName" >> "$logFile"
2>&1; then
+ log -e "cleanup: failed to remove RBD snapshot $RBD_IMAGE@$snapName
(non-fatal)"
+ fi
+ done
+ rbd_cleanup_keyfile
+}
+
+# Remove every snapshot carrying the backup prefix except $1, across the
remaining disk arguments.
+# Only snapshots this tool created are ever touched: user and CloudStack
volume snapshots do not
+# use the prefix.
+rbd_sweep_stale_anchors() {
+ local keepSnap="$1"
+ shift
+ local d stale
+ for d in "$@"; do
+ [[ -z "$d" ]] && continue
+ parse_rbd_opts "$d"
+ while read -r stale; do
+ [[ -z "$stale" || "$stale" == "$keepSnap" ]] && continue
+ if ! rbd "${RBD_ARGS[@]}" snap rm "$RBD_IMAGE@$stale" >> "$logFile"
2>&1; then
+ log -e "cleanup: failed to remove stale RBD snapshot $RBD_IMAGE@$stale
(non-fatal)"
+ fi
+ done < <(
+ rbd "${RBD_ARGS[@]}" snap ls "$RBD_IMAGE" --format json 2>>"$logFile" |
python3 -c '
+import sys, json
+try:
+ snaps = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+for s in snaps or []:
+ name = (s or {}).get("name") or ""
+ if name.startswith(sys.argv[1]):
+ print(name)
+' "$RBD_SNAPSHOT_PREFIX" 2>/dev/null || true
+ )
+ done
+ rbd_cleanup_keyfile
+}
+
+rbd_snapshot_exists() {
+ local snapName="$1"
+ rbd "${RBD_ARGS[@]}" snap ls "$RBD_IMAGE" --format json 2>>"$logFile" |
python3 -c '
+import sys, json
+try:
+ snaps = json.load(sys.stdin)
+except Exception:
+ sys.exit(1)
+sys.exit(0 if any((s or {}).get("name") == sys.argv[1] for s in snaps or [])
else 1)
+' "$snapName"
+}
+
+# Incremental backup of Ceph/RBD volumes.
+#
+# RBD images are raw, so they have nowhere to persist a QEMU dirty bitmap and
cannot take part in
+# the libvirt-checkpoint scheme backup_running_vm uses. Ceph provides the
equivalent natively: an
+# `rbd snap` per cycle as the anchor, and `rbd export-diff --from-snap` to
stream out exactly the
+# extents that changed between two anchors (computed inside Ceph from the
image object-map).
+#
+# Because the snapshot lives in Ceph rather than in the QEMU process, this
works identically for
+# running and stopped VMs, and survives a live migration of the VM between
hosts.
+#
+# Only the newest anchor is kept on each image: once this run's delta is
exported, the parent
+# snapshot is removed. A full additionally sweeps every other snapshot
carrying the backup prefix,
+# so anchors abandoned by a deleted chain, an unassigned offering or a restore
cannot accumulate.
+backup_rbd_vm() {
+ if [[ -z "$DISK_PATHS" ]]; then
+ echo "RBD backup mode requires the volume paths (-d|--diskpaths)"
+ exit 1
+ fi
+ if [[ -z "$BITMAP_NEW" ]]; then
+ echo "RBD backup mode requires --bitmap-new (the snapshot to create)"
+ exit 1
+ fi
+
+ if ! command -v rbd > /dev/null 2>&1; then
+ echo "RBD backup mode requires the rbd command (ceph-common) on this host"
+ exit 1
+ fi
+
+ mkdir -p "$RBD_STATE_DIR" || { echo "Failed to create $RBD_STATE_DIR"; exit
1; }
+ if command -v flock > /dev/null 2>&1; then
+ local lock_file
+ lock_file=$(printf "$RBD_BACKUP_LOCK_FILE" "$VM")
+ if ! { exec {RBD_LOCK_FD}>"$lock_file"; } 2>/dev/null; then
+ log -ne "WARNING: unable to open $lock_file, taking the backup of vm $VM
without a lock"
+ elif ! flock -n "$RBD_LOCK_FD"; then
+ echo "Another backup of vm $VM is already running on this host"
+ exit $EXIT_BACKUP_IN_PROGRESS
+ fi
+ else
+ log -ne "WARNING: flock is not installed, taking the backup of vm $VM
without a lock"
+ fi
+
+ local effective_mode="$MODE"
+ case "$effective_mode" in
+ full|incremental)
+ ;;
+ *)
+ echo "Mode $effective_mode is not supported by the rbd method"
+ cleanup
+ exit 1
+ ;;
+ esac
+ local -a disks=()
+ IFS=',' read -ra disks <<< "$DISK_PATHS"
+
+ local d
+ for d in "${disks[@]}"; do
+ if [[ "$d" != rbd:* ]]; then
+ echo "RBD backup mode was requested but disk $d is not an RBD volume"
+ exit 1
+ fi
+ done
+
+ # The parent anchor must still be present on EVERY disk. A volume migration
or an out-of-band
+ # snapshot purge can drop it; fall back to a full rather than letting
export-diff fail. Checked
+ # before anything is mounted or created so the fallback costs nothing.
+ if [[ "$effective_mode" == "incremental" ]]; then
+ for d in "${disks[@]}"; do
+ parse_rbd_opts "$d"
+ if ! rbd_snapshot_exists "$BITMAP_PARENT"; then
+ log -e "rbd incremental: parent snapshot $BITMAP_PARENT missing on
$RBD_IMAGE - falling back to full"
+ echo "INCREMENTAL_FALLBACK=true"
+ effective_mode="full"
+ break
+ fi
+ done
+ rbd_cleanup_keyfile
+ fi
+
+ mount_operation
+ 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
+ # crash-consistent. Only possible while the VM runs and its guest agent
answers.
+ local guest_state
+ guest_state=$(printf "$RBD_GUEST_STATE_FILE" "$VM")
+ rm -f "$guest_state"
+ local thaw=0
+ local freeze_ok=0
+ 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.
+ echo "frozen" >> "$guest_state"
+ thaw=1
+ if freeze_err=$(qemu_agent_command '{"execute":"guest-fsfreeze-freeze"}'
2>&1 > /dev/null); then
+ freeze_ok=1
+ else
+ log -e "Failed to freeze the filesystem for vm $VM, continuing without
quiescing: $freeze_err"
+ fi
+ fi
+
+ # Without a freeze the snapshots of a VM with several disks are taken one
after another while
+ # the guest keeps writing, so the set would not be crash consistent. Pausing
the VM for the few
+ # moments the snapshots take restores that, much as a backup-begin
checkpoint does. A single
+ # 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
+ log -ne "WARNING: unable to pause VM $VM, the disk snapshots will not be
taken at the same instant"
+ fi
+ fi
Review Comment:
If `virsh suspend` hits the timeout, `resume` stays 0, but libvirt can still
complete the suspend after the client is killed (same reasoning as the freeze
comment above), and the state file is removed further down on the success path,
so the Instance could stay paused with nothing left to resume it; should we
always attempt a resume once a suspend was attempted?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]