public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: "Michael Köppl" <m.koeppl@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH guest-common v7 05/24] add module to track previously used guest IDs
Date: Mon,  5 Oct 2026 16:47:46 +0200	[thread overview]
Message-ID: <20261005144805.825538-6-m.koeppl@proxmox.com> (raw)
In-Reply-To: <20261005144805.825538-1-m.koeppl@proxmox.com>

The /cluster/nextid API endpoint always suggests the lowest free
guest ID, so IDs of destroyed guests get handed out again. Offering
an opt-out requires recording every ID that has ever been in use
somewhere both the endpoint and the guest create and destroy paths
can reach.

Store them in /etc/pve/virtual-guest/used-guest-ids and register it as
a cfs file, so the list is kept in sync cluster-wide. IDs are stored as
"<start>-<end>" ranges and are not expanded per ID since cfs_read_file()
hands out a deep copy of the parsed data on every call, which gets
expensive on clusters that churn through many guests. Adjacent ranges
are merged on write to keep the file small. Entries that do not parse,
ranges with reversed bounds included, are skipped with a warning instead
of failing the whole read.

get_next_unused_id() returns the lowest ID at or above a given one that
is neither in use nor recorded as having been used previously.

Recording failures are non-critical and will only warn while 'unique' is
off.

Originally-by: Daniel Krambrock <krambrock@hrz.uni-marburg.de>
Originally-by: Severen Redwood <severen.redwood@sitehost.co.nz>
Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 src/Makefile       |   1 +
 src/PVE/GuestID.pm | 131 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 132 insertions(+)
 create mode 100644 src/PVE/GuestID.pm

diff --git a/src/Makefile b/src/Makefile
index 01ee0ae..161dbe5 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -9,6 +9,7 @@ install: PVE
 	install -m 0644 PVE/AbstractConfig.pm ${PERL5DIR}/PVE/
 	install -m 0644 PVE/AbstractMigrate.pm ${PERL5DIR}/PVE/
 	install -m 0644 PVE/GuestHelpers.pm ${PERL5DIR}/PVE/
+	install -m 0644 PVE/GuestID.pm ${PERL5DIR}/PVE/
 	install -m 0644 PVE/Replication.pm ${PERL5DIR}/PVE/
 	install -m 0644 PVE/ReplicationConfig.pm ${PERL5DIR}/PVE/
 	install -m 0644 PVE/ReplicationState.pm ${PERL5DIR}/PVE/
diff --git a/src/PVE/GuestID.pm b/src/PVE/GuestID.pm
new file mode 100644
index 0000000..dcffc08
--- /dev/null
+++ b/src/PVE/GuestID.pm
@@ -0,0 +1,131 @@
+package PVE::GuestID;
+
+use v5.36;
+
+use PVE::Cluster qw(
+    cfs_lock_file
+    cfs_read_file
+    cfs_register_file
+    cfs_write_file
+);
+
+my $FILENAME = 'virtual-guest/used-guest-ids';
+
+my sub parse_id_list($filename, $raw) {
+    my $ranges = [];
+
+    return $ranges if !defined($raw);
+
+    for my $line (split(/\n/, $raw)) {
+        next if $line =~ m/^\s*$/;
+
+        if ($line =~ m/^(\d+)$/) {
+            push $ranges->@*, [$1, $1];
+        } elsif ($line =~ m/^(\d+)-(\d+)$/) {
+            my ($start, $end) = ($1, $2);
+            if ($start > $end) {
+                warn "skipping reversed range in $filename: $line\n";
+                next;
+            }
+            push $ranges->@*, [$start, $end];
+        } else {
+            warn "skipping invalid entry in $filename: $line\n";
+        }
+    }
+
+    # lookup and insertion rely on the ranges being ordered by start,
+    # merging adjacent and overlapping ones is done when writing the
+    # id list.
+    return [sort { $a->[0] <=> $b->[0] } $ranges->@*];
+}
+
+my sub next_unused($ranges, $id) {
+    my $next = $id;
+    for my $range ($ranges->@*) {
+        my ($start, $end) = $range->@*;
+        next if $end < $next;
+        last if $next < $start;
+        $next = $end + 1;
+    }
+    return $next;
+}
+
+my sub format_entry($start, $last) {
+    return $start == $last ? "$start\n" : "$start-$last\n";
+}
+
+my sub write_id_list($filename, $ranges) {
+    my $output = '';
+    my ($start, $last);
+
+    for my $range ($ranges->@*) {
+        my ($curr_start, $curr_end) = $range->@*;
+
+        if (!defined($start)) {
+            ($start, $last) = ($curr_start, $curr_end);
+        } elsif ($curr_start <= $last + 1) {
+            $last = $curr_end if $curr_end > $last;
+        } else {
+            $output .= format_entry($start, $last);
+            ($start, $last) = ($curr_start, $curr_end);
+        }
+    }
+
+    $output .= format_entry($start, $last) if defined($start);
+
+    return $output;
+}
+
+# Returns the lowest ID at or above $id that is neither taken by an
+# existing guest nor recorded as used before.
+sub get_next_unused_id($id) {
+    my $ranges = cfs_read_file($FILENAME);
+    my $vmlist = PVE::Cluster::get_vmlist() // {};
+    my $existing = $vmlist->{ids} // {};
+
+    $id = next_unused($ranges, $id);
+    while (defined($existing->{$id})) {
+        $id = next_unused($ranges, $id + 1);
+    }
+
+    return $id;
+}
+
+my sub insert_id($ranges, $id) {
+    my $i = 0;
+
+    while ($i < scalar(@$ranges) && $ranges->[$i]->[1] < $id) {
+        $i++;
+    }
+
+    return 0 if $i < scalar(@$ranges) && $ranges->[$i]->[0] <= $id;
+
+    splice(@$ranges, $i, 0, [$id, $id]);
+
+    return 1;
+}
+
+sub register_used_id($id) {
+    cfs_lock_file(
+        $FILENAME,
+        10,
+        sub {
+            my $ranges = cfs_read_file($FILENAME);
+
+            return if !insert_id($ranges, $id);
+
+            cfs_write_file($FILENAME, $ranges);
+        },
+    );
+    if (my $err = $@) {
+        my $dc_conf = cfs_read_file('datacenter.cfg');
+
+        my $emsg = "unable to record guest ID $id as used";
+        die "$emsg - $err" if $dc_conf->{'next-id'}->{unique};
+        warn "$emsg - $err";
+    }
+}
+
+cfs_register_file($FILENAME, \&parse_id_list, \&write_id_list);
+
+1;
-- 
2.47.3





  parent reply	other threads:[~2026-10-05 14:50 UTC|newest]

