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 test-tools 5/8] instance: cli: run a script once for a whole cluster
Date: Tue,  1 Dec 2026 15:58:14 +0100	[thread overview]
Message-ID: <20261201145817.894414-6-m.koeppl@proxmox.com> (raw)
In-Reply-To: <20261201145817.894414-1-m.koeppl@proxmox.com>

Clusters formed with `setup --no-cluster` and `create-cluster` do not
run post_cluster hooks, so there was no way to run a script that needs
the whole cluster against them.

Add `run-script --cluster NAME`, which runs the script once with the
same $CONFIG_PATH as post_cluster hooks, targeting all nodes of the
cluster, ordered by IP. Unlike per-instance runs, which keep at most
max_concurrent_setups instances up, all nodes are powered on together.
Nodes that were not running before are shut down again afterwards.

Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 README.md                                     |   9 ++
 proxmox-test-instance/src/cli.rs              |  20 ++-
 .../src/instance_manager/mod.rs               | 118 ++++++++++++++++--
 3 files changed, 135 insertions(+), 12 deletions(-)

diff --git a/README.md b/README.md
index d54095aa..fe727133 100644
--- a/README.md
+++ b/README.md
@@ -245,6 +245,15 @@ address. The first node is the one the cluster was created on.
 }
 ```
 
+Clusters formed manually (`setup --no-cluster` followed by `create-cluster`) do not run
+`post_cluster` hooks. Once such a cluster is formed, `run-script --cluster` runs a script once for
+it, with the same `$CONFIG_PATH`. As with other `run-script` calls, the script path is relative to
+the current directory:
+
+```shell
+proxmox-test-instance run-script --cluster pvecluster inventory.ron ./scripts/my-cluster-hook.sh
+```
+
 # proxmox-test-runner
 
 ## TL;DR
diff --git a/proxmox-test-instance/src/cli.rs b/proxmox-test-instance/src/cli.rs
index 1aca340a..5745c9fd 100644
--- a/proxmox-test-instance/src/cli.rs
+++ b/proxmox-test-instance/src/cli.rs
@@ -157,6 +157,9 @@ OPTIONS:
   --config     PATH     Provide a custom config file
   --include    INSTANCE Include this instance. Can be set multiple times.
   --exclude    INSTANCE Exclude this instance. Can be set multiple times.
+  --cluster    NAME     Run the script once for this cluster instead, with all
+                        of its nodes in $CONFIG_PATH. Cannot be combined with
+                        --include or --exclude.
 
 If neither --include nor --exclude are provided, the script
 is executed against ALL instances from the inventory.
@@ -164,7 +167,8 @@ If both are provided, excluded instances are subtracted from included ones.
 
 ARGS:
   <INVENTORY>           Inventory of test instances
-  <SCRIPT>              Script to run for each selected instance
+  <SCRIPT>              Script to run for each selected instance, or once for
+                        the cluster
 ";
 
 const CREATE_CLUSTER_HELP: &str = "\
@@ -447,6 +451,7 @@ impl Cli {
             Some("run-script") => Command::RunScript(RunScriptArgs {
                 secrets: args.opt_value_from_os_str("--secrets", parse_path)?,
                 config: args.opt_value_from_os_str("--config", parse_path)?,
+                cluster: args.opt_value_from_str("--cluster")?,
                 include: args.values_from_str("--include")?,
                 exclude: args.values_from_str("--exclude")?,
                 inventory: args.free_from_os_str(parse_path)?,
@@ -591,6 +596,9 @@ pub struct RunScriptArgs {
     pub include: Vec<String>,
     /// Don't run the script on these instances
     pub exclude: Vec<String>,
+
+    /// Run the script once for this cluster instead of on each instance.
+    pub cluster: Option<String>,
 }
 
 #[derive(Clone, Debug)]
@@ -905,10 +913,18 @@ impl Command {
         secret_resolver: &SecretResolver,
         interrupted: Arc<AtomicBool>,
     ) -> Result<(), Error> {
+        if args.cluster.is_some() && (!args.include.is_empty() || !args.exclude.is_empty()) {
+            bail!("--cluster cannot be combined with --include or --exclude");
+        }
+
         let inventory = TestInventory::load(&args.inventory)?;
         let mut manager = InstanceManager::new(testrunner_config, secret_resolver, interrupted)?;
         manager.set_state(inventory);
-        manager.run_script(&args.script, &args.include, &args.exclude)?;
+
+        match &args.cluster {
+            Some(cluster) => manager.run_cluster_script(&args.script, cluster)?,
+            None => manager.run_script(&args.script, &args.include, &args.exclude)?,
+        }
 
         Ok(())
     }
diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index 0c23eca9..f4cc9085 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -1026,6 +1026,37 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         })
     }
 
+    /// Runs a script once for a cluster from the inventory, powering on its nodes that are not
+    /// running and shutting them down again afterwards.
+    pub fn run_cluster_script(&self, script: &str, cluster: &str) -> Result<(), Error> {
+        let recorded = self
+            .state
+            .clusters
+            .as_deref()
+            .unwrap_or_default()
+            .iter()
+            .find(|recorded| recorded.name == cluster)
+            .with_context(|| format!("no cluster '{cluster}' in inventory"))?;
+
+        let members = self.cluster_instances(&Cluster {
+            name: recorded.name.clone(),
+            nodes: Some(recorded.nodes.clone()),
+            post_cluster: Vec::new(),
+        })?;
+        let instances = self.instance_names_for_nodes(&recorded.nodes)?;
+
+        self.with_started_instances(&instances, &None, || {
+            for instance in &instances {
+                // Nodes may just have been booted, so overdue package timers could hold the apt
+                // lock the script needs.
+                self.disable_package_management(instance)?;
+            }
+
+            let data = self.cluster_hook_data(&recorded.name, &members)?;
+            self.run_command(script, None, &format!("cluster {}", recorded.name), &data)
+        })
+    }
+
     /// Form the cluster and return its actual membership for the inventory.
     pub fn create_cluster(&mut self, cluster: &Cluster) -> Result<TestInstanceCluster, Error> {
         let runtime = proxmox_async::runtime::get_runtime();
@@ -1148,10 +1179,25 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
             self.disable_package_management(instance)?;
         }
 
-        let runtime_config = ClusterHookRuntimeConfig {
+        let data = self.cluster_hook_data(&cluster.name, members)?;
+        let target = format!("cluster {}", cluster.name);
+
+        for hook in &cluster.post_cluster {
+            self.run_command(&hook.command(plan_dir)?, None, &target, &data)?;
+        }
+        Ok(())
+    }
+
+    /// Returns the `$CONFIG_PATH` contents of a script run once for a whole cluster.
+    fn cluster_hook_data(
+        &self,
+        cluster: &str,
+        members: &[TestInstance],
+    ) -> Result<serde_json::Value, Error> {
+        Ok(serde_json::to_value(ClusterHookRuntimeConfig {
             ssh_private_keyfile: self.config.ssh_private_keyfile.clone(),
             ssh_user: "root".into(),
-            cluster: cluster.name.clone(),
+            cluster: cluster.to_string(),
             nodes: members
                 .iter()
                 .map(|member| ClusterHookNode {
@@ -1159,14 +1205,7 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
                     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.
@@ -1934,4 +1973,63 @@ mod tests {
                 .is_err()
         );
     }
+
+    #[test]
+    fn cluster_script_uses_recorded_members_in_ip_order() {
+        let config: Config = ron::from_str(
+            r#"Config(
+            test_host_url: "https://127.0.0.1:1", test_host_userid: "root@pam!test",
+            test_host_token: Some("test"), control_ip: "127.0.0.1",
+            default_storage: "local", default_bridge: "ttvnet", vmid_range: (6000, 6010),
+            ssh_private_keyfile: "/dev/null", ssh_public_keyfile: "/dev/null",
+        )"#,
+        )
+        .unwrap();
+        let resolver = SecretResolver::default();
+        let mut manager =
+            InstanceManager::new(&config, &resolver, Arc::new(AtomicBool::new(false))).unwrap();
+        // The IPs sort differently as strings, so this also checks that members are ordered by
+        // address, as the README promises.
+        manager.state.instances = ron::from_str(r#"{
+        "first": (nodename: "pve1", virt: Qemu(vmid: 6000), ip: "10.0.0.10", root_password: Inline("test"), ssh_private_keyfile: "/dev/null", additional_disks: []),
+        "second": (nodename: "pve2", virt: Qemu(vmid: 6001), ip: "10.0.0.9", root_password: Inline("test"), ssh_private_keyfile: "/dev/null", additional_disks: []),
+    }"#).unwrap();
+        manager.state.clusters = Some(vec![
+            TestInstanceCluster {
+                name: "pvecluster".into(),
+                nodes: vec!["pve1".into(), "pve2".into()],
+            },
+            TestInstanceCluster {
+                name: "stale".into(),
+                nodes: vec!["pve3".into()],
+            },
+        ]);
+
+        // No test host required, both fail before any node is powered on.
+        let error = manager.run_cluster_script("true", "missing").unwrap_err();
+        assert!(
+            error
+                .to_string()
+                .contains("no cluster 'missing' in inventory")
+        );
+        let error = manager.run_cluster_script("true", "stale").unwrap_err();
+        assert!(error.to_string().contains("not in the inventory: pve3"));
+
+        let members = manager
+            .cluster_instances(&Cluster {
+                name: "pvecluster".into(),
+                nodes: Some(vec!["pve1".into(), "pve2".into()]),
+                post_cluster: Vec::new(),
+            })
+            .unwrap();
+        let data = manager.cluster_hook_data("pvecluster", &members).unwrap();
+        assert_eq!(data["cluster"], "pvecluster");
+        assert_eq!(
+            data["nodes"],
+            serde_json::json!([
+                { "name": "pve2", "host": "10.0.0.9" },
+                { "name": "pve1", "host": "10.0.0.10" },
+            ])
+        );
+    }
 }
-- 
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 ` [PATCH test-tools 4/8] instance: add hooks that run once a cluster is formed Michael Köppl
2026-12-01 14:58 ` Michael Köppl [this message]
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-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