all lists on lists.proxmox.com
 help / color / mirror / Atom feed
* [PATCH test-tools 0/3] register clusters with PDM after forming them
@ 2026-11-26 17:59 Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 1/3] instance: pve client: add helper for the API certificate fingerprint Michael Köppl
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: Michael Köppl @ 2026-11-26 17:59 UTC (permalink / raw)
  To: pve-devel; +Cc: j.klocker

PDM remotes were registered before clusters were formed, so each node
became a standalone remote pinned to its original certificate. After
joining, PDM could only connect to the node that created the cluster.

This series forms clusters first and registers each cluster as a
single remote, starting all of its nodes together so they are quorate.
1/3 and 2/3 are refactors with no functional changes intended.

With PDM, max_concurrent_setups must now cover PDM plus the largest
cluster. This is checked before the setup creates anything.

Tested with setup-lifecycle.py and a local 3-node cluster setup.


test-tools:

Michael Köppl (3):
  instance: pve client: add helper for the API certificate fingerprint
  instance: move the grouping of instances by cluster into a helper
  instance: setup: register clusters with PDM after forming them

 README.md                                     |   8 +-
 proxmox-test-instance/src/api/pdm_client.rs   |  26 +-
 proxmox-test-instance/src/api/pve_client.rs   |  10 +
 .../src/instance_manager/budget.rs            |   7 +
 .../src/instance_manager/mod.rs               | 241 +++++++++++-------
 .../tests/setup-lifecycle.py                  |  77 ++++--
 6 files changed, 255 insertions(+), 114 deletions(-)


Summary over all repositories:
  6 files changed, 255 insertions(+), 114 deletions(-)

-- 
Generated by murpp 0.12.1




^ permalink raw reply	[flat|nested] 4+ messages in thread

* [PATCH test-tools 1/3] instance: pve client: add helper for the API certificate fingerprint
  2026-11-26 17:59 [PATCH test-tools 0/3] register clusters with PDM after forming them Michael Köppl
@ 2026-11-26 17:59 ` Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 2/3] instance: move the grouping of instances by cluster into a helper Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 3/3] instance: setup: register clusters with PDM after forming them Michael Köppl
  2 siblings, 0 replies; 4+ messages in thread
From: Michael Köppl @ 2026-11-26 17:59 UTC (permalink / raw)
  To: pve-devel; +Cc: j.klocker

Registering PDM remotes needs the fingerprint of every node it lists,
so move the lookup of the pve-ssl.pem certificate next to the request
that fetches it.

Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 proxmox-test-instance/src/api/pve_client.rs       | 10 ++++++++++
 proxmox-test-instance/src/instance_manager/mod.rs | 13 ++-----------
 2 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/proxmox-test-instance/src/api/pve_client.rs b/proxmox-test-instance/src/api/pve_client.rs
index 4e4c1f47..4eddcb2d 100644
--- a/proxmox-test-instance/src/api/pve_client.rs
+++ b/proxmox-test-instance/src/api/pve_client.rs
@@ -996,6 +996,16 @@ impl PveClient {
         Ok(data)
     }
 
+    /// The fingerprint of the certificate the API of `node` presents.
+    pub async fn api_fingerprint(&self, node: &str) -> Result<Option<String>, Error> {
+        let certs = self.get_certificates(node).await?;
+        let cert = certs
+            .iter()
+            .find(|c| c.filename == "pve-ssl.pem")
+            .with_context(|| format!("failed to get certificate for node {node}"))?;
+        Ok(cert.fingerprint.clone())
+    }
+
     fn client(&self) -> &Client {
         &self.client.0
     }
diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index 53dee7dd..c3fbd0d7 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -1161,17 +1161,8 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
                                     self.secret_resolver.resolve(&instance.root_password)?;
                                 let client =
                                     PveClient::new_with_creds(&url, "root@pam", &secret).await?;
-                                let certs = client.get_certificates(&instance.nodename).await?;
-                                let cert = certs
-                                    .iter()
-                                    .find(|c| c.filename == "pve-ssl.pem")
-                                    .with_context(|| {
-                                        format!(
-                                            "failed to get certificate for node {}",
-                                            instance.nodename
-                                        )
-                                    })?;
-                                instance.fingerprint = cert.fingerprint.clone();
+                                instance.fingerprint =
+                                    client.api_fingerprint(&instance.nodename).await?;
                                 pdm_client.add_remote(&instance, &secret).await?;
                                 Ok(instance.fingerprint.clone())
                             })
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [PATCH test-tools 2/3] instance: move the grouping of instances by cluster into a helper
  2026-11-26 17:59 [PATCH test-tools 0/3] register clusters with PDM after forming them Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 1/3] instance: pve client: add helper for the API certificate fingerprint Michael Köppl
@ 2026-11-26 17:59 ` Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 3/3] instance: setup: register clusters with PDM after forming them Michael Köppl
  2 siblings, 0 replies; 4+ messages in thread
From: Michael Köppl @ 2026-11-26 17:59 UTC (permalink / raw)
  To: pve-devel; +Cc: j.klocker

Registering PDM remotes needs the same grouping to start the nodes of
a cluster together.

Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 .../src/instance_manager/mod.rs               | 22 ++++++++++++-------
 1 file changed, 14 insertions(+), 8 deletions(-)

diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index c3fbd0d7..493c56ac 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -628,6 +628,19 @@ impl<'a> InstanceManager<'a> {
     where
         F: Fn(&str) -> Result<(), Error> + Sync,
     {
+        let groups = self.instance_groups(instances)?;
+
+        budget::for_each_group(
+            &groups,
+            self.config.max_concurrent_setups,
+            &self.interrupted,
+            |group| self.visit_group(group, timeout, &task),
+        )
+    }
+
+    /// Partitions `instances` into the groups they have to be powered on in, pulling in the
+    /// remaining nodes of every recorded cluster that one of them belongs to.
+    fn instance_groups(&self, instances: &[String]) -> Result<Vec<InstanceGroup>, Error> {
         let requested_nodes: HashSet<&str> = instances
             .iter()
             .filter_map(|name| self.state.instances.get(name))
@@ -652,14 +665,7 @@ impl<'a> InstanceManager<'a> {
             })
             .collect::<Result<_, Error>>()?;
 
-        let groups = budget::group_instances(&clusters, instances);
-
-        budget::for_each_group(
-            &groups,
-            self.config.max_concurrent_setups,
-            &self.interrupted,
-            |group| self.visit_group(group, timeout, &task),
-        )
+        Ok(budget::group_instances(&clusters, instances))
     }
 
     /// Stops the periodic package management services a guest runs on its own. These services
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [PATCH test-tools 3/3] instance: setup: register clusters with PDM after forming them
  2026-11-26 17:59 [PATCH test-tools 0/3] register clusters with PDM after forming them Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 1/3] instance: pve client: add helper for the API certificate fingerprint Michael Köppl
  2026-11-26 17:59 ` [PATCH test-tools 2/3] instance: move the grouping of instances by cluster into a helper Michael Köppl
@ 2026-11-26 17:59 ` Michael Köppl
  2 siblings, 0 replies; 4+ messages in thread
From: Michael Köppl @ 2026-11-26 17:59 UTC (permalink / raw)
  To: pve-devel; +Cc: j.klocker

PDM remotes were registered before any cluster was formed, so each
node became a standalone remote, pinned to the fingerprint of its
original certificate, causing PDM afterwards to fail to connect to
every node but the one that created the cluster with "certificate
verify failed".

Form clusters first and register a formed cluster as a single remote,
named after the cluster and listing all of its nodes. The nodes of a
cluster share their API tokens, so registering them one by one fails
on the second node with "Token already exists".

Start all nodes of a cluster together for the registration. A node on
its own lacks quorum, and pve-guests.service waits for quorum without
a timeout, so the node never finishes booting and the readiness check
times out. The capacity check for PDM now requires room for PDM + the
largest cluster and runs before the setup creates anything.

With --no-cluster, the planned members stay independent nodes, so
each of them is still registered as a remote of its own.

Reported-by: Jakob Klocker <j.klocker@proxmox.com>
Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 README.md                                     |   8 +-
 proxmox-test-instance/src/api/pdm_client.rs   |  26 ++-
 .../src/instance_manager/budget.rs            |   7 +
 .../src/instance_manager/mod.rs               | 210 ++++++++++++------
 .../tests/setup-lifecycle.py                  |  77 +++++--
 5 files changed, 231 insertions(+), 97 deletions(-)

diff --git a/README.md b/README.md
index bf040e14..22327054 100644
--- a/README.md
+++ b/README.md
@@ -98,9 +98,11 @@ Setup leaves guests stopped, and its offline snapshots restore in that state.
 For manual work, use `proxmox-test-instance start` to start the required entries,
 including every member before calling `create-cluster`.
 
-Registering PDM remotes requires capacity for at least two guests in
-`max_concurrent_setups`. PDM stays online while remotes are registered one at
-a time.
+Registering PDM remotes requires capacity in `max_concurrent_setups` for PDM
+plus the largest remote, i.e. two guests for standalone nodes, or one more than
+the node count of the largest cluster. PDM stays online while remotes are
+registered one at a time. A cluster is registered as a single remote, named
+after the cluster and listing all of its nodes, which are started together.
 
 After receiving a task ID, the instance tool waits up to one hour for that task,
 including the time spent on status requests. This is a CI deadline, not proof
diff --git a/proxmox-test-instance/src/api/pdm_client.rs b/proxmox-test-instance/src/api/pdm_client.rs
index 8067f37e..ee729cec 100644
--- a/proxmox-test-instance/src/api/pdm_client.rs
+++ b/proxmox-test-instance/src/api/pdm_client.rs
@@ -82,20 +82,30 @@ impl PdmClient {
         Ok(PdmClient { client })
     }
 
+    /// Registers `nodes` as one remote, using the first node to create its API token.
+    ///
+    /// The nodes of a cluster share their API tokens, so a cluster has to be registered as a
+    /// whole. Registering its nodes one by one fails on the second token.
     pub async fn add_remote(
         &self,
-        pve_instance: &TestInstance,
-        instance_pw: &str,
+        id: &str,
+        nodes: &[TestInstance],
+        root_password: &str,
     ) -> Result<(), Error> {
         let remote = Remote {
             ty: RemoteType::Pve,
-            id: pve_instance.nodename.clone(),
-            nodes: vec![PropertyString::new(NodeUrl {
-                hostname: pve_instance.ip.clone(),
-                fingerprint: pve_instance.fingerprint.clone(),
-            })],
+            id: id.to_string(),
+            nodes: nodes
+                .iter()
+                .map(|node| {
+                    PropertyString::new(NodeUrl {
+                        hostname: node.ip.clone(),
+                        fingerprint: node.fingerprint.clone(),
+                    })
+                })
+                .collect(),
             authid: Authid::root_auth_id().clone(),
-            token: instance_pw.to_string(),
+            token: root_password.to_string(),
         };
 
         self.client
diff --git a/proxmox-test-instance/src/instance_manager/budget.rs b/proxmox-test-instance/src/instance_manager/budget.rs
index c49cbb69..6e941870 100644
--- a/proxmox-test-instance/src/instance_manager/budget.rs
+++ b/proxmox-test-instance/src/instance_manager/budget.rs
@@ -17,6 +17,8 @@ use proxmox_test_common::log;
 /// The two differ when a caller names only some nodes of a cluster. The whole cluster has to come
 /// up regardless, but the task still only concerns the instances that were asked for.
 pub(super) struct InstanceGroup {
+    /// The cluster this group represents, `None` for an instance that is not part of one.
+    pub cluster: Option<String>,
     pub power_on: Vec<String>,
     pub targets: Vec<String>,
 }
@@ -70,12 +72,14 @@ pub(super) fn group_instances(
         }
 
         groups.push(InstanceGroup {
+            cluster: Some(cluster.name.clone()),
             power_on: cluster.instances.clone(),
             targets,
         });
     }
 
     groups.extend(remaining.into_iter().map(|instance| InstanceGroup {
+        cluster: None,
         power_on: vec![instance.to_string()],
         targets: vec![instance.to_string()],
     }));
@@ -354,6 +358,7 @@ mod tests {
     #[test]
     fn a_group_larger_than_the_limit_still_runs() {
         let groups = vec![InstanceGroup {
+            cluster: None,
             power_on: names(&["a", "b", "c"]),
             targets: names(&["a", "b", "c"]),
         }];
@@ -374,6 +379,7 @@ mod tests {
     fn a_failed_visit_stops_waiting_groups() {
         let groups: Vec<InstanceGroup> = (0..3)
             .map(|i| InstanceGroup {
+                cluster: None,
                 power_on: vec![format!("{i}-a"), format!("{i}-b")],
                 targets: vec![format!("{i}-a")],
             })
@@ -394,6 +400,7 @@ mod tests {
         let groups: Vec<InstanceGroup> = ["a", "b", "c"]
             .iter()
             .map(|i| InstanceGroup {
+                cluster: None,
                 power_on: names(&[i]),
                 targets: names(&[i]),
             })
diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index 493c56ac..bde72902 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -182,16 +182,17 @@ impl<'a> InstanceManager<'a> {
             }
         }
 
-        // The limit below ensures that the setup fails before creating anything rather than midway
+        // The limits below ensure that the setup fails before creating anything rather than midway
         // through the setup.
         //
         // FIXME: this might be overly strict and could possibly be removed. A host that cannot
         // hold max_concurrent_setups instances is misconfigured anyway, and a cluster slightly
         // above the limit may well still fit, in which case this rejects a plan that would have
         // worked fine.
-        if let (Some(limit), Some(clusters)) = (self.config.max_concurrent_setups, &config.clusters)
-        {
-            for cluster in clusters {
+        if let Some(limit) = self.config.max_concurrent_setups {
+            let mut largest_cluster = 0;
+
+            for cluster in config.clusters.iter().flatten() {
                 let node_count = match &cluster.nodes {
                     Some(nodes) if !nodes.is_empty() => nodes.len(),
                     _ => config
@@ -211,6 +212,17 @@ impl<'a> InstanceManager<'a> {
                         cluster.name
                     );
                 }
+
+                largest_cluster = largest_cluster.max(node_count);
+            }
+
+            // PDM keeps running while one remote at a time is registered, and a cluster is
+            // registered with all of its nodes running, see create_managed_datacenter.
+            let required = 1 + largest_cluster.max(1);
+            if config.managed_datacenter.is_some() && required > limit {
+                bail!(
+                    "managed datacenter registration needs {required} running instances, but max_concurrent_setups is {limit}"
+                );
             }
         }
 
@@ -412,6 +424,44 @@ impl<'a> InstanceManager<'a> {
 
         self.run_instance_startup(&config.instances, timeout)?;
 
+        if let Some(clusters) = &config.clusters {
+            for cluster in clusters {
+                let nodes: Vec<String> = self
+                    .cluster_instances(cluster)?
+                    .iter()
+                    .map(|instance| instance.nodename.clone())
+                    .collect();
+
+                if !no_cluster {
+                    let cluster_instances = self.instance_names_for_nodes(&nodes)?;
+
+                    // The nodes are powered off after the setup, and forming a cluster needs all
+                    // of them reachable at once.
+                    let result = self
+                        .start(&cluster_instances, &[])
+                        .and_then(|()| self.create_cluster(cluster));
+                    let cleanup = self.shutdown(&cluster_instances, &[]);
+                    finish_instance_visit(result, cleanup)?;
+                }
+
+                // Planned membership also groups peers for scripts run before manual formation.
+                self.record_cluster(TestInstanceCluster {
+                    name: cluster.name.clone(),
+                    nodes: nodes.clone(),
+                })?;
+
+                log::log_step(
+                    "Updating inventory",
+                    &format!(
+                        "adding cluster {} with nodes {}",
+                        &cluster.name,
+                        &nodes.join(", ")
+                    ),
+                );
+                write_state_to_inventory(output_path.as_deref(), &self.state)?;
+            }
+        }
+
         if let Some(managed_datacenter) = &config.managed_datacenter {
             let s = self.state.clone();
             let pdm_instance = s.instances.get(&managed_datacenter.pdm_node);
@@ -422,6 +472,8 @@ impl<'a> InstanceManager<'a> {
                     "root@pam",
                     self.secret_resolver.resolve(&pdm.root_password)?.as_str(),
                     managed_datacenter,
+                    no_cluster,
+                    timeout,
                 )?;
 
                 let remotes = managed_datacenter.remotes.clone().unwrap_or_else(|| {
@@ -452,44 +504,6 @@ impl<'a> InstanceManager<'a> {
             }
         }
 
-        if let Some(clusters) = &config.clusters {
-            for cluster in clusters {
-                let nodes: Vec<String> = self
-                    .cluster_instances(cluster)?
-                    .iter()
-                    .map(|instance| instance.nodename.clone())
-                    .collect();
-
-                if !no_cluster {
-                    let cluster_instances = self.instance_names_for_nodes(&nodes)?;
-
-                    // The nodes are powered off after the setup, and forming a cluster needs all
-                    // of them reachable at once.
-                    let result = self
-                        .start(&cluster_instances, &[])
-                        .and_then(|()| self.create_cluster(cluster));
-                    let cleanup = self.shutdown(&cluster_instances, &[]);
-                    finish_instance_visit(result, cleanup)?;
-                }
-
-                // Planned membership also groups peers for scripts run before manual formation.
-                self.record_cluster(TestInstanceCluster {
-                    name: cluster.name.clone(),
-                    nodes: nodes.clone(),
-                })?;
-
-                log::log_step(
-                    "Updating inventory",
-                    &format!(
-                        "adding cluster {} with nodes {}",
-                        &cluster.name,
-                        &nodes.join(", ")
-                    ),
-                );
-                write_state_to_inventory(output_path.as_deref(), &self.state)?;
-            }
-        }
-
         // Snapshot last so that the cluster membership is part of the snapshot and a rollback
         // restores a plan that is ready to be tested.
         for instance in &config.instances {
@@ -1120,61 +1134,49 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         userid: &str,
         password: &str,
         managed_datacenter: &ManagedDatacenter,
+        no_cluster: &bool,
+        timeout: &Option<u64>,
     ) -> Result<(), Error> {
         let runtime = proxmox_async::runtime::get_runtime();
 
         // Retain inventory keys: cloned guests can have different node names.
-        let instances: Vec<(String, TestInstance)> = match &managed_datacenter.remotes {
+        let instance_names: Vec<String> = match &managed_datacenter.remotes {
             Some(remotes) if !remotes.is_empty() => self
                 .state
                 .instances
                 .iter()
                 .filter(|(_, instance)| remotes.contains(&instance.nodename))
-                .map(|(name, instance)| (name.clone(), instance.clone()))
+                .map(|(name, _)| name.clone())
                 .collect(),
             _ => self
                 .state
                 .instances
                 .iter()
                 .filter(|(name, _)| name.as_str() != managed_datacenter.pdm_node)
-                .map(|(name, instance)| (name.clone(), instance.clone()))
+                .map(|(name, _)| name.clone())
                 .collect(),
         };
 
-        let required = if instances.is_empty() { 1 } else { 2 };
-        if let Some(limit) = self.config.max_concurrent_setups
-            && limit < required
-        {
-            bail!(
-                "managed datacenter registration needs {required} running instances, but max_concurrent_setups is {limit}"
-            );
-        }
+        let groups = self.instance_groups(&instance_names)?;
 
-        // Keep PDM available while visiting one remote at a time. Starting all remotes together
-        // would defeat the setup budget for plans that do not fit into the host's memory.
+        // Keep PDM available while visiting one remote at a time. A cluster counts as one remote
+        // and its nodes are started together, since a node on its own lacks quorum. Starting all
+        // remotes together would defeat the setup budget for plans that do not fit into memory.
         let fingerprints = self.with_started_instances(
             std::slice::from_ref(&managed_datacenter.pdm_node),
             &None,
             || {
                 let pdm_client = runtime.block_on(PdmClient::new(ip, userid, password))?;
                 let mut fingerprints = Vec::new();
-                for (name, mut instance) in instances {
-                    let fingerprint =
-                        self.with_started_instances(std::slice::from_ref(&name), &None, || {
-                            runtime.block_on(async {
-                                let url = format!("https://{}:8006", instance.ip);
-                                let secret =
-                                    self.secret_resolver.resolve(&instance.root_password)?;
-                                let client =
-                                    PveClient::new_with_creds(&url, "root@pam", &secret).await?;
-                                instance.fingerprint =
-                                    client.api_fingerprint(&instance.nodename).await?;
-                                pdm_client.add_remote(&instance, &secret).await?;
-                                Ok(instance.fingerprint.clone())
-                            })
+
+                for group in groups {
+                    let registered =
+                        self.with_started_instances(&group.power_on, timeout, || {
+                            self.register_remote_group(&pdm_client, &group, *no_cluster)
                         })?;
-                    fingerprints.push((name, fingerprint));
+                    fingerprints.extend(registered);
                 }
+
                 Ok(fingerprints)
             },
         )?;
@@ -1188,6 +1190,74 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         Ok(())
     }
 
+    /// Registers the targets of a running `group` with PDM and returns their fingerprints, keyed
+    /// by inventory name.
+    ///
+    /// The nodes of a formed cluster share their API tokens, so they have to be registered as one
+    /// remote. Without formation, the planned members are independent nodes and each one becomes
+    /// a remote of its own.
+    fn register_remote_group(
+        &self,
+        pdm_client: &PdmClient,
+        group: &InstanceGroup,
+        no_cluster: bool,
+    ) -> Result<Vec<(String, Option<String>)>, Error> {
+        let mut nodes = group
+            .targets
+            .iter()
+            .map(|name| {
+                self.get_test_instance(name)
+                    .cloned()
+                    .with_context(|| format!("unknown instance: '{name}'"))
+            })
+            .collect::<Result<Vec<_>, Error>>()?;
+
+        match &group.cluster {
+            Some(cluster) if !no_cluster => {
+                self.register_remote(pdm_client, cluster, &mut nodes)?
+            }
+            _ => {
+                for node in &mut nodes {
+                    let id = node.nodename.clone();
+                    self.register_remote(pdm_client, &id, std::slice::from_mut(node))?;
+                }
+            }
+        }
+
+        Ok(group
+            .targets
+            .iter()
+            .cloned()
+            .zip(nodes.into_iter().map(|node| node.fingerprint))
+            .collect())
+    }
+
+    /// Registers `nodes` as the PDM remote `id`, after filling in their API fingerprints.
+    ///
+    /// PDM creates the remote's API token through the first node, so that node's root password is
+    /// the one handed over.
+    fn register_remote(
+        &self,
+        pdm_client: &PdmClient,
+        id: &str,
+        nodes: &mut [TestInstance],
+    ) -> Result<(), Error> {
+        let runtime = proxmox_async::runtime::get_runtime();
+
+        runtime.block_on(async {
+            for node in nodes.iter_mut() {
+                let url = format!("https://{}:8006", node.ip);
+                let secret = self.secret_resolver.resolve(&node.root_password)?;
+                let client = PveClient::new_with_creds(&url, "root@pam", &secret).await?;
+                node.fingerprint = client.api_fingerprint(&node.nodename).await?;
+            }
+
+            let first = nodes.first().context("a remote needs at least one node")?;
+            let secret = self.secret_resolver.resolve(&first.root_password)?;
+            pdm_client.add_remote(id, nodes, &secret).await
+        })
+    }
+
     pub fn rollback(
         &mut self,
         snapshot_name: &str,
diff --git a/proxmox-test-instance/tests/setup-lifecycle.py b/proxmox-test-instance/tests/setup-lifecycle.py
index ccbc4b41..18b879fe 100644
--- a/proxmox-test-instance/tests/setup-lifecycle.py
+++ b/proxmox-test-instance/tests/setup-lifecycle.py
@@ -24,7 +24,7 @@ subprocess.run([
     "-keyout", str(root / "key"), "-out", str(root / "cert"),
     "-days", "1", "-subj", "/CN=localhost",
 ], check=True, capture_output=True)
-requests, running, allocated, formed, registered = [], set(), set(), set(), set()
+requests, running, allocated, formed, registered = [], set(), set(), set(), {}
 snapshots = {}
 mode = ""
 peak = 0
@@ -71,18 +71,30 @@ class Handler(http.server.BaseHTTPRequestHandler):
                 data = [{"filename": "pve-ssl.pem", "subject": "test", "issuer": "test",
                          "san": [], "public-key-type": "rsa", "fingerprint": "AA:BB"}]
             elif self.path.endswith("/remotes/remote"):
-                remote = 6000 if params["id"] == "node-a" else 6001
-                assert remote in running, ("remote stopped during registration", requests)
-                assert "fingerprint=AA:BB" in params["nodes"][0], params
+                members = []
+                for node in params["nodes"]:
+                    assert "fingerprint=AA:BB" in node, params
+                    ip = node.split(",")[0].removeprefix("hostname=")
+                    members.append(5998 + int(ip.split(".")[-1]))
+                assert set(members) <= running, ("remote stopped during registration", requests)
                 if mode == "registration-failure":
                     failure = "registration denied"
                 else:
-                    registered.add(remote)
+                    registered[params["id"]] = sorted(members)
             elif self.path.endswith("/cluster/config"):
                 formed.add(vmid)
+            elif self.path.endswith("/cluster/config/join"):
+                if self.command == "POST":
+                    formed.add(vmid)
+                else:
+                    data = {"config_digest": "mock", "preferred_node": "node-a", "totem": {},
+                            "nodelist": [{"name": "node-a", "pve_addr": "127.0.0.2",
+                                          "pve_fp": "AA:BB", "quorum_votes": 1}]}
+            elif self.path.endswith("/cluster/resources"):
+                data = []
             elif self.path.endswith("/cluster/status"):
                 data = [{"id": "cluster", "name": "cluster", "type": "cluster",
-                         "nodes": 1, "quorate": 1}]
+                         "nodes": len(formed), "quorate": 1}]
             else:
                 self.send_error(404)
                 return
@@ -195,22 +207,26 @@ def inventory(capacity=False):
     return path
 
 
-def plan(pdm=False):
+def plan(pdm=False, cluster_nodes=None):
     instances = []
     for i, name in enumerate(["a", "b", "pdm"] if pdm else ["a"]):
         instances.append(f'''(name: "{name}", kind: VmClone(source: {100 + i},
         ip: "127.0.0.{2 + i}", nodename: "node-{name}", type: "{"pdm" if name == "pdm" else "pve"}",
         root_password: Inline("mock")))''')
-    extra = ('managed_datacenter: Some((pdm_node:"pdm",remotes:Some(["node-a","node-b"])))'
-             if pdm else 'clusters: Some([(name:"cluster",nodes:Some(["node-a"]))])')
+    extra = []
+    if pdm:
+        extra.append('managed_datacenter: Some((pdm_node:"pdm",remotes:Some(["node-a","node-b"])))')
+    if cluster_nodes:
+        nodes = ",".join(f'"{node}"' for node in cluster_nodes)
+        extra.append(f'clusters: Some([(name:"cluster",nodes:Some([{nodes}]))])')
     path = root / f"{mode}-plan.ron"
-    path.write_text('(instances:[' + ','.join(instances) + '],' + extra + ')')
+    path.write_text('(instances:[' + ','.join(instances) + '],' + ','.join(extra) + ')')
     return path
 
 
-def invoke(label, args, success, local_env=None):
+def invoke(label, args, success, local_env=None, timeout=30):
     result = subprocess.run([binary, *map(str, args), "--config", str(config)],
-                            env=local_env or env, capture_output=True, text=True, timeout=30)
+                            env=local_env or env, capture_output=True, text=True, timeout=timeout)
     text = (f"exit: {result.returncode}\nrequests: {requests}\nrunning: {sorted(running)}\n"
             f"peak: {peak}\n{result.stdout}\n{result.stderr}")
     (root / f"{label}.log").write_text(text)
@@ -254,16 +270,45 @@ try:
         result = invoke(label, ["setup", config_plan, inv], label == "registration")
         assert not running and peak <= (1 if label == "registration-limit" else 2)
         if label == "registration":
-            assert registered == {6000, 6001}
+            assert registered == {"node-a": [6000], "node-b": [6001]}
             assert inv.read_text().count('fingerprint: Some("AA:BB")') == 2
+        elif label == "registration-limit":
+            assert "needs 2 running instances" in result.stderr
+            assert not allocated and not inv.exists()
         else:
             assert 'plan_digest: ""' in inv.read_text()
             assert not snapshots
-            if label == "registration-limit":
-                assert "needs 2 running instances" in result.stderr
+
+    # Cluster nodes must be registered together while all are running, since they share their API
+    # tokens and otherwise they are not quorate.
+    reset("cluster-registration", 3)
+    config_plan = plan(True, ["node-a", "node-b"])
+    inv = root / "cluster-registration-inventory.ron"
+
+    invoke("cluster-registration", ["setup", config_plan, inv], True, timeout=60)
+    assert not running and peak <= 3
+    assert registered == {"cluster": [6000, 6001]}
+    assert inv.read_text().count('fingerprint: Some("AA:BB")') == 2
+    assert snapshots == {6000: True, 6001: True, 6002: False}
+
+    # Without formation, the planned members are independent nodes and each one is a remote.
+    reset("no-cluster-registration", 3)
+    config_plan = plan(True, ["node-a", "node-b"])
+    inv = root / "no-cluster-registration-inventory.ron"
+    invoke("no-cluster-registration", ["setup", config_plan, inv, "--no-cluster"], True)
+    assert not running and peak <= 3 and not formed
+    assert registered == {"node-a": [6000], "node-b": [6001]}
+
+    # PDM's share of the capacity for registering a cluster is checked before anything is created.
+    reset("cluster-registration-limit", 2)
+    config_plan = plan(True, ["node-a", "node-b"])
+    inv = root / "cluster-registration-limit-inventory.ron"
+    result = invoke("cluster-registration-limit", ["setup", config_plan, inv], False)
+    assert "needs 3 running instances" in result.stderr
+    assert not allocated and not inv.exists()
 
     reset("reuse")
-    config_plan = plan()
+    config_plan = plan(cluster_nodes=["node-a"])
     inv = root / "reuse-inventory.ron"
     invoke("unclustered-setup", ["setup", config_plan, inv, "--no-cluster"], True)
     assert snapshots == {6000: False} and not running
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2026-11-26 18:00 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-26 17:59 [PATCH test-tools 0/3] register clusters with PDM after forming them Michael Köppl
2026-11-26 17:59 ` [PATCH test-tools 1/3] instance: pve client: add helper for the API certificate fingerprint Michael Köppl
2026-11-26 17:59 ` [PATCH test-tools 2/3] instance: move the grouping of instances by cluster into a helper Michael Köppl
2026-11-26 17:59 ` [PATCH test-tools 3/3] instance: setup: register clusters with PDM after forming them Michael Köppl

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.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal