public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH container v2 22/36] restore: take over the guest uid from the backup where possible
Date: Tue, 17 Nov 2026 23:34:32 +0100	[thread overview]
Message-ID: <20261117223945.862914-23-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261117223945.862914-1-t.lamprecht@proxmox.com>

A restore to an unused VMID, or over a container without an identity,
should keep the uid of the backup if no other guest in the cluster uses
it. Take over that uid after the data is restored and the final config
is written, while holding the config lock. With 'unique', or if the uid
is in use, the container keeps the identity assigned when its VMID was
reserved. In all these cases the registration time is the time of the
restore. A container that already had an identity keeps both its uid
and its registration time.

Taking over the uid only after the restore succeeded means that a
failed restore does not take the uid for a container it leaves behind.
If the cluster-wide lock cannot be taken, warn and do not fail the
completed restore; the container keeps its own identity. Report the
outcome in the task log.

Record the uid of the backup as a pending change of 'meta' until the
restore finishes, if the restore could take it over. A retry over a
container left behind by an unfinished restore can then take the uid
over, if no other guest uses it. Record it with 'unique' too, which only
keeps the current restore from taking the uid. If the cluster-wide lock
cannot be taken, the pending uid stays for a later attempt.

A pending uid does not count as in use, so a retry at another VMID
stays possible. Outside of a restore, applying pending changes drops
it.

For restores from a file, PBS or a backup provider, record the pending
uid as soon as the config of the backup is known and keep it in the
configs that the restore writes afterwards. For standard input, the uid
is only known from the restored config, as API parameters cannot set
'meta'. That config carries the pending uid, also if the conversion to
a template writes it first. Archives without a PVE config have no uid.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---

changes v1 -> v2:
* use the shared helper of pve-guest-common for the take-over
* describe the effect of 'unique'
* test the order of the cleanup after a failed restore

 src/PVE/API2/LXC.pm         |  42 +++-
 src/test/lifecycle_tests.pl | 463 +++++++++++++++++++++++++++++++++++-
 2 files changed, 498 insertions(+), 7 deletions(-)

diff --git a/src/PVE/API2/LXC.pm b/src/PVE/API2/LXC.pm
index a65d5ae..5fea82f 100644
--- a/src/PVE/API2/LXC.pm
+++ b/src/PVE/API2/LXC.pm
@@ -62,6 +62,18 @@ my sub assert_not_restore_from_external {
     die "refusing to restore privileged container backup from external source\n";
 }
 
