From: Ciro Iriarte <cyruspy@gmail.com>
To: pve-devel@lists.proxmox.com
Subject: [RFC PATCH storage v2 2/6] rbd: implement copy-offload via snapshot + clone + flatten
Date: Thu, 26 Nov 2026 13:56:59 -0300 [thread overview]
Message-ID: <20261126.2.copyoffload-v2@cyruspy.gmail.com> (raw)
In-Reply-To: <20261126.0.copyoffload-v2@cyruspy.gmail.com>
From: Ciro Iriarte <ciro.iriarte+software@gmail.com>
Ceph can make a full copy without moving data through the host: snapshot
the source, clone the snapshot, flatten the clone. The flatten is the
data copy and runs on the cluster.
prepare create a minimal placeholder image to reserve the name
start snapshot (unless the caller gave one) and clone; both are
metadata operations, cheap enough for a guest freeze, and
they capture the point in time, hence copy-offload-atomic
status pending while the clone has a parent, complete once
flattened
The flatten is handed to the manager with 'ceph rbd task add flatten',
with the storage's connection options, so it runs cluster-side, outlives
the worker and can be cancelled. Status distinguishes complete (no
parent), pending (a task exists) and failed (still a clone, no task). A
fast flatten can leave the task list between the two reads, so if no
task is found, status re-reads the parent before reporting a failure,
and a task list that cannot be read at all, as during a manager
failover, counts as pending.
copy_image_check() refuses, and the host copies the clone instead, when
the target is on another Ceph cluster, when the two storages use
different Ceph users (the clone is made with the source's user, which
then writes to the target pool), or when the target's Ceph user is not
allowed to add manager tasks. Equal monhost values mean the same
cluster, and an unset one means the local cluster; different values are
compared by the clusters' fsid. Manager write access is probed by
cancelling a task that does not exist, which returns ENOENT if allowed
and EACCES if not. Any other probe failure dies, so the core falls back
with a warning. prepare runs only the checks that need no cluster
access, as it holds the storage lock.
Each command run by start has a 30 second timeout, so a hung cluster
fails the start within a bounded time instead of holding the guest
frozen indefinitely; the timeout is per command, and there are about
five per disk. On failure, start removes only the staging clone and its
own snapshot, with the same timeout. If the snapshot cannot be removed,
the next prepare that copies the same source to the same target name
cleans it up; prepare fails if it cannot, rather than leaving start to
fail on it inside the freeze.
start builds the clone under a staging name and renames the placeholder
out of the way instead of deleting it, so the disk name stays taken
throughout; otherwise a concurrent allocation could take it and this
copy's rollback would free the other volume. The parked placeholder is
removed by status once the copy is complete, or by free_image() if the
copy is rolled back; never by start, since 'rbd rm' walks every object
and start can run inside a guest freeze. Both transient names use
prefixes: list_images() matches on an anchored pattern, so they never
show up as a VM's disk, while find_free_diskname() matches the disk
number unanchored, so they still reserve it. copy_offload_naming_test.pm
covers both.
A caller-supplied snapshot is cloned with clone format 2, which does not
require the snapshot to be protected. Once the copy is independent,
status removes the snapshot this plugin took on the source; free_image()
does the same for a copy that failed, and cancels its flatten if it is
still running. free_image() only looks for these on a storage with
copy-offload enabled, so an ordinary free makes no extra calls.
copy_images_start() is not overridden. Ceph group snapshots do capture a
single instant, but an image can belong to only one group, so grouping
would change the source images' group membership.
Tested on Ceph Tentacle 20.2.1 with an erasure-coded pool: the copy had
no parent, matched the source and still read correctly after the source
was deleted. Running VMs were full-cloned with a mix of offloaded and
drive-mirrored disks; the clones were byte-identical and independent,
and no snapshot was left on the sources.
Signed-off-by: Ciro Iriarte <ciro.iriarte+software@gmail.com>
---
Changes in v2:
* rebased onto current master
* folded in the flatten status fix sent as a follow-up to v1 on
2026-07-22, with copy_offload_rbd_status_test.pm
* copy_image_check(): raw VM disks, one Ceph cluster (same monitors,
or else same fsid), the same Ceph user on both storages, and a user
allowed to add manager tasks; a failed probe dies, so the core falls
back with a warning. prepare repeats only the static checks,
as it holds the storage lock
* each command in start has a 30 second timeout; a failed start leaves
the parked placeholder to free_image(), and prepare removes a copy
snapshot left over from an earlier failed copy of the same source to
the same name, or fails if it cannot
* free_image() looks for copy leftovers only with copy-offload enabled
* the 'ceph rbd task' calls now use the storage's connection options,
so an external cluster works, and match the namespace
* free_image() cancels a running flatten, and status treats a
task list it cannot read as pending, not as a dead flatten
* values read back from 'rbd info' are untainted, as pvedaemon runs
with -T
src/PVE/Storage/RBDPlugin.pm | 551 ++++++++++++++++++++++-
src/test/copy_offload_naming_test.pm | 82 ++++
src/test/copy_offload_rbd_status_test.pm | 114 +++++
src/test/run_plugin_tests.pl | 2 +
4 files changed, 743 insertions(+), 6 deletions(-)
create mode 100644 src/test/copy_offload_naming_test.pm
create mode 100644 src/test/copy_offload_rbd_status_test.pm
diff --git a/src/PVE/Storage/RBDPlugin.pm b/src/PVE/Storage/RBDPlugin.pm
index ac0e0fa..061c75a 100644
--- a/src/PVE/Storage/RBDPlugin.pm
+++ b/src/PVE/Storage/RBDPlugin.pm
@@ -371,8 +371,9 @@ sub rbd_volume_du {
die "got no matching image from rbd du\n";
}
-my sub rbd_volume_exists {
- my ($scfg, $storeid, $volname) = @_;
+# Every image name in the pool, unfiltered (rbd_ls() skips names that are not disks).
+my sub rbd_image_names {
+ my ($scfg, $storeid, $timeout) = @_;
my $cmd = $rbd_cmd->($scfg, $storeid, 'ls', '--format', 'json');
my $raw = '';
@@ -381,6 +382,7 @@ my sub rbd_volume_exists {
errmsg => "rbd error",
errfunc => sub { },
outfunc => sub { $raw .= shift; },
+ (defined($timeout) ? (timeout => $timeout) : ()),
);
my $list;
@@ -391,11 +393,13 @@ my sub rbd_volume_exists {
die "got unexpected data from 'rbd ls': '$raw'\n";
}
- for my $name ($list->@*) {
- return 1 if $name eq $volname;
- }
+ return { map { $_ => 1 } $list->@* };
+}
+
+my sub rbd_volume_exists {
+ my ($scfg, $storeid, $volname) = @_;
- return 0;
+ return rbd_image_names($scfg, $storeid)->{$volname} ? 1 : 0;
}
# Needs to be public, so qemu-server can mock it for cfg2cmd.
@@ -448,6 +452,7 @@ sub plugindata {
],
'advanced-properties' => {
namespace => 1,
+ 'copy-offload-timeout' => 1,
},
'hidden-properties' => {
bwlimit => 1,
@@ -519,6 +524,8 @@ sub options {
krbd => { optional => 1 },
keyring => { optional => 1 },
bwlimit => { optional => 1 },
+ 'copy-offload' => { optional => 1 },
+ 'copy-offload-timeout' => { optional => 1 },
};
}
@@ -764,6 +771,486 @@ sub clone_image {
return $newvol;
}
+# ---- storage-offloaded full copy -------------------------------------------------
+#
+# Ceph can produce a full copy without moving the data through the host: snapshot the
+# source, clone the snapshot (copy-on-write, instant), then flatten the clone. The
+# flatten is what copies the data, and it runs on the Ceph cluster.
+#
+# That maps onto the hook's three phases as follows:
+#
+# prepare create a minimal placeholder image, reserving the target name.
+# start snapshot (unless the caller gave one) and clone it with clone format 2,
+# which needs no protected snapshot, then park the placeholder and rename
+# the clone into place. All metadata operations, so this is safe to run
+# inside a guest freeze, and it is what fixes the copy's point in time:
+# writes to the source afterwards cannot affect the clone.
+# status pending until the flatten has removed the clone's parent, that is, until
+# the target is independent and the source may be deleted.
+#
+# The last point is why 'complete' is defined as independent rather than readable: a
+# clone is fully readable the moment it exists, but deleting the source out from under
+# an unflattened clone would destroy it.
+
+my $rbd_copy_snap = sub {
+ my ($target_volname) = @_;
+ # Derived from the target name so status/cleanup can find it again without state.
+ return "__copy_$target_volname";
+};
+
+# 'ceph' with the storage's connection options, like $rbd_cmd, so an external cluster
+# (monhost/keyring set) is addressed instead of the local one.
+my sub ceph_cmd {
+ my ($scfg, $storeid, @args) = @_;
+
+ my $opt = PVE::CephConfig::ceph_connect_option($scfg, $storeid);
+ my $cmd = ['/usr/bin/ceph'];
+ push @$cmd, '-c', $opt->{ceph_conf} if $opt->{ceph_conf};
+ push @$cmd, '-m', $opt->{mon_host} if $opt->{mon_host};
+ push @$cmd, '--auth_client_required', $opt->{auth_client_required}
+ if $opt->{auth_client_required};
+ push @$cmd, '-n', "client.$opt->{userid}" if $opt->{userid};
+ push @$cmd, '--keyring', $opt->{keyring} if $opt->{keyring};
+ push @$cmd, @args;
+ return $cmd;
+}
+
+# The image's parent, from 'rbd info', or undef. Values are untainted: they come from
+# command output and are passed back to rbd, and pvedaemon runs with taint checks.
+my sub rbd_volume_parent {
+ my ($scfg, $storeid, $name) = @_;
+
+ my $cmd = $rbd_cmd->($scfg, $storeid, 'info', $name, '--format', 'json');
+ my $raw = '';
+ run_rbd_command($cmd, errmsg => "rbd info '$name' error", outfunc => sub { $raw .= shift });
+ my $parent = eval { decode_json($raw)->{parent} };
+ return undef if ref($parent) ne 'HASH';
+ for my $k (qw(pool pool_namespace image snapshot)) {
+ next if !defined($parent->{$k});
+ ($parent->{$k}) = $parent->{$k} =~ m/^([^\s\/\@]*)$/
+ or die "unexpected rbd parent $k '$parent->{$k}'\n";
+ }
+ return $parent;
+}
+
+# Bound for each backend command copy_image_start() runs, and for the probes in
+# copy_image_check(). The start runs inside a guest freeze, so a hanging cluster must
+# fail it rather than keep the guest frozen; every step is a metadata operation that
+# normally takes well under a second.
+my $COPY_CMD_TIMEOUT = 30;
+
+# Bound for the clean-up copy_image_prepare() does under the storage lock, whose
+# locked code is limited to 60 seconds: at most four such commands run there.
+my $COPY_LOCKED_CMD_TIMEOUT = 10;
+
+# Run a best-effort rbd command, bounded by $timeout (default $COPY_CMD_TIMEOUT).
+# Returns undef on success, '' if rbd reported the image or snapshot as missing, and
+# rbd's error otherwise, so a cleanup can tell "nothing to remove" from a real failure
+# without printing either.
+my sub rbd_try {
+ my ($cmd, $timeout) = @_;
+
+ my $stderr = '';
+ eval {
+ run_command(
+ $cmd,
+ outfunc => sub { },
+ errfunc => sub { $stderr .= "$_[0]\n" },
+ timeout => $timeout // $COPY_CMD_TIMEOUT,
+ );
+ };
+ my $err = $@ or return undef;
+ return '' if $stderr =~ /^rbd: .*\(2\) No such file or directory/m;
+ return $stderr || $err;
+}
+
+# The Ceph manager's rbd task queue, decoded. Dies if it cannot be read: a failed
+# look-up (a manager failover, or a key without manager access) is not the same as an
+# empty queue.
+my sub rbd_task_list {
+ my ($scfg, $storeid) = @_;
+
+ my $out = '';
+ eval {
+ run_command(ceph_cmd($scfg, $storeid, 'rbd', 'task', 'list', '--format', 'json'),
+ outfunc => sub { $out .= shift }, timeout => $COPY_CMD_TIMEOUT);
+ };
+ die "cannot list rbd tasks - $@" if $@;
+ return [] if $out !~ /\S/;
+
+ my $tasks = eval { decode_json($out) };
+ die "invalid JSON from 'ceph rbd task list' - $@" if $@ || ref($tasks) ne 'ARRAY';
+ return $tasks;
+}
+
+# The cluster's fsid, to tell whether two storages address the same Ceph cluster.
+my sub ceph_fsid {
+ my ($scfg, $storeid) = @_;
+
+ my $out = '';
+ run_command(ceph_cmd($scfg, $storeid, 'fsid'),
+ outfunc => sub { $out .= shift }, timeout => $COPY_CMD_TIMEOUT);
+ my ($fsid) = $out =~ m/^\s*([0-9a-f-]{36})\s*$/
+ or die "unexpected output from 'ceph fsid'\n";
+ return $fsid;
+}
+
+# The manager-side flatten task for an image, if one is queued or running. Dies if
+# the queue cannot be read, so the caller does not mistake a running flatten for a
+# dead one.
+my sub rbd_flatten_task {
+ my ($scfg, $storeid, $name) = @_;
+
+ my $tasks = rbd_task_list($scfg, $storeid);
+
+ my $pool = $scfg->{pool} || 'rbd';
+ my $ns = $scfg->{namespace} // '';
+ for my $task (@$tasks) {
+ my $refs = $task->{refs} // {};
+ next if ($refs->{action} // '') ne 'flatten';
+ next if ($refs->{image_name} // '') ne $name;
+ next if ($refs->{pool_name} // '') ne $pool;
+ next if ($refs->{pool_namespace} // '') ne $ns;
+ return $task;
+ }
+
+ return undef;
+}
+
+# Names for the two transient images a copy needs: the clone as it is being built, and
+# the placeholder once it has been moved out of the way.
+#
+# Both use a prefix. rbd_ls(), which feeds list_images(), selects on the anchored
+# m/^(?:vm|base)-(\d+)-/, so a prefixed name is invisible there and never appears as a
+# disk of that VM. find_free_diskname() meanwhile passes the raw 'rbd ls' output
+# to get_next_vm_diskname(), whose disk-number regex is unanchored, so a prefixed name
+# still reserves the disk number, which is what these need.
+my sub copy_staging_name { return "copynew-$_[0]" }
+my sub copy_parked_name { return "copytmp-$_[0]" }
+
+# Remove transient images a previous copy to this name left behind. They are invisible
+# to list_images(), so nothing else would ever reap them, and a leftover placeholder
+# would make the rename in copy_image_start() fail for every future copy to this name.
+my sub copy_reap_leftovers {
+ my ($scfg, $storeid, $volname, $timeout) = @_;
+ $timeout //= $COPY_CMD_TIMEOUT;
+
+ # Best effort, one 'rbd ls', each step bounded: it runs under the storage lock in
+ # copy_image_prepare() and on free_image(), which it must neither stall nor fail.
+ my $names = eval { rbd_image_names($scfg, $storeid, $timeout) };
+ if (my $err = $@) {
+ warn "could not check for stale copy images - $err";
+ return;
+ }
+ for my $stale (copy_staging_name($volname), copy_parked_name($volname)) {
+ next if !$names->{$stale};
+ warn "removing stale copy image '$stale'\n";
+ my $err = rbd_try($rbd_cmd->($scfg, $storeid, 'rm', $stale), $timeout);
+ warn "could not remove stale copy image '$stale' - $err" if defined($err);
+ }
+}
+
+# What can be told from the configuration alone. copy_image_prepare() repeats only this
+# part: it runs under the storage lock, where the cluster probes do not belong.
+my sub copy_check_static {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts) = @_;
+
+ my ($vtype) = $class->parse_volname($volname);
+ return "only VM disks can be offloaded, not '$vtype'"
+ if !PVE::Storage::Common::vtype_matches($vtype, 'vm-vol');
+ my $format = $opts->{format} // 'raw';
+ return "cannot produce format '$format'" if $format ne 'raw';
+
+ # The clone is made with the source storage's Ceph user, which then needs write
+ # access to the target pool. Only the same user is known to have it.
+ return "storages '$storeid' and '$target_storeid' use different Ceph users"
+ if ($scfg->{username} // 'admin') ne ($target_scfg->{username} // 'admin');
+
+ return undef;
+}
+
+# Whether the Ceph user may add manager tasks, without adding one: cancelling a task
+# that does not exist is a write command too, and answers ENOENT if allowed.
+my sub rbd_task_write_allowed {
+ my ($scfg, $storeid) = @_;
+
+ my $no_such_task = '00000000-0000-0000-0000-000000000000';
+ my $err = '';
+ eval {
+ run_command(
+ ceph_cmd($scfg, $storeid, 'rbd', 'task', 'cancel', $no_such_task),
+ outfunc => sub { },
+ errfunc => sub { $err .= "$_[0]\n" },
+ timeout => $COPY_CMD_TIMEOUT,
+ );
+ };
+ return 1 if $err =~ /ENOENT/;
+ return 0 if $err =~ /^Error E(?:ACCES|PERM)\b/m;
+ die "cannot query the Ceph manager - " . ($err || $@);
+}
+
+sub copy_image_check {
+ my ($class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $snap, $opts) = @_;
+
+ my $reason = copy_check_static(
+ $class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts,
+ );
+ return $reason if defined($reason);
+
+ # Equal 'monhost' values address the same monitors, and an unset one means the
+ # cluster this node runs. Different values may still name one cluster, which only
+ # its fsid tells. A probe that fails is a fault, not an answer, so it dies.
+ if (($scfg->{monhost} // '') ne ($target_scfg->{monhost} // '')) {
+ return "storage '$target_storeid' is on a different Ceph cluster"
+ if ceph_fsid($scfg, $storeid) ne ceph_fsid($target_scfg, $target_storeid);
+ }
+
+ # The flatten that does the copy runs as a Ceph manager task, which the storage's
+ # Ceph user must be allowed to add.
+ return "the Ceph user of '$target_storeid' may not add manager tasks"
+ if !rbd_task_write_allowed($target_scfg, $target_storeid);
+
+ return undef;
+}
+
+sub copy_image_prepare {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_vmid, $snap, $opts,
+ ) = @_;
+
+ my $reason = copy_check_static(
+ $class, $scfg, $storeid, $volname, $target_scfg, $target_storeid, $opts,
+ );
+ die "cannot offload copy of '$volname': $reason\n" if defined($reason);
+
+ my $name = $class->find_free_diskname($target_storeid, $target_scfg, $target_vmid);
+
+ # Safe here: we hold the target storage lock, and the name is ours because
+ # find_free_diskname() just handed it out.
+ copy_reap_leftovers($target_scfg, $target_storeid, $name, $COPY_LOCKED_CMD_TIMEOUT);
+
+ # A snapshot of the source named after this target is left over from an earlier
+ # copy to the same name that failed before it could remove it. The name was just
+ # handed out, so no live copy uses it, and copy_image_start() would fail on it.
+ if (!defined($snap)) {
+ my (undef, $src_name) = $class->parse_volname($volname);
+ my $stale = $rbd_copy_snap->($name);
+ my $err = rbd_try(
+ $rbd_cmd->($scfg, $storeid, 'snap', 'rm', $src_name, '--snap', $stale),
+ $COPY_LOCKED_CMD_TIMEOUT,
+ );
+ if (!defined($err)) {
+ warn "removed stale copy snapshot '$stale' of '$src_name'\n";
+ } elsif ($err ne '') {
+ # left in place, copy_image_start() would fail on it inside the guest freeze
+ die "cannot remove stale copy snapshot '$stale' of '$src_name' - $err";
+ }
+ }
+
+ # Create the target, do not just pick a name. The caller runs this under the
+ # target storage lock and releases it before copy_image_start(), so a name that was
+ # only chosen could be taken by a concurrent allocation in between, and the
+ # caller's rollback would then free a volume belonging to that other operation.
+ #
+ # The smallest image rbd accepts, not the source's size: it only holds the name
+ # until copy_image_start() parks it and renames the clone into place, and 'rbd rm'
+ # walks every object of an image. Up to the 4 MiB object size it is a single object.
+ my $cmd = $rbd_cmd->(
+ $target_scfg, $target_storeid, 'create', '--image-format', '2',
+ '--size', '4K', $name,
+ );
+ push $cmd->@*, ('--data-pool', $target_scfg->{'data-pool'})
+ if $target_scfg->{'data-pool'};
+ run_rbd_command($cmd, errmsg => "rbd create '$name' error");
+
+ return $name;
+}
+
+sub copy_image_start {
+ my (
+ $class, $scfg, $storeid, $volname,
+ $target_scfg, $target_storeid, $target_volname, $snap,
+ ) = @_;
+
+ my (undef, $name) = $class->parse_volname($volname);
+
+ my $run = sub {
+ my ($cmd, $errmsg) = @_;
+ run_rbd_command($cmd, errmsg => $errmsg, timeout => $COPY_CMD_TIMEOUT);
+ };
+
+ # Copy from the snapshot the caller asked for. Taking our own snapshot of the
+ # current image would copy live data when a snapshot was requested.
+ my $own_snap = defined($snap) ? undef : $rbd_copy_snap->($target_volname);
+ my $src_snap = $snap // $own_snap;
+
+ my $tmp = copy_staging_name($target_volname);
+ my $parked = copy_parked_name($target_volname);
+ my $cloned;
+
+ my $ok = eval {
+ # Inside the eval: a timed-out create may still have made the snapshot.
+ if ($own_snap) {
+ my $cmd = $rbd_cmd->($scfg, $storeid, 'snap', 'create', $name, '--snap', $own_snap);
+ $run->($cmd, "rbd snap create '$name' error");
+ }
+
+ # Clone format 2 so no snapshot protection is needed, which is required when copying
+ # from a caller-supplied snapshot we do not own and must not protect/unprotect.
+ my @options = (
+ '--rbd-default-clone-format', '2',
+ get_rbd_path($scfg, $name), '--snap', $src_snap,
+ );
+ push @options, ('--data-pool', $target_scfg->{'data-pool'})
+ if $target_scfg->{'data-pool'};
+
+ my $cmd = $rbd_cmd->(
+ $scfg, $storeid, 'clone', @options, get_rbd_path($target_scfg, $tmp),
+ );
+ $cloned = 1; # a timed-out clone may still have created it
+ $run->($cmd, "rbd clone '$name' error");
+
+ # Swap the clone into the reserved name. Move the placeholder aside rather than
+ # deleting it first: 'rbd rm' followed by 'rbd rename' leaves the disk number
+ # unreserved in between, and a concurrent allocation could take it, after
+ # which this copy's rollback would free somebody else's volume. Parked under a
+ # prefixed name it stays invisible to list_images() while still reserving the
+ # number. It is removed by copy_image_status() once the copy is complete, or by
+ # free_image() if the copy is rolled back; never here, as the caller may hold
+ # the guest frozen.
+ $cmd = $rbd_cmd->($target_scfg, $target_storeid, 'rename', $target_volname, $parked);
+ $run->($cmd, "rbd rename placeholder '$target_volname' error");
+ $cmd = $rbd_cmd->($target_scfg, $target_storeid, 'rename', $tmp, $target_volname);
+ if (!eval { $run->($cmd, "rbd rename '$tmp' error"); 1 }) {
+ my $rerr = $@;
+ # Put the reservation back so the caller's rollback frees what it was given.
+ my $c = $rbd_cmd->(
+ $target_scfg, $target_storeid, 'rename', $parked, $target_volname,
+ );
+ eval { $run->($c, "restoring placeholder error") };
+ warn $@ if $@;
+ die $rerr;
+ }
+ $cloned = 0; # the clone is the target now, which the caller frees
+
+ # Hand the flatten to the Ceph manager rather than running it here: it is the
+ # data copy, it must not block a caller that may be holding a guest
+ # freeze, and a cluster-side task survives this worker dying. It is also
+ # cancellable, which a detached child process would not have been.
+ $cmd = ceph_cmd($target_scfg, $target_storeid, 'rbd', 'task', 'add', 'flatten',
+ get_rbd_path($target_scfg, $target_volname));
+ run_command(
+ $cmd,
+ errmsg => "scheduling rbd flatten failed",
+ outfunc => sub { },
+ timeout => $COPY_CMD_TIMEOUT,
+ );
+ 1;
+ };
+ if (my $err = $@) {
+ # Leave the source as it was. Only what blocks removing our snapshot is removed
+ # here, each step bounded; a parked placeholder is reaped by free_image() when
+ # the caller frees the target, and a snapshot that cannot be removed now by the
+ # next copy_image_prepare() for this name.
+ if ($cloned) {
+ my $e = rbd_try($rbd_cmd->($target_scfg, $target_storeid, 'rm', $tmp));
+ warn "could not remove '$tmp' - $e" if $e;
+ }
+ if ($own_snap) {
+ my $e = rbd_try($rbd_cmd->($scfg, $storeid, 'snap', 'rm', $name, '--snap', $own_snap));
+ warn "could not remove snapshot '$own_snap' of '$name' - $e" if $e;
+ }
+ die $err;
+ }
+
+ return;
+}
+
+sub copy_image_status {
+ my ($class, $scfg, $storeid, $volname, $source) = @_;
+
+ my (undef, $name) = $class->parse_volname($volname);
+
+ # The image's parent link is the source of truth for completion: no parent means the
+ # flatten finished and the image is independent. A clone is readable from the
+ # moment it exists, but deleting the source before the flatten completes would
+ # destroy it.
+ my $read_parent = sub { rbd_volume_parent($scfg, $storeid, $name) };
+
+ my $parent = $read_parent->();
+
+ # Still a clone: the flatten is running, has just finished, or died. The manager task
+ # is only a liveness signal, not the completion signal. A fast flatten of a small
+ # image can vanish from 'rbd task list' between the info read above and this task
+ # lookup, so a missing task is ambiguous: re-read the parent before concluding the
+ # flatten died. Otherwise a copy that completed is misreported as a dead flatten,
+ # a race seen with concurrent multi-disk clones of small images.
+ if ($parent) {
+ # A failed task look-up proves nothing either way; poll again, and let the
+ # caller's timeout end a copy that never comes back.
+ my $task = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ if (my $err = $@) {
+ warn $err;
+ return { state => 'pending' };
+ }
+ if ($task) {
+ my $progress = $task->{progress};
+ return {
+ state => 'pending',
+ (defined($progress) ? (progress => $progress * 100) : ()),
+ };
+ }
+
+ # No task: re-read the parent. If the flatten just finished it is now gone.
+ $parent = $read_parent->();
+ if ($parent) {
+ # Parent persists with no task. One more task look-up guards a transient
+ # empty 'rbd task list' while the flatten is still running; only when that
+ # is also empty is the flatten dead.
+ my $again = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ if (my $err = $@) {
+ warn $err;
+ return { state => 'pending' };
+ }
+ die "flatten of '$volname' is no longer running and the image is still a clone\n"
+ if !$again;
+ return { state => 'pending' };
+ }
+ # Parent cleared: the flatten completed, fall through to the completion cleanup.
+ }
+
+ # independent. Drop the snapshot this copy was taken from, on the source image. Once
+ # the flatten completes the target no longer records where it came from, so this is
+ # the last chance to find it, and leaving it behind pins space on the source and
+ # blocks deleting that volume later.
+ #
+ # Only ever our own: the name is derived from the target, so a caller-supplied
+ # snapshot can never match and is left untouched.
+ if ($source) {
+ my $own_snap = $rbd_copy_snap->($volname);
+ my (undef, $src_name) = $class->parse_volname($source->{volname});
+ my $err = rbd_try($rbd_cmd->(
+ $source->{scfg}, $source->{storeid}, 'snap', 'rm', $src_name, '--snap', $own_snap,
+ ));
+ # a copy from a caller-supplied snapshot has none of ours: not worth a warning
+ warn "could not remove snapshot '$own_snap' of '$src_name' - $err" if $err;
+ }
+ # The placeholder copy_image_start() parked. Not removed there: 'rbd rm' walks
+ # every object and that call can run with a guest frozen. Best effort: the copy is
+ # already complete and correct, and dying here would make the caller free it.
+ my $parked = copy_parked_name($name);
+ eval {
+ if (rbd_volume_exists($scfg, $storeid, $parked)) {
+ my $c = $rbd_cmd->($scfg, $storeid, 'rm', $parked);
+ run_rbd_command($c, errmsg => "rbd rm placeholder '$parked' error");
+ }
+ };
+ warn $@ if $@;
+
+ return { state => 'complete' };
+}
+
sub alloc_image {
my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
@@ -790,6 +1277,41 @@ sub free_image {
my ($vtype, $name, $vmid, undef, undef, undef) = $class->parse_volname($volname);
+ # What an offloaded copy to this name can leave behind. Only looked for on a storage
+ # with copy-offload enabled, the only place such copies are made, so an ordinary
+ # free does not pay for the extra 'rbd' and 'ceph' calls.
+ my ($copy_parent, $task_id);
+ if ($scfg->{'copy-offload'}) {
+ # Transient images from a copy that died mid-flight. They are invisible to
+ # list_images(), so freeing the volume they belong to is the only occasion
+ # anything would look for them.
+ copy_reap_leftovers($scfg, $storeid, $name);
+
+ # An unfinished copy is still a clone of a snapshot this plugin took on the
+ # source image. Freeing the target would leave that snapshot behind, pinning
+ # space and blocking deletion of the source. The clone is the only record of
+ # where it came from, so read the parent now and drop the snapshot after the
+ # rm, but only when it is one of ours, never one the caller supplied.
+ my $parent = eval { rbd_volume_parent($scfg, $storeid, $name) };
+ $copy_parent = $parent if $parent && ($parent->{snapshot} // '') =~ /^__copy_/;
+
+ # Its flatten may still be running in the manager, holding the image; cancel it
+ # first, so the rm below does not fail. That includes a copy from a
+ # caller-supplied snapshot. Not looked up for a linked clone of a template.
+ if ($parent && ($parent->{snapshot} // '') ne '__base__') {
+ my $task = eval { rbd_flatten_task($scfg, $storeid, $name) };
+ warn $@ if $@;
+ ($task_id) = $task ? (($task->{id} // '') =~ m/^([\w-]+)$/) : ();
+ }
+ }
+ if (defined($task_id)) {
+ eval {
+ run_command(ceph_cmd($scfg, $storeid, 'rbd', 'task', 'cancel', $task_id),
+ errmsg => "cancelling rbd flatten of '$name' failed", outfunc => sub { });
+ };
+ warn $@ if $@;
+ }
+
my $snaps = rbd_ls_snap($scfg, $storeid, $name);
foreach my $snap (keys %$snaps) {
if ($snaps->{$snap}->{protected}) {
@@ -806,6 +1328,19 @@ sub free_image {
$cmd = $rbd_cmd->($scfg, $storeid, 'rm', $name);
run_rbd_command($cmd, errmsg => "rbd rm '$name' error");
+ if ($copy_parent) {
+ # Best effort: another unfinished copy may still hold the same snapshot.
+ eval {
+ # The parent may live in another pool or namespace than this storage.
+ my $spec = join('/', grep { defined && length } $copy_parent->{pool},
+ $copy_parent->{pool_namespace}, $copy_parent->{image});
+ my $c = $rbd_cmd->(
+ $scfg, $storeid, 'snap', 'rm', $spec, '--snap', $copy_parent->{snapshot},
+ );
+ run_rbd_command($c, errmsg => "rbd snap rm error", outfunc => sub { });
+ };
+ }
+
return undef;
}
@@ -1027,6 +1562,10 @@ sub volume_has_feature {
copy => { base => 1, current => 1, snap => 1 },
sparseinit => { base => 1, current => 1 },
rename => { current => 1 },
+ # The copy is produced from an RBD snapshot, so it comes from a static point
+ # in time and needs no host-side mirror to stay consistent while the source
+ # keeps changing; see copy_image_start().
+ 'copy-offload-atomic' => { base => 1, current => 1, snap => 1 },
};
my ($vtype, $name, $vmid, $basename, $basevmid, $isBase) = $class->parse_volname($volname);
diff --git a/src/test/copy_offload_naming_test.pm b/src/test/copy_offload_naming_test.pm
new file mode 100644
index 0000000..5f6d99e
--- /dev/null
+++ b/src/test/copy_offload_naming_test.pm
@@ -0,0 +1,82 @@
+package PVE::Storage::TestCopyOffloadNaming;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::Storage;
+use PVE::Storage::Plugin;
+use Test::More;
+
+# The names copy_image_start() parks its placeholder under must satisfy two opposing
+# properties at once, and a mistake in either is easy to miss:
+#
+# 1. Invisible to the volume lister. If the lister accepts the name, the placeholder
+# shows up as an unused disk of that VM, and stays there for good if the copy
+# dies mid-flight.
+# 2. Still reserving the disk number. The caller drops the storage lock between
+# prepare() and start(), so if the parked name stops reserving, a concurrent
+# allocation can take it, and the failing copy's rollback then frees somebody
+# else's volume.
+#
+# The two properties come from two different regexes, which is why a name can satisfy
+# one and not the other:
+#
+# - listers are anchored (rbd_ls: m/^(?:vm|base)-(\d+)-/,
+# LvmThin list_images: m/^(vm|base)-(\d+)-/)
+# - $get_vm_disk_number is unanchored (Plugin.pm)
+#
+# So a prefix is invisible but still reserves, and a suffix is the opposite on both
+# counts. This test pins that, because nothing about the naming looks load-bearing at a
+# glance and a rename to 'vm-101-disk-0.copytmp' would reintroduce both bugs without
+# failing anything else.
+
+# The anchored patterns the listers use, kept here so a change to either one is caught
+# rather than narrowing what these names protect without notice.
+my $rbd_lister_re = qr/^(?:vm|base)-(\d+)-/;
+my $lvmthin_lister_re = qr/^(vm|base)-(\d+)-/;
+
+my $tests = [
+ # [ name, listed?, reserves a disk number? ]
+ ['vm-101-disk-0', 1, 1], # the real volume: listed and reserving
+ ['copytmp-vm-101-disk-0', 0, 1], # parked placeholder
+ ['copynew-vm-101-disk-0', 0, 1], # staging clone
+ ['vm-101-disk-0.copytmp', 1, 1], # the SUFFIX form: listed => phantom. Do not use.
+];
+
+plan tests => scalar($tests->@*) * 3 + 2;
+
+for my $t ($tests->@*) {
+ my ($name, $listed, $reserves) = $t->@*;
+
+ is(!!($name =~ $rbd_lister_re), !!$listed, "rbd lister: '$name' listed = " . ($listed ? 1 : 0));
+ is(
+ !!($name =~ $lvmthin_lister_re), !!$listed,
+ "lvmthin lister: '$name' listed = " . ($listed ? 1 : 0),
+ );
+
+ # Unanchored: this is the reservation half.
+ is(
+ !!($name =~ qr/(vm|base)-101-disk-(\d+)/), !!$reserves,
+ "'$name' reserves a disk number = " . ($reserves ? 1 : 0),
+ );
+}
+
+# The property that matters, checked through the real allocator rather than a regex:
+# with only the parked placeholder present, disk 0 must not be handed out again.
+my $scfg = { type => 'rbd' };
+is(
+ PVE::Storage::Plugin::get_next_vm_diskname(['vm-101-disk-0'], 'st', 101, undef, $scfg),
+ 'vm-101-disk-1',
+ 'the real volume reserves its disk number',
+);
+is(
+ PVE::Storage::Plugin::get_next_vm_diskname(
+ ['copytmp-vm-101-disk-0'], 'st', 101, undef, $scfg,
+ ),
+ 'vm-101-disk-1',
+ 'a parked placeholder ALONE still reserves the disk number',
+);
+
+done_testing();
diff --git a/src/test/copy_offload_rbd_status_test.pm b/src/test/copy_offload_rbd_status_test.pm
new file mode 100644
index 0000000..73701e1
--- /dev/null
+++ b/src/test/copy_offload_rbd_status_test.pm
@@ -0,0 +1,114 @@
+package PVE::Storage::TestCopyOffloadRbdStatus;
+
+use strict;
+use warnings;
+
+use lib qw(..);
+
+use PVE::Storage::RBDPlugin;
+use PVE::CephConfig;
+use Test::More;
+
+# copy_image_status() must treat the image parent link, not the manager flatten task,
+# as the completion signal. A fast flatten of a small image can vanish from
+# `rbd task list` between the parent read and the task look-up, so a missing task while
+# the image still shows a parent is ambiguous: re-read the parent before declaring the
+# flatten dead. This pins that race (a copy that finished must not be reported as a dead
+# flatten; this was seen on a concurrent multi-disk clone) plus the
+# unambiguous states around it.
+
+my $scfg = { type => 'rbd', pool => 'testpool' };
+my $storeid = 'rbd-a';
+my $volname = 'vm-100-disk-0';
+
+# Scripted command output, consumed in call order.
+my @info_json; # what each 'rbd info' returns (parent present or not)
+my @task_json; # what each 'ceph rbd task list' returns
+
+{
+ no warnings 'redefine';
+
+ # Keep $rbd_cmd from touching the ceph config / filesystem.
+ *PVE::CephConfig::ceph_connect_option = sub { return (); };
+
+ # Every rbd subcommand copy_image_status touches goes through run_rbd_command:
+ # info -> the scripted parent state
+ # ls -> '[]' (rbd_volume_exists: the parked placeholder never exists here)
+ # other -> succeed silently (snap rm / rm are best-effort cleanup)
+ *PVE::Storage::RBDPlugin::run_rbd_command = sub {
+ my ($cmd, %param) = @_;
+ my $op = join(' ', @$cmd);
+ my $out = $param{outfunc} // sub { };
+ if ($op =~ /\binfo\b/) {
+ $out->(shift(@info_json) // '{}');
+ } elsif ($op =~ /\bls\b/) {
+ $out->('[]');
+ }
+ return 0;
+ };
+
+ # $rbd_flatten_task runs `ceph rbd task list` through run_command.
+ *PVE::Storage::RBDPlugin::run_command = sub {
+ my ($cmd, %param) = @_;
+ my $out = $param{outfunc} // sub { };
+ my $next = shift(@task_json) // '[]';
+ die "mgr unavailable\n" if $next eq 'DIE';
+ $out->($next);
+ return 0;
+ };
+}
+
+my $PARENT = '{"parent":{"pool":"testpool","image":"src","snapshot":"__copy_vm-100-disk-0"}}';
+my $NOPARENT = '{}';
+my $A_TASK =
+ '[{"refs":{"action":"flatten","image_name":"vm-100-disk-0","pool_name":"testpool"},"progress":0.5}]';
+my $NO_TASK = '[]';
+
+sub status {
+ return PVE::Storage::RBDPlugin->copy_image_status($scfg, $storeid, $volname, undef);
+}
+
+# 1. Independent on the first poll: no parent -> complete.
+@info_json = ($NOPARENT);
+@task_json = ();
+is(status()->{state}, 'complete', 'no parent on the first poll => complete');
+
+# 2. Flatten still running: parent + a live task -> pending (with progress).
+@info_json = ($PARENT);
+@task_json = ($A_TASK);
+my $st = status();
+is($st->{state}, 'pending', 'parent + a running flatten task => pending');
+is($st->{progress}, 50, ' progress surfaced from the task');
+
+# 3. The race: parent seen, task list momentarily empty, re-read shows the flatten just
+# finished. Must be complete, not a fatal "flatten no longer running".
+@info_json = ($PARENT, $NOPARENT); # info#1 parent, info#2 (re-read) parent gone
+@task_json = ($NO_TASK); # task look-up empty
+is(status()->{state}, 'complete',
+ 'empty task + parent-cleared-on-reread => complete (the fixed race)');
+
+# 4. Dead flatten: parent persists across the re-read and no task on either
+# look-up -> still fails, as before.
+@info_json = ($PARENT, $PARENT);
+@task_json = ($NO_TASK, $NO_TASK); # first lookup + the guard lookup both empty
+my $died = !eval { status(); 1 };
+ok($died, 'parent persists + no task on both look-ups => dies (real failure still fails)');
+like($@, qr/no longer running and the image is still a clone/, ' with the flatten-dead error');
+
+# 5. A failed task look-up (manager failover) is not a dead flatten: keep polling.
+@info_json = ($PARENT);
+@task_json = ('DIE');
+{
+ local $SIG{__WARN__} = sub { };
+ is(status()->{state}, 'pending', 'task list fails => pending, not a dead flatten');
+}
+@info_json = ($PARENT, $PARENT);
+@task_json = ($NO_TASK, 'DIE');
+{
+ local $SIG{__WARN__} = sub { };
+ is(status()->{state}, 'pending', 'guard look-up fails => pending, not a dead flatten');
+}
+
+done_testing();
+
+1;
diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index 57e3140..c8db425 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -26,6 +26,8 @@ my $res = $harness->runtests(
"plugin_load_test.pm",
"plugin_properties_test.pm",
"copy_offload_test.pm",
+ "copy_offload_naming_test.pm",
+ "copy_offload_rbd_status_test.pm",
);
exit -1 if !$res || $res->{failed} || $res->{parse_errors};
--
2.55.0
next prev parent reply other threads:[~2026-11-26 16:57 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-26 16:56 [RFC PATCH storage/qemu-server/docs v2 0/6] offload full clone to the storage backend Ciro Iriarte
2026-11-26 16:56 ` [RFC PATCH storage v2 1/6] storage: add asynchronous copy-offload hook for full copies Ciro Iriarte
2026-11-26 16:56 ` Ciro Iriarte [this message]
2026-11-26 16:57 ` [RFC PATCH storage v2 3/6] dir: implement copy-offload via reflink (FICLONE) Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH storage v2 4/6] btrfs, lvmthin: implement copy-offload (atomic class) Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH qemu-server v2 5/6] use storage copy-offload for full clone Ciro Iriarte
2026-11-26 16:57 ` [RFC PATCH docs v2 6/6] pvesm: document copy-offload and add it to the storage capability table Ciro Iriarte
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261126.2.copyoffload-v2@cyruspy.gmail.com \
--to=cyruspy@gmail.com \
--cc=pve-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.