Thread overview: 25+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-10-05 14:47 [PATCH many v7 00/24] add option to prevent suggesting previously used VMIDs Michael Köppl
2026-10-05 14:47 ` [PATCH cluster v7 01/24] cluster files: add virtual-guest/used-guest-ids Michael Köppl
2026-10-05 14:47 ` [PATCH cluster v7 02/24] datacenter config: add unique subproperty to next-id Michael Köppl
2026-10-05 14:47 ` [PATCH cluster v7 03/24] datacenter config: next-id: add enforce subproperty Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 04/24] src/makefile: order files alphabetically Michael Köppl
2026-10-05 14:47 ` Michael Köppl [this message]
2026-10-05 14:47 ` [PATCH guest-common v7 06/24] tests: add tests for used guest ID tracking Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 07/24] abstract config: register used guest ID when creating config Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 08/24] guest id: keep used ID list below the pmxcfs file size limit Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 09/24] tests: add tests for used-guest-ids max file size handling Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 10/24] guest id: optionally enforce the next-id range and uniqueness Michael Köppl
2026-10-05 14:47 ` [PATCH guest-common v7 11/24] guest id: add helper to check guest IDs against next-id enforcement Michael Köppl
2026-10-05 14:47 ` [PATCH qemu-server v7 12/24] api: record VM ID as used on destruction and remote migration Michael Köppl
2026-10-05 14:47 ` [PATCH qemu-server v7 13/24] api, remote migrate: exempt existing VMs from next-id enforcement Michael Köppl
2026-10-05 14:47 ` [PATCH container v7 14/24] api: record CT ID as used on destruction and remote migration Michael Köppl
2026-10-05 14:47 ` [PATCH container v7 15/24] api, migrate: exempt existing CTs from next-id enforcement Michael Köppl
2026-10-05 14:47 ` [PATCH manager v7 16/24] ui: guest ID selector: rename exists flag to rejected Michael Köppl
2026-10-05 14:47 ` [PATCH manager v7 17/24] ui: guest ID selector: show the error returned by nextid Michael Köppl
2026-10-05 14:47 ` [PATCH manager v7 18/24] fix #4369: api: optionally only suggest unique IDs Michael Köppl
2026-10-05 14:48 ` [PATCH manager v7 19/24] ui: dc options: rename VMID to guest ID Michael Köppl
2026-10-05 14:48 ` [PATCH manager v7 20/24] fix #4369: ui: dc options: add option for unique VM/CT IDs Michael Köppl
2026-10-05 14:48 ` [PATCH manager v7 21/24] api: nextid: reject IDs forbidden by next-id enforcement Michael Köppl
2026-10-05 14:48 ` [PATCH manager v7 22/24] ui: dc options: add option to enforce next free guest ID settings Michael Köppl
2026-10-05 14:48 ` [PATCH docs v7 23/24] pmxcfs: files: add virtual-guest/used-guest-ids Michael Köppl
2026-10-05 14:48 ` [PATCH docs v7 24/24] pvecm: next-id: document unique and enforce options Michael Köppl

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=20261005144805.825538-6-m.koeppl@proxmox.com \
    --to=m.koeppl@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