From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 677011FF09F for ; Tue, 01 Dec 2026 15:58:35 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id C467D216DB; Tue, 01 Dec 2026 15:58:25 +0100 (CET) From: =?UTF-8?q?Michael=20K=C3=B6ppl?= 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 Message-ID: <20261201145817.894414-5-m.koeppl@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201145817.894414-1-m.koeppl@proxmox.com> References: <20261201145817.894414-1-m.koeppl@proxmox.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796137099419 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.170 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: CLTYOSJQP3YPZEZSUP4QQRFCS7Q6UNF5 X-Message-ID-Hash: CLTYOSJQP3YPZEZSUP4QQRFCS7Q6UNF5 X-MailFrom: m.koeppl@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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>, + /// 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, } #[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, +} + +#[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 = self - .cluster_instances(cluster)? + let members = self.cluster_instances(cluster)?; + let nodes: Vec = 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