+# Returns the uid of the backup if the restore could take it over at its end, see
+# PVE::GuestIdentity::adoptable_uid. Until then, the restore keeps it as pending uid in every config
+# it writes, so that a container left behind by a failure or an abort still has it for a retry.
+# That holds with 'unique' too, which only keeps the restore itself from taking the uid over.
+my sub restore_pending_uid {
+    my ($reservation, $backup_identity) = @_;
+
+    my $uid = $backup_identity ? $backup_identity->{uid} : undef;
+
+    return PVE::GuestIdentity::adoptable_uid($reservation, $uid);
+}
+
 my $check_storage_access_migrate = sub {
     my ($rpcenv, $authuser, $storecfg, $storage, $node) = @_;
 
@@ -198,7 +210,8 @@ __PACKAGE__->register_method({
             unique => {
                 optional => 1,
                 type => 'boolean',
-                description => "Assign a unique random ethernet address.",
+                description => "Assign a unique random ethernet address and do not take over"
+                    . " the guest uid of the backup.",
                 requires => 'restore',
             },
             pool => {
@@ -431,7 +444,7 @@ __PACKAGE__->register_method({
 
         my $emsg = $restore ? "unable to restore CT $vmid -" : "unable to create CT $vmid -";
 
-        eval { PVE::LXC::Config->create_and_lock_config($vmid, $force) };
+        my $reservation = eval { PVE::LXC::Config->create_and_lock_config($vmid, $force) };
         die "$emsg $@" if $@;
 
         my $destroy_config_on_error = !$same_container_exists;
@@ -439,6 +452,7 @@ __PACKAGE__->register_method({
         my $code = sub {
             my $old_conf = PVE::LXC::Config->load_config($vmid);
             my $was_template;
+            my ($backup_identity, $pending_uid);
 
             my $vollist = [];
             eval {
@@ -450,6 +464,10 @@ __PACKAGE__->register_method({
                         print "recovering backed-up configuration from '$archive'\n";
                         ($orig_conf, $orig_mp_param) =
                             PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
+                        $backup_identity = PVE::LXC::Config->get_identity($orig_conf);
+                        $pending_uid = restore_pending_uid($reservation, $backup_identity);
+                        PVE::LXC::Config->record_pending_uid($vmid, $pending_uid)
+                            if defined($pending_uid);
 
                         for my $opt (keys %$orig_conf) {
                             # early check before disks are created
@@ -550,12 +568,11 @@ __PACKAGE__->register_method({
 
                 # we always have the 'create' lock so check for more than 1 entry
                 if (scalar(keys %$old_conf) > 1) {
+                    my $replacement_conf = { lock => 'create' };
+                    PVE::GuestIdentity::set_pending_uid($replacement_conf, $pending_uid);
                     # destroy old container volumes
                     PVE::LXC::destroy_lxc_container(
-                        $storage_cfg,
-                        $vmid,
-                        $old_conf,
-                        { lock => 'create' },
+                        $storage_cfg, $vmid, $old_conf, $replacement_conf,
                     );
                 }
 
@@ -597,6 +614,11 @@ __PACKAGE__->register_method({
                             $unique,
                             $skip_fw_config_restore,
                         );
+                        # the API parameters cannot carry 'meta', so it comes from the backup
+                        if ($archive eq '-') {
+                            $backup_identity = PVE::LXC::Config->get_identity($conf);
+                            $pending_uid = restore_pending_uid($reservation, $backup_identity);
+                        }
                         PVE::LXC::create_ifaces_ipams_ips($conf, $vmid) if $unique;
                         my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
                         $lxc_setup->post_restore_hook($password, $ssh_keys);
@@ -620,6 +642,8 @@ __PACKAGE__->register_method({
                 foreach my $mp (keys %$delayed_mp_param) {
                     $conf->{$mp} = $delayed_mp_param->{$mp};
                 }
+                # the template conversion writes the restored config, too
+                PVE::GuestIdentity::set_pending_uid($conf, $pending_uid);
                 # If the template flag was set, we try to convert again to template after restore
                 if ($was_template) {
                     print STDERR "Convert restored container to template...\n";
@@ -645,6 +669,12 @@ __PACKAGE__->register_method({
                 }
                 die "$emsg $err";
             }
+            if ($restore) {
+                my $uid = $backup_identity ? $backup_identity->{uid} : undef;
+                PVE::GuestIdentity::adopt_from_backup(
+                    'PVE::LXC::Config', $vmid, $unique ? undef : $uid, $reservation,
+                );
+            }
             PVE::AccessControl::add_vm_to_pool($vmid, $pool) if $pool;
         };
 
diff --git a/src/test/lifecycle_tests.pl b/src/test/lifecycle_tests.pl
index a774716..eb5b308 100755
--- a/src/test/lifecycle_tests.pl
+++ b/src/test/lifecycle_tests.pl
@@ -15,6 +15,7 @@ BEGIN {
     $INC{'PVE/VZDump.pm'} = __FILE__;
 }
 
+use Fcntl qw(:flock);
 use File::Path qw(make_path remove_tree);
 use JSON;
 use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC);
@@ -57,16 +58,25 @@ my sub write_raw_config($vmid, $raw, $node = undef) {
     file_set_contents($file, $raw);
 }
 
+my sub write_raw_vm_config($vmid, $raw) {
+    my $dir = cfs_file("nodes/$NODENAME/qemu-server");
+    make_path($dir);
+    file_set_contents("$dir/$vmid.conf", $raw);
+}
+
 my sub read_raw_config($vmid, $node = undef) {
     my $file = cfs_file(ct_config_path($vmid, $node));
     return -f $file ? file_get_contents($file) : undef;
 }
 
+my $written = {}; # VMID => the written raw configs, in the order of the writes
+
 # VMIDs whose container config still existed when their firewall config got removed
 my $vmfw_removed_reserved = {};
 
 my sub reset_configs {
     remove_tree("$WORKDIR/cfs", "$WORKDIR/rootfs");
+    $written = {};
     $vmfw_removed_reserved = {};
 }
 
@@ -86,6 +96,9 @@ my $storage_cfg = {
     },
 };
 
+# error of the cluster-wide guest identity lock, if set
+my $domain_lock_error;
+
 # reported Proxmox VE versions of the other cluster nodes
 my $node_versions = {
     'new-node' => PVE::GuestIdentity::MIN_PVE_MANAGER_VERSION,
@@ -120,6 +133,7 @@ $cluster_module->mock(
         my $file = cfs_file($path);
         make_path($file =~ s|/[^/]+$||r);
         file_set_contents($file, $raw);
+        push $written->{ ($path =~ m|/(\d+)\.conf$|)[0] }->@*, $raw;
     },
     check_vmid_unused => sub {
         my ($vmid, $noerr) = @_;
@@ -127,6 +141,30 @@ $cluster_module->mock(
         return undef if $noerr;
         die "CT $vmid already exists on node '$NODENAME'\n";
     },
+    cfs_lock_domain => sub {
+        my ($domain, $timeout, $code, @param) = @_;
+        die "unexpected lock domain '$domain'\n" if $domain ne 'guest-identity';
+        if (defined($domain_lock_error)) {
+            $@ = $domain_lock_error;
+            return undef;
+        }
+        my $res = eval { $code->(@param) };
+        return $res;
+    },
+    get_guest_config_properties => sub {
+        my ($properties) = @_;
+        my $res = {};
+        for my $file (glob("$WORKDIR/cfs/nodes/*/{lxc,qemu-server}/*.conf")) {
+            my ($vmid) = $file =~ m|/(\d+)\.conf$|;
+            for my $line (split(/\n/, file_get_contents($file))) {
+                last if $line =~ m/^\[/;
+                for my $property (@$properties) {
+                    $res->{$vmid}->{$property} = $1 if $line =~ m/^\Q$property\E:\s*(.*?)\s*$/;
+                }
+            }
+        }
+        return $res;
+    },
     remote_node_ip => sub { return '192.0.2.1' },
     get_node_pvecfg_version => sub {
         my ($node) = @_;
@@ -200,7 +238,12 @@ package PVE::LXC::Test::RPCEnvironment {
     }
 
     sub get_user { return $_[0]->{user} }
-    sub check { return 1 }
+
+    sub check($self, $user, $path, $privs, $noerr = undef) {
+        return 1 if !$self->{deny}->{$path};
+        return 0 if $noerr;
+        die "permission check failed ($path, " . join(', ', @$privs) . ")\n";
+    }
     sub check_vm_perm { return 1 }
     sub check_pool_exist { return 1 }
 
@@ -249,6 +292,7 @@ my sub run_task($code) {
 # Fake storage and container runtime
 
 my $backup_raw_config;
+my $backup_read_error;
 
 my $storage_module = Test::MockModule->new('PVE::Storage');
 $storage_module->mock(
@@ -314,6 +358,7 @@ $create_module->mock(
     archive_is_oci_format => sub { return 0 },
     recover_config => sub {
         my ($storecfg, $volid, $vmid) = @_;
+        die $backup_read_error if defined($backup_read_error);
         my $conf = PVE::LXC::Config::parse_pct_config("/lxc/$vmid.conf", $backup_raw_config);
         delete $conf->{snapshots};
         my $mp_param = {};
@@ -956,6 +1001,422 @@ subtest 'clone to another node is refused if the node drops the guest identity'
     isnt($identity->{uid}, 'existingexistingexis', 'clone has a new uid');
 };
 
+subtest 'restore takes over the guest identity with the config lock held' => sub {
+    reset_configs();
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+
+    my $real_adopt = \&PVE::GuestIdentity::adopt;
+    my $locked;
+    $identity_module->mock(
+        adopt => sub {
+            my ($class, $vmid) = @_;
+            open(my $fh, '>>', "$WORKDIR/lock/pve-config-$vmid.lock")
+                or die "open failed - $!\n";
+            $locked = !flock($fh, LOCK_EX | LOCK_NB);
+            close($fh);
+            return $real_adopt->(@_);
+        },
+    );
+    my $err = restore_ct(200);
+    $identity_module->unmock('adopt');
+
+    is($err, '', 'restore succeeds') or diag($task_log);
+    ok($locked, 'config lock is held while taking over the identity');
+    is(identity_of(200)->{uid}, 'backupbackupbackupba', 'uid of the backup is taken over');
+};
+
+subtest 'restore takes over the guest identity of the backup' => sub {
+    my $backup_meta = 'ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba';
+    my $existing_meta = 'ctime=1500000000,rtime=1500000000000,uid=existingexistingexis';
+    $now_ms = 1_700_000_000_000;
+
+    my $in_use_by_ct =
+        "guest identity: backup uid backupbackupbackupba is in use by guest 150, keeping uid ";
+
+    my $run = sub {
+        my ($name, $setup, $param, $expected_uid, $expected_rtime, $expected_log) = @_;
+
+        reset_configs();
+        $setup->();
+        my $err = restore_ct(200, $param);
+        is($err, '', "$name: restore succeeds") or diag($task_log);
+        my $identity = identity_of(200);
+        if (defined($expected_uid)) {
+            is($identity->{uid}, $expected_uid, "$name: uid");
+        } else {
+            like($identity->{uid}, qr/^[a-z2-7]{20}$/, "$name: uid is assigned");
+            isnt(
+                $identity->{uid},
+                'backupbackupbackupba',
+                "$name: uid is not the one of the backup",
+            );
+        }
+        is($identity->{rtime}, $expected_rtime, "$name: rtime");
+        like($task_log, $expected_log, "$name: result is logged");
+    };
+
+    $backup_raw_config = backup_config($backup_meta);
+    $run->(
+        'free VMID',
+        sub { },
+        {},
+        'backupbackupbackupba',
+        $now_ms,
+        qr/^guest identity: adopted uid backupbackupbackupba from the backup$/m,
+    );
+    $run->(
+        'free VMID, uid used by another container',
+        sub { write_raw_config(150, existing_config('uid=backupbackupbackupba')) },
+        {},
+        undef,
+        $now_ms,
+        qr/^\Q$in_use_by_ct\E[a-z2-7]{20}$/m,
+    );
+    $run->(
+        'free VMID, uid used by a VM',
+        sub { write_raw_vm_config(151, "memory: 512\nmeta: uid=backupbackupbackupba\n") },
+        {},
+        undef,
+        $now_ms,
+        qr/^guest identity: backup uid backupbackupbackupba is in use by guest 151, keeping uid /m,
+    );
+    $run->(
+        'free VMID, unique',
+        sub { },
+        { unique => 1 },
+        undef,
+        $now_ms,
+        qr/^guest identity: new uid [a-z2-7]{20}$/m,
+    );
+    $run->(
+        'in place, target without identity',
+        sub { write_raw_config(200, existing_config('ctime=1500000000')) },
+        { force => 1 },
+        'backupbackupbackupba',
+        $now_ms,
+        qr/^guest identity: adopted uid backupbackupbackupba from the backup$/m,
+    );
+    $run->(
+        'in place, target without identity, unique',
+        sub { write_raw_config(200, existing_config('ctime=1500000000')) },
+        { force => 1, unique => 1 },
+        undef,
+        $now_ms,
+        qr/^guest identity: new uid [a-z2-7]{20}$/m,
+    );
+    $run->(
+        'in place, target with the same identity',
+        sub {
+            write_raw_config(
+                200,
+                existing_config(
+                    'ctime=1500000000,rtime=1500000000000,uid=backupbackupbackupba'),
+            );
+        },
+        { force => 1 },
+        'backupbackupbackupba',
+        1500000000000,
+        qr/^guest identity: kept uid backupbackupbackupba$/m,
+    );
+    $run->(
+        'in place, target with the same identity, unique',
+        sub {
+            write_raw_config(
+                200,
+                existing_config(
+                    'ctime=1500000000,rtime=1500000000000,uid=backupbackupbackupba'),
+            );
+        },
+        { force => 1, unique => 1 },
+        'backupbackupbackupba',
+        1500000000000,
+        qr/^guest identity: kept uid backupbackupbackupba$/m,
+    );
+
+    $backup_raw_config = backup_config('ctime=1400000000');
+    $run->(
+        'free VMID, backup without identity',
+        sub { },
+        {},
+        undef,
+        $now_ms,
+        qr/^guest identity: new uid [a-z2-7]{20}$/m,
+    );
+    $run->(
+        'in place, target with identity, backup without identity',
+        sub { write_raw_config(200, existing_config($existing_meta)) },
+        { force => 1 },
+        'existingexistingexis',
+        1500000000000,
+        qr/^guest identity: kept uid existingexistingexis$/m,
+    );
+
+    $backup_raw_config = backup_config($backup_meta);
+    $run->(
+        'free VMID, from STDIN',
+        sub { },
+        { ostemplate => '-', rootfs => 'local:4' },
+        'backupbackupbackupba',
+        $now_ms,
+        qr/^guest identity: adopted uid backupbackupbackupba from the backup$/m,
+    );
+    $backup_raw_config = undef;
+    $run->(
+        'free VMID, from STDIN without config',
+        sub { },
+        { ostemplate => '-', rootfs => 'local:4' },
+        undef,
+        $now_ms,
+        qr/^guest identity: new uid [a-z2-7]{20}$/m,
+    );
+};
+
+subtest 'restore keeps the new guest identity if the identity lock fails' => sub {
+    reset_configs();
+    $now_ms = 1_700_000_000_000;
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+    $domain_lock_error = "cfs-lock 'domain-guest-identity' error: no quorum!\n";
+
+    my $err = restore_ct(200);
+    $domain_lock_error = undef;
+    is($err, '', 'restore succeeds') or diag($task_log);
+    my $identity = identity_of(200);
+    like($identity->{uid}, qr/^[a-z2-7]{20}$/, 'uid is assigned');
+    isnt($identity->{uid}, 'backupbackupbackupba', 'uid of the backup is not taken over');
+    my $warning =
+        "WARN: guest identity: unable to adopt backup uid backupbackupbackupba, keeping"
+        . " uid $identity->{uid} - cfs-lock 'domain-guest-identity' error: no quorum!";
+    like($task_log, qr/^\Q$warning\E$/m, 'failure is logged as warning');
+};
+
+my sub pending_uid_of($vmid) {
+    return PVE::GuestIdentity::get_pending_uid(PVE::LXC::Config->load_config($vmid));
+}
+
+subtest 'failed restore keeps the uid of the backup only as pending uid' => sub {
+    reset_configs();
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+
+    my $fake_setup_module = Test::MockModule->new('PVE::LXC::Test::Setup', no_auto => 1);
+    $fake_setup_module->mock(post_restore_hook => sub { die "post-restore hook failed\n" });
+
+    my $err = restore_ct(200);
+    like($err, qr/post-restore hook failed/, 'restore fails');
+    ok(!defined(read_raw_config(200)), 'config of the free VMID is removed');
+    ok(
+        $vmfw_removed_reserved->{200},
+        'its firewall config was removed while the VMID was still reserved',
+    );
+
+    $fake_setup_module->unmock('post_restore_hook');
+    $err = restore_ct(200);
+    is($err, '', 'retry restores to a free VMID again') or diag($task_log);
+    like(
+        $task_log,
+        qr/^guest identity: adopted uid backupbackupbackupba from the backup$/m,
+        'retry takes over the uid of the backup',
+    );
+    PVE::LXC::Config->destroy_config(200);
+
+    my $existing_meta = 'ctime=1500000000,rtime=1500000000000,uid=existingexistingexis';
+    write_raw_config(200, existing_config($existing_meta));
+    $backup_read_error = "unable to read backup\n";
+    $err = restore_ct(200, { force => 1 });
+    $backup_read_error = undef;
+    like($err, qr/unable to read backup/, 'restore fails before changing the container');
+    my $conf = PVE::LXC::Config->load_config(200);
+    is($conf->{meta}, $existing_meta, 'target keeps its identity');
+    ok(!defined($conf->{lock}), 'create lock is removed');
+
+    # a privileged backup needs Sys.Modify, which is checked after reading the backup
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba') =~
+        s/^unprivileged: 1\n//mr;
+    write_raw_config(200, existing_config('ctime=1500000000'));
+    $rpcenv->{deny}->{'/'} = 1;
+    $err = restore_ct(200, { force => 1 });
+    delete $rpcenv->{deny};
+    like($err, qr/permission check failed/, 'restore fails after reading the backup');
+    my $identity = identity_of(200);
+    like($identity->{uid}, qr/^[a-z2-7]{20}$/, 'target got an identity with the reservation');
+    isnt($identity->{uid}, 'backupbackupbackupba', 'uid of the backup is not taken over');
+    is(pending_uid_of(200), 'backupbackupbackupba', 'target has it as pending uid');
+    ok(!defined(PVE::LXC::Config->load_config(200)->{lock}), 'create lock is removed');
+
+    $err = restore_ct(200, { force => 1 });
+    is($err, '', 'retry of the same restore succeeds') or diag($task_log);
+    like(
+        $task_log,
+        qr/^guest identity: adopted uid backupbackupbackupba from the backup$/m,
+        'retry takes over the uid of the backup',
+    );
+    is(identity_of(200)->{uid}, 'backupbackupbackupba', 'stored');
+    is(pending_uid_of(200), undef, 'pending uid is removed');
+};
+
+# Restores in place over a container without identity, failing after reading the backup.
+my sub failed_restore_in_place {
+    reset_configs();
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba') =~
+        s/^unprivileged: 1\n//mr;
+    write_raw_config(200, existing_config('ctime=1500000000'));
+    $rpcenv->{deny}->{'/'} = 1;
+    my $err = restore_ct(200, { force => 1 });
+    delete $rpcenv->{deny};
+    like($err, qr/permission check failed/, 'restore fails after reading the backup');
+    is(pending_uid_of(200), 'backupbackupbackupba', 'container left behind has the pending uid');
+}
+
+subtest 'retry elsewhere, then over the container left behind' => sub {
+    failed_restore_in_place();
+    my $leftover = identity_of(200)->{uid};
+
+    my $err = restore_ct(201);
+    is($err, '', 'restore to another VMID succeeds') or diag($task_log);
+    is(identity_of(201)->{uid}, 'backupbackupbackupba', 'pending uid is not in use');
+    is(pending_uid_of(200), 'backupbackupbackupba', 'container left behind keeps it');
+
+    $err = restore_ct(200, { force => 1 });
+    is($err, '', 'restore over the container left behind succeeds') or diag($task_log);
+    like(
+        $task_log,
+        qr/: backup uid backupbackupbackupba is in use by guest 201, keeping uid $leftover$/m,
+        'uid of the backup is in use by now',
+    );
+    is(identity_of(200)->{uid}, $leftover, 'container left behind keeps its uid');
+    is(pending_uid_of(200), undef, 'pending uid is removed');
+};
+
+subtest 'using the container left behind drops its pending uid' => sub {
+    failed_restore_in_place();
+
+    my $err = update_ct(200, { description => 'used' });
+    is($err, '', 'config change of the stopped container') or diag($task_log);
+    my $dropped = "guest identity: dropping pending uid backupbackupbackupba of an unfinished"
+        . " restore - a retry now needs 'allow-identity-mismatch'";
+    like($task_log, qr/^WARN: \Q$dropped\E$/m, 'dropped');
+    is(pending_uid_of(200), undef, 'pending uid is gone');
+};
+
+subtest 'restore with unique keeps a pending uid, but never takes it over' => sub {
+    for my $retry ({ unique => 1 }, {}) {
+        my $what = $retry->{unique} ? 'retry with unique' : 'retry without unique';
+
+        reset_configs();
+        $backup_raw_config =
+            backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba') =~
+            s/^unprivileged: 1\n//mr;
+        write_raw_config(200, existing_config('ctime=1500000000'));
+        $rpcenv->{deny}->{'/'} = 1;
+        my $err = restore_ct(200, { force => 1, unique => 1 });
+        delete $rpcenv->{deny};
+        like(
+            $err,
+            qr/permission check failed/,
+            'restore with unique fails after reading the backup',
+        );
+        my $leftover = identity_of(200)->{uid};
+        is(
+            pending_uid_of(200),
+            'backupbackupbackupba',
+            'container left behind has the pending uid',
+        );
+
+        $err = restore_ct(200, { force => 1, $retry->%* });
+        is($err, '', "$what succeeds") or diag($task_log);
+        is(pending_uid_of(200), undef, "$what: pending uid is removed");
+        is(
+            identity_of(200)->{uid},
+            $retry->{unique} ? $leftover : 'backupbackupbackupba',
+            "$what: "
+                . ($retry->{unique} ? 'keeps its uid' : 'takes over the uid of the backup'),
+        );
+    }
+};
+
+subtest 'failed adoption keeps the pending uid' => sub {
+    reset_configs();
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+    $domain_lock_error = "cfs-lock 'domain-guest-identity' error: no quorum!\n";
+    my $err = restore_ct(200);
+    $domain_lock_error = undef;
+    is($err, '', 'restore succeeds') or diag($task_log);
+    like(
+        $task_log,
+        qr/unable to adopt backup uid backupbackupbackupba, keeping uid /,
+        'warning',
+    );
+    isnt(identity_of(200)->{uid}, 'backupbackupbackupba', 'container has a uid of its own');
+    is(pending_uid_of(200), 'backupbackupbackupba', 'nothing decided, pending uid stays');
+
+    $err = restore_ct(200, { force => 1 });
+    is($err, '', 'restore of the backup again is not refused') or diag($task_log);
+    is(identity_of(200)->{uid}, 'backupbackupbackupba', 'uid of the backup is taken over');
+};
+
+subtest 'config of a container left behind shows its stored identity' => sub {
+    failed_restore_in_place();
+    my $meta = PVE::LXC::Config->load_config(200)->{meta};
+
+    my $conf = PVE::API2::LXC::Config->vm_config({ node => $NODENAME, vmid => 200 });
+    is($conf->{meta}, $meta, 'config with pending changes applied: stored identity');
+    $conf = PVE::API2::LXC::Config->vm_config({ node => $NODENAME, vmid => 200, current => 1 });
+    is($conf->{meta}, $meta, 'current config: stored identity');
+
+    my $pending = PVE::API2::LXC->vm_pending({ node => $NODENAME, vmid => 200 });
+    my ($item) = grep { $_->{key} eq 'meta' } $pending->@*;
+    is($item->{value}, $meta, 'pending view: current value');
+    is($item->{pending}, 'uid=backupbackupbackupba', 'pending view: pending uid');
+};
+
+# Once a write of the config of CT 200 has the pending uid of the backup, all later writes of the
+# restore have it, so that the container keeps it whenever the restore stops. Only the adoption
+# removes it.
+subtest 'every write of a restore keeps the pending uid' => sub {
+    my $backup_meta = 'ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba';
+    my $cases = [
+        ['free VMID', undef, {}],
+        ['in place over a container without uid', existing_config('ctime=1500000000'), {}],
+        ['free VMID, from STDIN', undef, { ostemplate => '-', rootfs => 'local:4' }],
+        ['free VMID, template', undef, {}, "template: 1\n"],
+    ];
+    $storage_module->mock(volume_has_feature => sub { return 0 });
+
+    for my $case (@$cases) {
+        my ($what, $target, $param, $extra) = @$case;
+
+        reset_configs();
+        $backup_raw_config = backup_config($backup_meta) . ($extra // '');
+        write_raw_config(200, $target) if $target;
+        my $err = restore_ct(200, { $target ? (force => 1) : (), $param->%* });
+        is($err, '', "$what: restore succeeds") or diag($task_log);
+        like(
+            $task_log,
+            qr/^guest identity: adopted uid backupbackupbackupba/m,
+            "$what: adopted",
+        );
+
+        my @writes = $written->{200}->@*;
+        my $last = pop(@writes);
+        my $first = 0;
+        $first++ while $first < @writes && $writes[$first] !~ m/^\[pve:pending\]/m;
+        ok($first < @writes, "$what: pending uid is written") or next;
+        my @later = @writes[$first .. $#writes];
+        is(
+            scalar(grep { m/^\[pve:pending\]\nmeta: uid=backupbackupbackupba$/m } @later),
+            scalar(@later),
+            "$what: all later writes keep it",
+        );
+        unlike($last, qr/^\[pve:pending\]/m, "$what: adoption removes it");
+    }
+    $storage_module->unmock('volume_has_feature');
+};
+
 remove_tree($WORKDIR);
 
 done_testing();
-- 
2.47.3





  parent reply	other threads:[~2026-11-17 22:45 UTC|newest]

Thread overview: 38+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-17 22:34 [PATCH cluster/guest-common/qemu-server/container/manager/docs v2 00/36] fix #7846: guest identity (uid) and cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 01/36] pmxcfs: reject changes to the cluster ID file from user space Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 02/36] pmxcfs: generate a cluster ID on standalone nodes Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 03/36] pmxcfs: dfsm: add a callback that runs once all members are in sync Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 04/36] pmxcfs: quorum: pass the corosync membership to an optional listener Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 05/36] pmxcfs: dcdb: generate the cluster ID once the cluster is in sync Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 06/36] cluster: add helper to read the cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 07/36] pmxcfs: allow removing the cluster ID file in forced local mode Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 08/36] guest identity: add helpers for the guest uid and registration time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 09/36] abstract config: assign a guest identity and keep it on config writes Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 10/36] abstract config: let the VMID reservation return the previous state Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 11/36] guest identity: allow taking over a uid that is unused in the cluster Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 12/36] api: restore: release the VMID if a restore to an unused VMID fails Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 13/36] api: migrate, clone: refuse targets that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 14/36] fix #7846: config: add a guest identity to the 'meta' property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 15/36] restore: take over the guest uid from the backup where possible Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 16/36] api: remote migration: take over the guest uid from the source Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 17/36] api: status: return the guest uid Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 18/36] tests: remote migration: check a failed command and an early tunnel end Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 19/36] config: add read-only meta property with the creation time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 20/36] fix #7846: config: add a guest identity to the 'meta' property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 21/36] api: migrate, clone: refuse targets that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` Thomas Lamprecht [this message]
2026-11-17 22:34 ` [PATCH container v2 23/36] restore: refuse overwriting a container with another guest's backup Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 24/36] test: remote migration: check the cleanup of the target after failures Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 25/36] api: remote migration: take over the guest uid from the source Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 26/36] api: status: return the guest uid Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 27/36] api: cluster resources: add guest uid and registration time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 28/36] api: cluster status: add cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 29/36] ui: restore: allow overwriting a guest with a backup of another guest Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 30/36] ui: migrate: refuse target nodes that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 31/36] ui: guest summary: show " Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 32/36] api: migrate all: refuse targets that would drop " Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 33/36] vzdump: describe the guest identity of VMs and containers Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 34/36] pvecm: document the cluster ID and how to get a new one Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 35/36] qm: configuration: describe the read-only meta property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 36/36] pct: " Thomas Lamprecht
2026-11-18  5:57 ` superseded: [PATCH cluster/guest-common/qemu-server/container/manager/docs v2 00/36] fix #7846: guest identity (uid) and cluster ID Thomas Lamprecht

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=20261117223945.862914-23-t.lamprecht@proxmox.com \
    --to=t.lamprecht@proxmox.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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal