all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: "Michael Köppl" <m.koeppl@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH test-tools 4/8] instance: add hooks that run once a cluster is formed
Date: Tue,  1 Dec 2026 15:58:13 +0100	[thread overview]
Message-ID: <20261201145817.894414-5-m.koeppl@proxmox.com> (raw)
In-Reply-To: <20261201145817.894414-1-m.koeppl@proxmox.com>

Some setup steps need the formed cluster with all of its nodes at once.
Setting up Ceph, for example, needs a monitor on every node and creates
its pools only once. Setup hooks cannot do this. They run before the
cluster is formed, once per instance, and only know about that one
instance.

Clusters in plans can now have 'post_cluster' hooks. They run once for
the whole cluster after it has been formed, while all of its nodes are
still running, so that their result is part of the 'post-setup'
snapshot. Their $CONFIG_PATH lists all nodes, ordered by IP address, the
first being the one the cluster was created on.

Scripts messages now name their target without calling it an instance,
since it can also be a cluster.

Plans without cluster hooks serialize as before, so their setup digest
stays the same and not rebuilds are necessary.

Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 README.md                                     | 35 ++++++-
 proxmox-test-instance/src/cli.rs              |  1 +
 proxmox-test-instance/src/config.rs           |  5 +-
 .../src/instance_manager/mod.rs               | 94 ++++++++++++++++---
 4 files changed, 121 insertions(+), 14 deletions(-)

diff --git a/README.md b/README.md
index 8bca2818..d54095aa 100644
--- a/README.md
+++ b/README.md
@@ -84,7 +84,7 @@ Depending on the plan, this will
   - Start the PVE/PBS autoinstaller from a provided ISO
   - Wait for the installation to finish
   - Run any post-setup scripts/playbooks
-  - Form configured clusters and shut down the guests
+  - Form configured clusters, run their post-cluster hooks, and shut down the guests
   - Create an offline snapshot called `post-setup`
   - Write the current inventory state to the given inventory file, which can
     be used by `proxmox-test-runner`
@@ -212,6 +212,39 @@ Scripts are executed on the same host where `proxmox-test-instance`
 is executed. SSH may be used to perform any setup steps on the instance itself.
 The builtin hooks in `scripts/` serve as examples.
 
+### Cluster hooks
+
+The `post_cluster` hooks of a cluster run once the cluster has been formed, while all of its nodes
+are running. They take the same `Builtin(...)` and `File(...)` forms as setup hooks, but run once
+for the whole cluster rather than once per node. They do not run with `setup --no-cluster`.
+
+```ron
+clusters: [
+    Cluster(
+        name: "pvecluster",
+        nodes: ["pve1", "pve2", "pve3"],
+        post_cluster: [
+            File("scripts/my-cluster-hook.sh"),
+        ],
+    ),
+],
+```
+
+Instead of a single host, their `$CONFIG_PATH` lists all nodes of the cluster, ordered by IP
+address. The first node is the one the cluster was created on.
+```json
+{
+  "ssh_private_keyfile": "/home/user/.ssh/id_rsa",
+  "ssh_user": "root",
+  "cluster": "pvecluster",
+  "nodes": [
+    { "name": "pve1", "host": "172.16.0.100" },
+    { "name": "pve2", "host": "172.16.0.101" },
+    { "name": "pve3", "host": "172.16.0.102" }
+  ]
+}
+```
+
 # proxmox-test-runner
 
 ## TL;DR
diff --git a/proxmox-test-instance/src/cli.rs b/proxmox-test-instance/src/cli.rs
index 1033f5dd..1aca340a 100644
--- a/proxmox-test-instance/src/cli.rs
+++ b/proxmox-test-instance/src/cli.rs
@@ -928,6 +928,7 @@ impl Command {
             name: args.cluster_name.clone(),
             // TODO: make this configurable
             nodes: None,
+            post_cluster: Vec::new(),
         };
         let created = manager.create_cluster(&cluster)?;
         manager.record_cluster(created)?;
diff --git a/proxmox-test-instance/src/config.rs b/proxmox-test-instance/src/config.rs
index 7842ae1b..59f2b6f2 100644
--- a/proxmox-test-instance/src/config.rs
+++ b/proxmox-test-instance/src/config.rs
@@ -37,7 +37,7 @@ pub struct SetupInstance {
 /// A script to run on the host, connecting to the test instance at some pre-defined lifecycle
 /// stage. Its command line names the script first, followed by the arguments, which are passed
 /// through the shell.
-#[derive(Clone, Debug, Deserialize, Serialize)]
+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
 pub enum Hook {
     /// A script shipped with the deb package, named without its `.sh` suffix.
     Builtin(String),
@@ -134,6 +134,9 @@ fn iso_type_default() -> String {
 pub struct Cluster {
     pub name: String,
     pub nodes: Option<Vec<String>>,
+    /// Hooks run once for the whole cluster after the cluster has been formed.
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    pub post_cluster: Vec<Hook>,
 }
 
 #[derive(Clone, Debug, Deserialize, Serialize)]
diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index fceec04e..0c23eca9 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -62,6 +62,21 @@ struct HookRuntimeConfig {
     ssh_user: String,
 }
 
+/// The `$CONFIG_PATH` of a cluster hook.
+#[derive(Serialize)]
+struct ClusterHookRuntimeConfig {
+    ssh_private_keyfile: String,
+    ssh_user: String,
+    cluster: String,
+    nodes: Vec<ClusterHookNode>,
+}
+
+#[derive(Serialize)]
+struct ClusterHookNode {
+    name: String,
+    host: String,
+}
+
 pub struct InstanceManager<'a> {
     config: &'a Config,
     secret_resolver: &'a SecretResolver,
@@ -455,8 +470,8 @@ impl<'a> InstanceManager<'a> {
 
         if let Some(clusters) = &config.clusters {
             for cluster in clusters {
-                let nodes: Vec<String> = self
-                    .cluster_instances(cluster)?
+                let members = self.cluster_instances(cluster)?;
+                let nodes: Vec<String> = members
                     .iter()
                     .map(|instance| instance.nodename.clone())
                     .collect();
@@ -468,7 +483,10 @@ impl<'a> InstanceManager<'a> {
                     // of them reachable at once.
                     let result = self
                         .start(&cluster_instances, &[])
-                        .and_then(|()| self.create_cluster(cluster));
+                        .and_then(|()| self.create_cluster(cluster))
+                        .and_then(|_| {
+                            self.run_cluster_hooks(plan_dir, cluster, &members, &cluster_instances)
+                        });
                     let cleanup = self.shutdown(&cluster_instances, &[]);
                     finish_instance_visit(result, cleanup)?;
                 }
@@ -922,9 +940,19 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
             ssh_user: "root".into(),
         };
 
+        self.run_command(cmd, label, instance, &serde_json::to_value(runtime_config)?)
+    }
+
+    /// Runs `cmd` with `data` in `$CONFIG_PATH`. `target` names what it runs against in the log.
+    fn run_command(
+        &self,
+        cmd: &str,
+        label: Option<&str>,
+        target: &str,
+        data: &serde_json::Value,
+    ) -> Result<(), Error> {
         let label = label.unwrap_or(cmd);
-        let data = serde_json::to_value(runtime_config)?;
-        log::log_step("Running script", &format!("'{label}' on '{instance}'"));
+        log::log_step("Running script", &format!("'{label}' on '{target}'"));
 
         // Groups run concurrently, so the streamed lines of half a dozen instances are interleaved.
         // Keep a copy to report with a failure, since by then the cause has scrolled far out of
@@ -932,14 +960,14 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         let output = Arc::new(Mutex::new(Vec::new()));
 
         let stdout_output = Arc::clone(&output);
-        let stdout_name = instance.to_string();
+        let stdout_name = target.to_string();
         let stdout_cb = move |s: String| {
             log::log_command_output(&format!("[{stdout_name}] {s}"));
             stdout_output.lock().unwrap().push(s);
         };
 
         let stderr_output = Arc::clone(&output);
-        let stderr_name = instance.to_string();
+        let stderr_name = target.to_string();
         let stderr_cb = move |s: String| {
             log::log_command_output(&format!("[{stderr_name}] {s}"));
             stderr_output.lock().unwrap().push(s);
@@ -948,7 +976,7 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         let status = run_with_timeout(
             cmd,
             None,
-            Some(&data),
+            Some(data),
             &[],
             &self.interrupted,
             stdout_cb,
@@ -957,18 +985,18 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
 
         match status {
             RunStatus::Timeout(t) => {
-                bail!("'{label}' for instance '{instance}' timed out after {t} seconds")
+                bail!("'{label}' for '{target}' timed out after {t} seconds")
             }
-            RunStatus::Interrupted => bail!("'{label}' for instance '{instance}' was interrupted"),
+            RunStatus::Interrupted => bail!("'{label}' for '{target}' was interrupted"),
             RunStatus::Success => {
-                log::log(format!("'{label}' for instance '{instance}' finished"));
+                log::log(format!("'{label}' for '{target}' finished"));
             }
             RunStatus::Failure(s) => {
                 let output = output.lock().unwrap();
                 let tail = &output[output.len().saturating_sub(FAILED_SCRIPT_LOG_LINES)..];
 
                 bail!(
-                    "'{label}' for instance '{instance}' failed with exit status {s}\n{}",
+                    "'{label}' for '{target}' failed with exit status {s}\n{}",
                     tail.join("\n")
                 )
             }
@@ -1102,6 +1130,45 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         })
     }
 
+    /// Runs the hooks of `cluster` once for all its members, which must be running.
+    fn run_cluster_hooks(
+        &self,
+        plan_dir: &Path,
+        cluster: &Cluster,
+        members: &[TestInstance],
+        instances: &[String],
+    ) -> Result<(), Error> {
+        if cluster.post_cluster.is_empty() {
+            return Ok(());
+        }
+
+        for instance in instances {
+            // Nodes were just booted, so overdue package timers could hold the apt lock a hook
+            // needs.
+            self.disable_package_management(instance)?;
+        }
+
+        let runtime_config = ClusterHookRuntimeConfig {
+            ssh_private_keyfile: self.config.ssh_private_keyfile.clone(),
+            ssh_user: "root".into(),
+            cluster: cluster.name.clone(),
+            nodes: members
+                .iter()
+                .map(|member| ClusterHookNode {
+                    name: member.nodename.clone(),
+                    host: member.ip.clone(),
+                })
+                .collect(),
+        };
+        let data = serde_json::to_value(runtime_config)?;
+        let target = format!("cluster {}", cluster.name);
+
+        for hook in &cluster.post_cluster {
+            self.run_command(&hook.command(plan_dir)?, None, &target, &data)?;
+        }
+        Ok(())
+    }
+
     /// Record disjoint topology, or confirm an identical planned cluster without duplicating it.
     pub fn record_cluster(&mut self, cluster: TestInstanceCluster) -> Result<(), Error> {
         let clusters = self.state.clusters.get_or_insert_default();
@@ -1734,6 +1801,7 @@ mod tests {
         let default = Cluster {
             name: "test".into(),
             nodes: None,
+            post_cluster: Vec::new(),
         };
         assert!(
             manager
@@ -1756,6 +1824,7 @@ mod tests {
                 .cluster_instances(&Cluster {
                     name: "test".into(),
                     nodes: Some(vec!["missing".into()]),
+                    post_cluster: Vec::new(),
                 })
                 .unwrap_err()
                 .to_string()
@@ -1811,6 +1880,7 @@ mod tests {
             .create_cluster(&Cluster {
                 name: "manual".into(),
                 nodes: None,
+                post_cluster: Vec::new(),
             })
             .unwrap_err();
         // Attempting authentication would instead fail parsing the deliberately invalid address.
-- 
2.47.3





  parent reply	other threads:[~2026-12-01 14:58 UTC|newest]

Thread overview: 9+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-01 14:58 [PATCH e2e-tests/test-tools 0/8] instance: rework hooks and set up Ceph as a cluster hook Michael Köppl
2026-12-01 14:58 ` [PATCH test-tools 1/8] readme: drop token fields from the hook config example Michael Köppl
2026-12-01 14:58 ` [PATCH test-tools 2/8] instance: ship generic hook scripts Michael Köppl
2026-12-01 14:58 ` [PATCH test-tools 3/8] instance: distinguish builtin hooks from hook files Michael Köppl
2026-12-01 14:58 ` Michael Köppl [this message]
2026-12-01 14:58 ` [PATCH test-tools 5/8] instance: cli: run a script once for a whole cluster Michael Köppl
2026-12-01 14:58 ` [PATCH test-tools 6/8] instance: add a builtin hook to set up a Ceph cluster Michael Köppl
2026-12-01 14:58 ` [PATCH e2e-tests 7/8] plans: use the hook scripts shipped with proxmox-test-instance Michael Köppl
2026-12-01 14:58 ` [PATCH e2e-tests 8/8] scripts: drop the scripts now shipped by proxmox-test-instance 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=20261201145817.894414-5-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 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