From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 6700A1FF0B3 for ; Thu, 26 Nov 2026 17:58:14 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 097CC21797; Thu, 26 Nov 2026 17:58:03 +0100 (CET) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1795712254; x=1796317054; darn=lists.proxmox.com; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:subject:cc:to:from:date:from:to:cc:subject :date:message-id:reply-to:content-type; bh=N3IKkkvqMvCchyohIa6nUJvsxMWFwJmbPxdyMLpzeWI=; b=SB6yvn4iYfhnkNh8wA4J/CvHZIduwEEJ/7nN/dieFiiALYYtMG1/IyiXae0vvgBFoJ 49/jOx0T8aZD6GNyspNOnW2UL1uDEO0gskoXlR+OgU4O34chyIwmhh4UlBWPBzhMf5yW kwfV/SGBaJ3lsfK2hIcOZrTuvKiPHLUJ2s3SdEI7cG9ggMU/HR95el50vlCt4pL95CId DBitU/mDHFOOKvbe8g2Ca34h7PozUAIE/SkpRVuGryhAnVTkDLWTJndHQOV5VTfX4BhU //e12NEubOo5HjHKwyv4f+a4CaZbvPy9nBmwXdhgyywEA0UZS4P7V99Ak3a3/Sdw+Q4J iY/g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795712254; x=1796317054; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:subject:cc:to:from:date:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=N3IKkkvqMvCchyohIa6nUJvsxMWFwJmbPxdyMLpzeWI=; b=G/VShQm2u5lPQ6V4fC6yzl8x1zULO50UgE5D43M6czETaenprAvu0AIghPvCgiatvY tGP3Rk05JwhZ4mWDReVlo0+vCL5f4vD0hU/4AMdWmkbkINtUfzdQbLrTxhifxEa91cFQ KdijEBfk34q8Ly3jB8+I7XXCcWIe+4324TeBzGAZTIrhx47T8wUXF1u3IWeCTUkAJwaO 5vYloMRag2sOdYZskIOn7GQ8pJPedr5KSwFqygiPCzasNnWhUAFUv7FuL+7jXvOaTR3S WftSLeXkDDP+C2xyRkSiFzHlEcpnvV6tal/6K7gPR/4QGkmfAA2UTEpE6OfTlLEEvjus DGKg== X-Gm-Message-State: APuU4Z8xrre21OWf8oicA05pE5rrcKZmWrEHfmS8yzcqsD7bztJZdx7J 3lAwiFZLsdeW7wtE1NQw9aHgyUFHU9VnfiiTgKCHv/FgdpfohFpwVjoA X-Gm-Gg: AZFdTZeTqqem04iMJ8OljRcy5Xo32uE3GOXmRtKujfVxD+j3Kt0P3KtROxwnxlmEUlw tI1d7CpvAoc2RJrZ1hT+fs7KkGeLnf0ElJbJ+n7HmjFTBYJha6Kqa4wVdoSze2OpQJqFSNMC/EV ItWaxeNkQg7rNCwXOTweeO1TvmBWgkyTPvLVADeVVlxQVwzWCma6N8YiPGlESTUj5bU/gN10dSO WX42ACFgr6xaZGSRujDNk4q+b4oSH+SSCEIFRQxPRM9qFXdqzj0zhSB8NJvo08MKi7cGQYbK6kf w/8v81twwsQTYPmu0u7VGtyPZ8TbLVNQVYmvPteU5It2RuqCgFx6trFkO/5KQNXaa9K1iR+yk1o DXzDWhPhgeBo+t3GwKNTosRYCHI4L6CvUpROzi0mO06awL+CAhh3w/ejGqL+XYrCcJQJK5Sdt7A J75VpNLwwtOVt08J6UhOTRuiqJhYQm/WcAXGImmlZ2c1gf+ms0oKo30SyByqdzL2IfFDMUevd3v 3++QdafET9auTNeYgrn4ctAcYPkBnUh+rxZNj0FvcFtJjkl7i/js0qdcsEm6T2s8MvESrn0npfL iWQtcaWKPqs+u10pjd03fv8= X-Received: by 2002:a05:6122:1816:b0:5ec:4112:6839 with SMTP id 71dfb90a1353d-5ee8af18034mr11384654e0c.15.1795712253567; Thu, 26 Nov 2026 08:57:33 -0800 (PST) Date: Thu, 26 Nov 2026 13:57:05 -0300 From: Ciro Iriarte To: pve-devel@lists.proxmox.com Subject: [RFC PATCH qemu-server v2 5/6] use storage copy-offload for full clone Message-ID: <20261126.5.copyoffload-v2@cyruspy.gmail.com> In-Reply-To: <20261126.0.copyoffload-v2@cyruspy.gmail.com> References: <20261126.0.copyoffload-v2@cyruspy.gmail.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL -0.859 Adjusted score from AWL reputation of From: address DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature DKIM_VALID_AU -0.1 Message has a valid DKIM or DK signature from author's domain DKIM_VALID_EF -0.1 Message has a valid DKIM or DK signature from envelope-from domain DMARC_PASS -0.1 DMARC pass policy FREEMAIL_FROM 0.001 Sender email is commonly abused enduser mail provider KAM_MAILER 2 Automated Mailer Tag Left in Email RCVD_IN_DNSWL_NONE -0.0001 Sender listed at https://www.dnswl.org/, no trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: NQXLNSWUUSLX3325LUQZNGCX7A6ZZ6U5 X-Message-ID-Hash: NQXLNSWUUSLX3325LUQZNGCX7A6ZZ6U5 X-MailFrom: cyruspy@gmail.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: From: Ciro Iriarte Use the pve-storage copy-offload hook for full clones. An offloaded copy replaces both halves of a full clone in clone_disk(), the allocation and the data copy, since the backend creates the target itself. The decision and the offloaded copy live in two helpers, and clone_disk() picks between linked clone, offload and the existing path. For a running guest, consistency across disks is a VM-level property: clone_vm() calls clone_disk() per drive, and BlockJob::monitor() cuts all mirrors over in one freeze. An offloaded copy started per disk would capture each disk at a different instant. So for the attached disks of a running guest, clone_disk() only reserves the target and defers the start, which captures the point in time. monitor() gains an on_frozen callback, run at the cut-over, which starts the deferred copies. Offloaded and mirrored disks are then captured at the same instant. The copies are waited on afterwards, with the guest running. Every cut-over gets the callback, including the one triggered by a final cloud-init drive, and starting is idempotent. When every disk is offloaded there is no cut-over, so clone_vm() quiesces the guest itself. Both use the new BlockJob::run_with_guest_quiesced(), which takes over the freeze and suspend logic from monitor() and thaws or resumes the guest before re-raising an error. If the guest can be neither frozen nor suspended, the mirrors are still cut over, as on master, but the deferred copies are not started and the clone fails: their targets are only reservations, so a host-side copy is no longer possible. A live disk move has no freeze to defer into, so offload is skipped there without asking the storage. Four changes from monitor()'s old behaviour also apply to a clone without offload: * when the guest agent's freeze fails, the guest is suspended instead of continuing unquiesced * a guest that is already paused stays paused instead of being resumed afterwards; one whose state cannot be queried is not quiesced, matching what master does when the suspend fails * a failed thaw or resume is reported with log_warn(), so the task ends with a warning instead of a plain message; failing it would discard a finished clone, and on Windows the agent's freeze is limited to about ten seconds, after which the thaw reports an error * when a failed freeze cannot be undone either, the guest is suspended and the thaw is retried after the resume run_guest_quiesce_tests.pl covers these paths. A snapshot or a detached disk cannot change during the copy, so its copy runs right away. A deferred copy records the source's size, as its target is only a reservation until copy_image_start() runs. 'bulk' falls back to the host-side path for an attached disk of a running guest: it smears over a changing source, and the mirror convergence it would need is not implemented. cloudinit, efidisk0 and tpmstate0 are never offloaded. Signed-off-by: Ciro Iriarte --- Changes in v2: * rebased onto current master, where the data copy moved into clone_disk_copy_data(); the goto that commit removed is not brought back: the offload decision and copy are two helpers, and clone_disk() picks between linked clone, offload and the existing path * a deferred copy records the source size in the config; v1 recorded the size of the placeholder * the cut-over triggered by a final cloud-init drive also starts the deferred copies; in v1 they got a second freeze of their own * only the attached disks of a running guest are deferred; v1 also deferred a copy from a snapshot and suspended the guest for nothing * the quiesce logic moved into BlockJob::run_with_guest_quiesced(), shared by monitor() and the all-offloaded case. A failed guest agent freeze now falls back to suspend, including clones without offload. If that fails too, deferred copies are not started and the clone fails. * a guest that is already paused is left paused; a failed thaw or resume ends the task with a warning (log_warn) rather than a plain message, and if a failed freeze cannot be undone, the thaw is retried after the resume. These also apply to clones without offload. New run_guest_quiesce_tests.pl * a guest whose state cannot be queried is not quiesced, so a paused guest is never resumed by mistake * a live disk move no longer queries the storage, as it cannot defer * deferred copies print their progress while being waited on * needs a libpve-storage-perl that ships APIVER 18 (1/6); debian/control is not bumped here src/PVE/API2/Qemu.pm | 17 +++ src/PVE/QemuServer.pm | 225 ++++++++++++++++++++++++++-- src/PVE/QemuServer/BlockJob.pm | 119 +++++++++++---- src/test/Makefile | 5 +- src/test/run_guest_quiesce_tests.pl | 154 +++++++++++++++++++ 5 files changed, 479 insertions(+), 41 deletions(-) create mode 100755 src/test/run_guest_quiesce_tests.pl diff --git a/src/PVE/API2/Qemu.pm b/src/PVE/API2/Qemu.pm index 2119e69e..44c9bc64 100644 --- a/src/PVE/API2/Qemu.pm +++ b/src/PVE/API2/Qemu.pm @@ -4902,6 +4902,9 @@ __PACKAGE__->register_method({ my $newvollist = []; my $jobs = {}; + # storage-offloaded copies whose start is deferred into the guest freeze, so + # that every disk of a running VM is captured at the same instant + my $deferred_copies = []; eval { local $SIG{INT} = local $SIG{TERM} = local $SIG{QUIT} = local $SIG{HUP} = @@ -4953,6 +4956,7 @@ __PACKAGE__->register_method({ $completion, $oldconf->{agent}, $clonelimit, + $deferred_copies, ); $newconf->{$opt} = PVE::QemuServer::print_drive($newdrive); @@ -4961,6 +4965,19 @@ __PACKAGE__->register_method({ $i++; } + # Anything still unstarted means there was no mirror cutover to + # piggyback the freeze on (every disk was offloaded), so freeze + # here. Keyed on the copies themselves rather than on %$jobs, so it + # cannot double-start if the job bookkeeping changes. + if (grep { !$_->{started} } @$deferred_copies) { + PVE::QemuServer::freeze_and_run_deferred_copies( + $storecfg, $vmid, $oldconf->{agent}, $deferred_copies, + ); + } + + # the guest is running again; the data movement is waited for here + PVE::QemuServer::wait_deferred_copies($storecfg, $deferred_copies); + delete $newconf->{lock}; # do not write pending changes diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm index 1d665877..8d7b84d6 100644 --- a/src/PVE/QemuServer.pm +++ b/src/PVE/QemuServer.pm @@ -7991,7 +7991,10 @@ my sub clone_disk_check_io_uring { } my sub clone_disk_copy_data { - my ($storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit) = @_; + my ( + $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit, + $on_frozen, + ) = @_; my ($vmid, $drive, $size, $snapname) = $source->@{qw(vmid drive size snapname)}; my ($newvmid, $newvolid, $dst_drivename, $dst_format) = @@ -8006,6 +8009,9 @@ my sub clone_disk_copy_data { my $mirror_opts = {}; $mirror_opts->{'guest-agent'} = $qga; $mirror_opts->{bwlimit} = $bwlimit if defined($bwlimit); + # Start any deferred offloaded copies inside the freeze this mirror's + # completion takes, putting every disk of the VM at one point in time. + $mirror_opts->{'on-frozen'} = $on_frozen if $on_frozen; PVE::QemuServer::BlockJob::mirror( $source_info, $dest_info, @@ -8051,8 +8057,180 @@ my sub clone_disk_copy_data { return; } +# Start every deferred storage-offloaded copy. Must be called with the guest frozen (or +# suspended): the start is what captures each copy's point in time, so doing them all here +# is what makes a multi-disk clone consistent. +# +# One batch, so that a backend able to capture several volumes at once +# (copy_images_start()) does so. +# +# Kept cheap: the guest is stalled for the duration. The data movement runs +# afterwards and is waited for by wait_deferred_copies(), with the guest running again. +sub run_deferred_copies { + my ($storecfg, $deferred_copies, $quiesced) = @_; + + return if !$deferred_copies; + + # idempotent: never start a copy twice + my $pending = [grep { !$_->{started} } @$deferred_copies]; + return if !scalar(@$pending); + + # Without a freeze or suspend the starts would land at different instants while the + # guest writes, which is what deferring them is meant to prevent. + die "guest could not be frozen or suspended - not starting the offloaded copies\n" + if !$quiesced; + + # vdisk_copy_start_group() flags each copy as it starts it, so a failure partway + # through leaves an accurate record of what is running. + PVE::Storage::vdisk_copy_start_group($storecfg, $pending); + + return; +} + +# Wait for the deferred copies to become independent of their sources. Runs with the +# guest already thawed: only the starts need the freeze, not the data movement. +sub wait_deferred_copies { + my ($storecfg, $deferred_copies) = @_; + + return if !$deferred_copies; + + for my $copy (@$deferred_copies) { + # Never accept an unstarted copy: its target is allocated but its + # content is undefined, so returning it would hand out a corrupt disk. + die "internal error - offloaded copy of '$copy->{source}' was never started\n" + if !$copy->{started}; + + print("waiting for offloaded copy of '$copy->{source}' to become independent\n"); + PVE::Storage::vdisk_copy_wait( + $storecfg, $copy->{target}, $copy->{source}, sub { print("copy progress: $_[0]%\n") }, + ); + } +} + +# Freeze the guest, start the deferred copies, thaw. Used when a clone has no mirror +# jobs to rendezvous with (every disk was offloaded), so there is no +# BlockJob::monitor() freeze to piggyback on. Quiesces the same way monitor() does. +sub freeze_and_run_deferred_copies { + my ($storecfg, $vmid, $qga, $deferred_copies) = @_; + + return if !$deferred_copies || !scalar(@$deferred_copies); + + PVE::QemuServer::BlockJob::run_with_guest_quiesced( + $vmid, $qga, sub { run_deferred_copies($storecfg, $deferred_copies, @_) }, + ); + + return; +} + +# The copy-offload class to use for a full clone of this disk, or undef for the host-side +# copy, and whether its start has to be deferred into the guest freeze. +my sub clone_disk_offload_class { + my ($storecfg, $source, $dest, $storeid, $deferred_copies) = @_; + + my ($running, $src_drivename, $drive, $snapname) = + $source->@{qw(running drivename drive snapname)}; + my $dst_drivename = $dest->{drivename}; + + # Not for the special drives: cloudinit is regenerated rather than copied, efidisk0 is + # copied with a size-limited qemu-img dd, and tpmstate0 is allocated at the size its + # TPM version needs. An opaque backend copy reproduces none of that. Either side being + # special is disqualifying. + my $special_re = qr/^(?:efidisk0|tpmstate0)$/; + return if drive_is_cloudinit($drive); + return if defined($dst_drivename) && $dst_drivename =~ $special_re; + return if defined($src_drivename) && $src_drivename =~ $special_re; + + # Multi-disk consistency is a VM-level property here: clone_vm() calls clone_disk() + # once per drive, and BlockJob::monitor() cuts every mirror over in one freeze. The + # current state of a running guest's attached disk changes under the copy, so its start, + # which fixes its point in time, waits for that freeze. A snapshot or a detached + # disk does not change and is copied right away. + my $unused = defined($src_drivename) && $src_drivename =~ /^unused/; + my $defer = $running && !$snapname && !$unused; + # deferring needs a caller that runs the freeze, such as clone_vm(); a live disk move + # has none, so do not even ask the storage + return if $defer && !$deferred_copies; + + my $class = PVE::Storage::copy_offload_class( + $storecfg, $drive->{file}, $storeid, $snapname, $running, { format => $dest->{format} }, + ); + return if !$class; + + # 'bulk' smears over a changing source and would need a bitmap-seeded mirror to + # converge, which is not implemented, so take the host-side path instead. + return if $defer && $class ne 'atomic'; + + return ($class, $defer); +} + +# Full clone through the storage backend (pve-storage copy_image). It replaces both the +# allocation and the host-side copy, since the backend creates the target itself. Returns +# the new volid and, for a deferred copy, the size to record: until its start, the target +# is only a reservation. +my sub clone_disk_offload { + my ( + $storecfg, $source, $dest, $storeid, $class, $defer, $newvollist, $jobs, $completion, + $qga, $deferred_copies, $on_frozen, + ) = @_; + + my ($vmid, $drive, $snapname) = $source->@{qw(vmid drive snapname)}; + my $newvmid = $dest->{vmid}; + my $opts = { format => $dest->{format} }; + + if ($defer) { + print("offloading full copy to storage backend ($class, deferred)\n"); + + my $newvolid = PVE::Storage::vdisk_copy_prepare( + $storecfg, $drive->{file}, $storeid, $newvmid, $snapname, $opts, + ); + push @$newvollist, $newvolid; + + # recorded as plain volids: the starts are issued as one batch, so that a backend + # able to group them can capture every disk at a single instant + push @$deferred_copies, + { source => $drive->{file}, target => $newvolid, snap => $snapname }; + + print("allocated target volume '$newvolid', copy starts at freeze\n"); + + # On the last disk with mirror jobs pending, the cut-over happens here: nothing + # after this calls monitor(). + if (($completion && $completion eq 'complete') && scalar(keys %$jobs) > 0) { + PVE::QemuServer::BlockJob::monitor( + vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga, undef, $on_frozen, + ); + } + + return ($newvolid, scalar(PVE::Storage::volume_size_info($storecfg, $drive->{file}, 10))); + } + + print("offloading full copy to storage backend ($class)\n"); + + my $newvolid = PVE::Storage::vdisk_copy( + $storecfg, + $drive->{file}, + $storeid, + $newvmid, + $snapname, + $opts, + sub { print("copy progress: $_[0]%\n") }, + ); + push @$newvollist, $newvolid; + + print("created target volume '$newvolid' on the backend\n"); + + PVE::Storage::activate_volumes($storecfg, [$newvolid]); + + return ($newvolid, undef); +} + +# $deferred_copies is an optional arrayref collecting storage-offloaded copies whose +# start must happen inside the caller's guest freeze; see clone_disk_offload() and +# run_deferred_copies(). Without it, a running source is never offloaded. sub clone_disk { - my ($storecfg, $source, $dest, $full, $newvollist, $jobs, $completion, $qga, $bwlimit) = @_; + my ( + $storecfg, $source, $dest, $full, $newvollist, $jobs, $completion, $qga, $bwlimit, + $deferred_copies, + ) = @_; my ($vmid, $running) = $source->@{qw(vmid running)}; my ($src_drivename, $drive, $snapname) = $source->@{qw(drivename drive snapname)}; @@ -8077,26 +8255,45 @@ sub clone_disk { die "cannot move TPM state while VM is running\n" if $use_drive_mirror && $src_drivename eq 'tpmstate0'; - my $newvolid; + my ($newvolid, $offload_size); print "create " . ($full ? 'full' : 'linked') . " clone of drive "; print "$src_drivename " if $src_drivename; print "($drive->{file})\n"; - if (!$full) { - $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname); - push @$newvollist, $newvolid; - } else { - my ($src_storeid) = PVE::Storage::parse_volume_id($drive->{file}); - my $storeid = $storage || $src_storeid; + # A full clone's target storage and format, and whether the backend copies it. + my ($src_storeid, $storeid, $dst_format, $offload_class, $defer, $on_frozen); + if ($full) { + ($src_storeid) = PVE::Storage::parse_volume_id($drive->{file}); + $storeid = $storage || $src_storeid; - my $dst_format = resolve_dst_disk_format($storecfg, $storeid, $drive->{file}, $format); + $dst_format = resolve_dst_disk_format($storecfg, $storeid, $drive->{file}, $format); if ($format && $format ne $dst_format) { warn "format '$format' is not supported by the target storage '$storeid' - using" . " '$dst_format' instead\n"; } $dest->{format} = $dst_format; + # Deferred offloaded copies start inside whichever freeze cuts the mirror jobs + # over (this or a later disk's, or clone_vm()'s own when there is none), so the + # offloaded and mirrored disks of a VM share an instant. Idempotent, so every + # cut-over gets it, including the one a final cloud-init drive triggers. + $on_frozen = sub { run_deferred_copies($storecfg, $deferred_copies, @_) } + if $deferred_copies; + + ($offload_class, $defer) = + clone_disk_offload_class($storecfg, $source, $dest, $storeid, $deferred_copies); + } + + if (!$full) { + $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname); + push @$newvollist, $newvolid; + } elsif ($offload_class) { + ($newvolid, $offload_size) = clone_disk_offload( + $storecfg, $source, $dest, $storeid, $offload_class, $defer, $newvollist, $jobs, + $completion, $qga, $deferred_copies, $on_frozen, + ); + } else { my $name = undef; my $size = undef; if (drive_is_cloudinit($drive)) { @@ -8140,18 +8337,20 @@ sub clone_disk { # previous drive-mirrors if (($completion && $completion eq 'complete') && (scalar(keys %$jobs) > 0)) { PVE::QemuServer::BlockJob::monitor( - vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga, + vm_qmp_peer($vmid), $newvmid, $jobs, $completion, $qga, undef, + $on_frozen, ); } # No data needs to be copied for the cloudinit drive. } else { clone_disk_copy_data( - $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, $bwlimit, + $storecfg, $source, $dest, $use_drive_mirror, $jobs, $completion, $qga, + $bwlimit, $on_frozen, ); } } - my $size = eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) }; + my $size = $offload_size // eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) }; my $disk = dclone($drive); delete $disk->{format}; diff --git a/src/PVE/QemuServer/BlockJob.pm b/src/PVE/QemuServer/BlockJob.pm index c6af8576..d475d44c 100644 --- a/src/PVE/QemuServer/BlockJob.pm +++ b/src/PVE/QemuServer/BlockJob.pm @@ -81,13 +81,82 @@ sub qemu_blockjobs_cancel { } } +# Run $code with the guest quiesced: fs-frozen through the guest agent where that +# applies, suspended otherwise or when the freeze fails. A guest that is not running +# (paused, suspended) is left as it is. $code gets whether the guest is quiesced. +# +# The guest is thawed or resumed whatever $code did. A failure to do so is reported with +# log_warn(), so the task ends with a warning: failing it would discard a finished copy, +# and the guest agent's freeze on Windows is limited to about ten seconds, after which +# the thaw itself reports an error. +sub run_with_guest_quiesced { + my ($vmid, $qga, $code) = @_; + + my $mode; # how the guest was quiesced: 'freeze', 'suspend', 'as-is' or undef + my $thaw_pending; # a failed freeze whose thaw failed too + my $status = eval { mon_cmd($vmid, 'query-status')->{status} }; + if ($@ || !defined($status)) { + # Not knowing whether the guest was paused, do not risk resuming it: run $code + # unquiesced, which refuses what needs a quiesced guest. + warn "cannot query the state of VM $vmid, not quiescing it - " . ($@ || "no status\n"); + $status = undef; + } elsif ($status ne 'running') { + print "vm is not running ($status), leaving it as it is\n"; + $mode = 'as-is'; + } elsif (PVE::QemuServer::Agent::guest_fs_freeze_applicable($qga, $vmid)) { + print "issuing guest agent 'guest-fsfreeze-freeze' command\n"; + eval { PVE::QemuServer::Agent::guest_fs_freeze($vmid); }; + if (my $err = $@) { + warn $err; + # The freeze may have frozen some filesystems before failing. + eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); }; + $thaw_pending = 1 if $@; + } else { + $mode = 'freeze'; + } + } + if (!$mode && defined($status)) { + print "suspend vm\n"; + eval { PVE::QemuServer::RunState::vm_suspend($vmid, 1); }; + if (my $err = $@) { + warn $err; + } else { + $mode = 'suspend'; + } + } + + my @res = eval { $code->(defined($mode)) }; + my $err = $@; + + if (defined($mode) && $mode eq 'suspend') { + print "resume vm\n"; + eval { PVE::QemuServer::RunState::vm_resume($vmid, 1, 1); }; + log_warn("failed to resume VM $vmid, it may still be paused - $@") if $@; + } + if ((defined($mode) && $mode eq 'freeze') || $thaw_pending) { + print "issuing guest agent 'guest-fsfreeze-thaw' command\n"; + eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); }; + log_warn("failed to thaw the guest filesystems of VM $vmid, check them in the guest - $@") + if $@; + } + + die $err if $err; + + return wantarray ? @res : $res[0]; +} + # $completion can be either # 'complete': wait until all jobs are ready, job-complete them (default) # 'cancel': wait until all jobs are ready, block-job-cancel them # 'skip': wait until all jobs are ready, return with block jobs in ready state # 'auto': wait until all jobs disappear, only use for jobs which complete automatically +# +# $on_frozen is an optional coderef, run while the guest is quiesced at the instant the +# mirror jobs are cut over, with whether the quiesce succeeded. Clone uses it to start +# storage-offloaded copies there, so that a VM's offloaded and mirrored disks share one +# point in time. sub monitor { - my ($qmp_peer, $vmiddst, $jobs, $completion, $qga, $op) = @_; + my ($qmp_peer, $vmiddst, $jobs, $completion, $qga, $op, $on_frozen) = @_; die "drive mirror: different destination is only supported when peer is main QEMU instance\n" if $vmiddst && $qmp_peer->{type} ne 'qmp'; @@ -169,31 +238,24 @@ sub monitor { last if $completion eq 'skip' || $completion eq 'auto'; if ($qmp_peer->{type} eq 'qmp' && $vmiddst && $vmiddst != $qmp_peer->{id}) { - my $vmid = $qmp_peer->{id}; - my $should_fsfreeze = - PVE::QemuServer::Agent::guest_fs_freeze_applicable($qga, $vmid); - if ($should_fsfreeze) { - print "issuing guest agent 'guest-fsfreeze-freeze' command\n"; - eval { PVE::QemuServer::Agent::guest_fs_freeze($vmid); }; - warn $@ if $@; - } else { - print "suspend vm\n"; - eval { PVE::QemuServer::RunState::vm_suspend($vmid, 1); }; - warn $@ if $@; - } - - # if we clone a disk for a new target vm, we don't switch the disk - qemu_blockjobs_cancel($qmp_peer, $jobs); - - if ($should_fsfreeze) { - print "issuing guest agent 'guest-fsfreeze-thaw' command\n"; - eval { PVE::QemuServer::Agent::guest_fs_thaw($vmid); }; - warn $@ if $@; - } else { - print "resume vm\n"; - eval { PVE::QemuServer::RunState::vm_resume($vmid, 1, 1); }; - warn $@ if $@; - } + run_with_guest_quiesced( + $qmp_peer->{id}, + $qga, + sub { + my ($quiesced) = @_; + # Storage-offloaded copies start here: their point in time is + # fixed by the start, so doing it inside the freeze is what + # puts them at the same instant as the mirrored disks cut + # over below. The cut-over happens either way. + eval { $on_frozen->($quiesced) if $on_frozen; }; + my $err = $@; + + # if we clone a disk for a new target vm, we don't switch the disk + qemu_blockjobs_cancel($qmp_peer, $jobs); + + die $err if $err; + }, + ); last; } else { @@ -284,6 +346,7 @@ sub qemu_drive_mirror { $qga, $bwlimit, $src_bitmap, + $on_frozen, ) = @_; my $device_id = "drive-$drive_id"; @@ -319,7 +382,7 @@ sub qemu_drive_mirror { die "mirroring error: $err\n"; } - monitor(vm_qmp_peer($vmid), $vmiddst, $jobs, $completion, $qga); + monitor(vm_qmp_peer($vmid), $vmiddst, $jobs, $completion, $qga, undef, $on_frozen); } # Callers should version guard this (only available with a binary >= QEMU 8.2) @@ -523,6 +586,7 @@ sub blockdev_mirror { $completion, $options->{'guest-agent'}, 'mirror', + $options->{'on-frozen'}, ); } @@ -546,6 +610,7 @@ sub mirror { $options->{'guest-agent'}, $options->{bwlimit}, $source->{bitmap}, + $options->{'on-frozen'}, ); } } diff --git a/src/test/Makefile b/src/test/Makefile index 2d3a55da..c0ae031e 100644 --- a/src/test/Makefile +++ b/src/test/Makefile @@ -1,6 +1,6 @@ all: test -test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network +test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_guest_quiesce test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network test_snapshot: run_snapshot_tests.pl ./run_snapshot_tests.pl @@ -48,6 +48,9 @@ test_memory: run_memory_tests.pl test_agent: run_agent_tests.pl ./run_agent_tests.pl +test_guest_quiesce: run_guest_quiesce_tests.pl + ./run_guest_quiesce_tests.pl + test_raw_config_write: run_raw_config_write_tests.pl ./run_raw_config_write_tests.pl diff --git a/src/test/run_guest_quiesce_tests.pl b/src/test/run_guest_quiesce_tests.pl new file mode 100755 index 00000000..57be58c4 --- /dev/null +++ b/src/test/run_guest_quiesce_tests.pl @@ -0,0 +1,154 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use lib qw(..); + +use Test::MockModule; +use Test::More; + +use PVE::QemuServer::BlockJob; + +# run_with_guest_quiesced(): how the guest is quiesced, that it is always released, and +# that a failed release ends the task with a warning instead of failing it. + +my @calls; +my %fail; # name of a call => error it raises, or an arrayref of errors for successive calls +my @warnings; # what log_warn() got +my $status = 'running'; +my $freeze_applicable = 1; + +my $call = sub { + my ($name) = @_; + push @calls, $name; + my $f = $fail{$name}; + $f = shift(@$f) if ref($f) eq 'ARRAY'; + die $f if $f; +}; + +my $blockjob = Test::MockModule->new('PVE::QemuServer::BlockJob'); +$blockjob->redefine( + mon_cmd => sub { die "qmp timeout\n" if $status eq 'DIE'; return { status => $status } }, + log_warn => sub { push @warnings, $_[0] }, +); +my $agent = Test::MockModule->new('PVE::QemuServer::Agent'); +$agent->redefine( + guest_fs_freeze_applicable => sub { $freeze_applicable }, + guest_fs_freeze => sub { $call->('freeze') }, + guest_fs_thaw => sub { $call->('thaw') }, +); +my $runstate = Test::MockModule->new('PVE::QemuServer::RunState'); +$runstate->redefine( + vm_suspend => sub { $call->('suspend') }, + vm_resume => sub { $call->('resume') }, +); + +my $tests = [ + { + name => 'agent freeze, then thaw', + calls => ['freeze', 'code', 'thaw'], + quiesced => 1, + }, + { + name => 'no agent: suspend, then resume', + freeze_applicable => 0, + calls => ['suspend', 'code', 'resume'], + quiesced => 1, + }, + { + name => 'failed freeze falls back to suspend', + fail => { freeze => "agent timeout\n" }, + calls => ['freeze', 'thaw', 'suspend', 'code', 'resume'], + quiesced => 1, + }, + { + name => 'nothing quiesces: code runs unquiesced', + fail => { freeze => "agent timeout\n", suspend => "qmp timeout\n" }, + calls => ['freeze', 'thaw', 'suspend', 'code'], + quiesced => 0, + }, + { + name => 'a paused guest is left paused', + status => 'paused', + calls => ['code'], + quiesced => 1, + }, + { + name => 'state unknown: not quiesced, so a paused guest is not resumed', + status => 'DIE', + calls => ['code'], + quiesced => 0, + }, + { + name => 'error from code: the guest is still thawed', + fail => { code => "copy failed\n" }, + calls => ['freeze', 'code', 'thaw'], + error => qr/^copy failed$/, + }, + { + name => 'failed thaw warns, the operation stands', + fail => { thaw => "agent gone\n" }, + calls => ['freeze', 'code', 'thaw'], + quiesced => 1, + warning => qr/failed to thaw the guest filesystems of VM 100.*agent gone/s, + }, + { + name => 'failed resume warns, the operation stands', + freeze_applicable => 0, + fail => { resume => "qmp gone\n" }, + calls => ['suspend', 'code', 'resume'], + quiesced => 1, + warning => qr/failed to resume VM 100, it may still be paused - qmp gone/, + }, + { + name => 'failed freeze whose thaw fails: thawed again after the resume', + fail => { freeze => "agent timeout\n", thaw => ["agent busy\n", undef] }, + calls => ['freeze', 'thaw', 'suspend', 'code', 'resume', 'thaw'], + quiesced => 1, + }, + { + name => 'failed freeze whose thaw keeps failing: warns', + fail => { freeze => "agent timeout\n", thaw => "agent gone\n" }, + calls => ['freeze', 'thaw', 'suspend', 'code', 'resume', 'thaw'], + quiesced => 1, + warning => qr/failed to thaw the guest filesystems/, + }, +]; + +for my $t (@$tests) { + @calls = (); + @warnings = (); + %fail = map { $_ => (ref($t->{fail}->{$_}) ? [$t->{fail}->{$_}->@*] : $t->{fail}->{$_}) } + keys(($t->{fail} // {})->%*); + $status = $t->{status} // 'running'; + $freeze_applicable = $t->{freeze_applicable} // 1; + + my $quiesced; + local $SIG{__WARN__} = sub { }; + eval { + PVE::QemuServer::BlockJob::run_with_guest_quiesced( + 100, undef, + sub { + ($quiesced) = @_; + $call->('code'); + }, + ); + }; + my $err = $@; + + is_deeply(\@calls, $t->{calls}, "$t->{name}: calls"); + if ($t->{error}) { + like($err, $t->{error}, "$t->{name}: error"); + } else { + is($err, '', "$t->{name}: no error"); + is($quiesced ? 1 : 0, $t->{quiesced}, "$t->{name}: quiesced flag"); + } + if ($t->{warning}) { + like(join('', @warnings), $t->{warning}, "$t->{name}: warning"); + } else { + is(scalar(@warnings), 0, "$t->{name}: no warning"); + } +} + +done_testing(); -- 2.55.0