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 3/8] instance: distinguish builtin hooks from hook files
Date: Tue,  1 Dec 2026 15:58:12 +0100	[thread overview]
Message-ID: <20261201145817.894414-4-m.koeppl@proxmox.com> (raw)
In-Reply-To: <20261201145817.894414-1-m.koeppl@proxmox.com>

Hooks were command lines run relative to the current dir of
proxmox-test-instance. For proxmox-test-scheduler, that is the home dir
of the SSH user, so a plan only found its scripts if they happened to be
placed there, regardless of where the plan itself was.

Hooks now either name a script shipped with proxmox-test-instance, as in
Builtin("update-packages pve staging"), or a script of their own, as in
File("../scripts/setup-ldap.sh"), which is resolved relative to the
directory of the plan file. A symlink to the plan is resolved first, so
that the scripts next to the plan itself are found.

Hooks given as plain strings are no longer accepted, so existing plans
need to be adapted. The setup digest of plans with hooks changes
accordingly and their next setup starts fresh.

Signed-off-by: Michael Köppl <m.koeppl@proxmox.com>
---
 README.md                                     | 23 ++++++--
 proxmox-test-instance/src/cli.rs              | 20 ++++++-
 proxmox-test-instance/src/config.rs           | 53 ++++++++++++++++++-
 .../src/instance_manager/mod.rs               | 10 ++--
 4 files changed, 96 insertions(+), 10 deletions(-)

diff --git a/README.md b/README.md
index abef2c61..8bca2818 100644
--- a/README.md
+++ b/README.md
@@ -164,7 +164,8 @@ Plan(
                 // root_password: Inline("password"),
             ),
             post_setup: [
-                "scripts/update-packages.sh pve staging",
+                Builtin("update-packages pve staging"),
+                File("scripts/my-hook.sh"),
             ],
         ),
     ]
@@ -177,7 +178,24 @@ Plan(
 The `proxmox-test-instance run-script` command can be used to run scripts on test instances, e.g.
 to update them to the latest packages, to inject test artifacts etc.
 
+### Setup hooks
 
+The `post_setup` hooks of an instance run after its installation. Each hook is a command line
+naming a script, followed by its arguments, which are passed through the shell:
+
+- `Builtin("<name> [<args>]")` runs a script shipped with `proxmox-test-instance`, installed as
+  `/usr/share/proxmox-test-instance/scripts/<name>.sh`.
+- `File("<path> [<args>]")` runs a script of your own. A relative path is resolved against the
+  directory of the plan file, after resolving symlinks to it.
+
+| Builtin | Arguments | Description |
+|---|---|---|
+| `update-packages` | `<pve\|pbs\|pmg\|pdm> <staging\|no-subscription\|test>` | Switch to the given repository and upgrade all packages |
+| `download-container-image` | `<storage> <template>` | Download a container template into a storage |
+| `download-cloud-image` | `<storage> <url> <filename> <sha512>` | Download a disk image into the import content of a storage, keeping it only if the checksum matches |
+| `install-ceph` | `<version> <repository>` | Install the Ceph packages, without setting up a Ceph cluster |
+| `setup-zfs-storage` | `<disk-serial> <name>` | Create a ZFS pool on the additional disk with the given serial and add it as a storage of the same name |
+| `setup-frr` | | Install and enable FRR |
 
 Setup hooks for assets are also provided with the asset configuration via a JSON configuration file,
 located at `$CONFIG_PATH`. This allows to use the same hook script for multiple assets.
@@ -192,8 +210,7 @@ located at `$CONFIG_PATH`. This allows to use the same hook script for multiple
 To get the contents in a hook script, `jq` may be used.
 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.
-An example can be seen in `hooks/update-packages.sh` in the sibling
-`proxmox-e2e-tests` repository.
+The builtin hooks in `scripts/` serve as examples.
 
 # proxmox-test-runner
 
diff --git a/proxmox-test-instance/src/cli.rs b/proxmox-test-instance/src/cli.rs
index bbc9cb34..1033f5dd 100644
--- a/proxmox-test-instance/src/cli.rs
+++ b/proxmox-test-instance/src/cli.rs
@@ -1,10 +1,10 @@
 use std::{
     io::{BufRead, BufReader, Write},
-    path::PathBuf,
+    path::{Path, PathBuf},
     sync::{Arc, atomic::AtomicBool},
 };
 
-use anyhow::{Error, bail};
+use anyhow::{Context, Error, bail};
 use pico_args::Arguments;
 use proxmox_test_common::{
     inventory::TestInventory, log, secrets::SecretResolver, utils::from_file,
@@ -370,6 +370,18 @@ fn parse_u64(s: &std::ffi::OsStr) -> Result<u64, Error> {
     Ok(s.to_string_lossy().parse::<u64>()?)
 }
 
+/// Returns the directory the plan is in. This is used e.g. by relative hook paths of a plan.
+/// Symlinks are resolved first so that hooks are found next to the plan itself rather than next
+/// to a link.
+fn resolve_plan_dir(plan: &Path) -> Result<PathBuf, Error> {
+    let plan = plan
+        .canonicalize()
+        .with_context(|| format!("cannot resolve plan path '{}'", plan.display()))?;
+    plan.parent()
+        .map(Path::to_path_buf)
+        .context("plan path has no parent directory")
+}
+
 #[derive(Clone, Debug)]
 pub struct Cli {
     pub command: Command,
@@ -795,8 +807,10 @@ impl Command {
         let mut manager = InstanceManager::new(testrunner_config, secret_resolver, interrupted)?;
 
         let plan: Plan = from_file(args.plan.clone())?;
+        let plan_dir = resolve_plan_dir(&args.plan)?;
 
         manager.fresh_setup(
+            &plan_dir,
             &plan,
             &args.output,
             &testrunner_config.default_bridge,
@@ -817,8 +831,10 @@ impl Command {
         let mut manager = InstanceManager::new(testrunner_config, secret_resolver, interrupted)?;
 
         let plan: Plan = from_file(args.plan.clone())?;
+        let plan_dir = resolve_plan_dir(&args.plan)?;
 
         manager.setup(
+            &plan_dir,
             &plan,
             &args.output,
             &testrunner_config.default_bridge,
diff --git a/proxmox-test-instance/src/config.rs b/proxmox-test-instance/src/config.rs
index b1d99de0..7842ae1b 100644
--- a/proxmox-test-instance/src/config.rs
+++ b/proxmox-test-instance/src/config.rs
@@ -1,12 +1,16 @@
 use std::fmt::Display;
+use std::path::Path;
 
-use anyhow::{Error, bail};
+use anyhow::{Context, Error, bail};
 use serde::{Deserialize, Serialize};
 
 use proxmox_test_common::secrets::Secret;
 use proxmox_test_common::types::Disk;
 use proxmox_test_common::utils;
 
+/// Where builtin hook scripts are installed.
+pub const BUILTIN_HOOK_DIR: &str = "/usr/share/proxmox-test-instance/scripts";
+
 pub const DEFAULT_SDN_ZONE_NAME: &str = "ttzone";
 pub const DEFAULT_SDN_VNET_NAME: &str = "ttvnet";
 pub const DEFAULT_SDN_SUBNET: &str = "172.16.0.0/24";
@@ -26,10 +30,55 @@ pub struct SetupInstance {
     pub name: String,
     pub kind: InstanceKind,
     #[serde(default)]
-    pub post_setup: Vec<String>,
+    pub post_setup: Vec<Hook>,
     pub playbook: Option<String>,
 }
 
+/// 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)]
+pub enum Hook {
+    /// A script shipped with the deb package, named without its `.sh` suffix.
+    Builtin(String),
+    /// A script path relative to the directory of the plan file unless absolute.
+    File(String),
+}
+
+impl Hook {
+    /// Returns the command line that runs this hook for a plan located in `plan_dir`.
+    pub fn command(&self, plan_dir: &Path) -> Result<String, Error> {
+        let (Hook::Builtin(command) | Hook::File(command)) = self;
+        let command = command.trim();
+        let (script, args) = command
+            .split_once(char::is_whitespace)
+            .unwrap_or((command, ""));
+        if script.is_empty() {
+            bail!("hook does not name a script");
+        }
+
+        let path = match self {
+            Hook::Builtin(_) => {
+                if script.contains('/') {
+                    bail!("builtin hook '{script}' must be a name, not a path");
+                }
+                Path::new(BUILTIN_HOOK_DIR).join(format!("{script}.sh"))
+            }
+            Hook::File(_) => plan_dir.join(script),
+        };
+        let path = path
+            .to_str()
+            .with_context(|| format!("hook path '{}' is not valid UTF-8", path.display()))?;
+
+        let script = format!("'{}'", path.replace('\'', r"'\''"));
+        Ok(if args.is_empty() {
+            script
+        } else {
+            format!("{script} {args}")
+        })
+    }
+}
+
 #[derive(Clone, Debug, Deserialize, Serialize)]
 pub enum InstanceKind {
     Vm(VmSettings),
diff --git a/proxmox-test-instance/src/instance_manager/mod.rs b/proxmox-test-instance/src/instance_manager/mod.rs
index 53dee7dd..fceec04e 100644
--- a/proxmox-test-instance/src/instance_manager/mod.rs
+++ b/proxmox-test-instance/src/instance_manager/mod.rs
@@ -115,6 +115,7 @@ impl<'a> InstanceManager<'a> {
 
     pub fn fresh_setup(
         &mut self,
+        plan_dir: &Path,
         config: &Plan,
         inventory_path: &Option<PathBuf>,
         default_bridge: &str,
@@ -410,7 +411,7 @@ impl<'a> InstanceManager<'a> {
             }
         }
 
-        self.run_instance_startup(&config.instances, timeout)?;
+        self.run_instance_startup(plan_dir, &config.instances, timeout)?;
 
         if let Some(managed_datacenter) = &config.managed_datacenter {
             let s = self.state.clone();
@@ -566,6 +567,7 @@ impl<'a> InstanceManager<'a> {
     /// leaving it powered off again afterwards.
     fn run_instance_startup(
         &self,
+        plan_dir: &Path,
         setup_instances: &[SetupInstance],
         timeout: &Option<u64>,
     ) -> Result<(), Error> {
@@ -590,8 +592,8 @@ impl<'a> InstanceManager<'a> {
                 self.run_script_impl(&script, Some("first boot setup"), name)?;
             }
 
-            for script in &instance.post_setup {
-                self.run_script_impl(script, None, name)?;
+            for hook in &instance.post_setup {
+                self.run_script_impl(&hook.command(plan_dir)?, None, name)?;
             }
 
             if let Some(playbook) = &instance.playbook {
@@ -787,6 +789,7 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
 
     pub fn setup(
         &mut self,
+        plan_dir: &Path,
         config: &Plan,
         inventory_path: &PathBuf,
         default_bridge: &str,
@@ -835,6 +838,7 @@ systemctl list-unit-files --type=timer --state=enabled --no-legend | grep daily
         self.state = TestInventory::default();
 
         self.fresh_setup(
+            plan_dir,
             config,
             &Some(inventory_path.clone()),
             default_bridge,
-- 
2.47.3





  parent reply	other threads:[~2026-12-01 14:59 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 ` Michael Köppl [this message]
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 ` [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-4-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