[control] Engine switch: POST /engine through a Units abstraction (systemctl via polkit, a fake in tests); engine file first, back to the old engine if the new one does not serve; changes and share links wait while Caddy serves

This commit is contained in:
2026-11-07 23:22:59 +01:00
parent c18ae154ad
commit 12886a1d31
+227
View File
@@ -0,0 +1,227 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Switching the engine at runtime (ROADMAP §3, §4; G18) with a fake `systemctl`: the engine
//! file is written first, the old unit stopped and the new one started; while Caddy serves,
//! changes and share links wait; a switch whose target does not come up goes back.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use std::time::{Duration, Instant};
use crate::common::{Env, EnvSpec};
use serde_json::{Value, json};
/// Records every call; `is-active` answers from marker files; a unit named in
/// `fail-start` cannot start.
const FAKE: &str = r#"#!/bin/sh
dir="$(dirname "$0")/units"
mkdir -p "$dir"
[ "$1" = "--no-ask-password" ] && shift
echo "$*" >> "$dir/../calls.log"
case "$1" in
start) if grep -qx "$2" "$dir/../fail-start" 2>/dev/null; then exit 1; fi; touch "$dir/$2" ;;
stop) rm -f "$dir/$2" ;;
restart) touch "$dir/$2" ;;
is-active) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
*) exit 2 ;;
esac
"#;
async fn env() -> Env {
let mut env = Env::new(EnvSpec::default()).await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::write(&fake, FAKE).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
// Edge runs now.
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n",
env.dir.join("engine").display(),
fake.display()
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
env
}
fn calls(env: &Env) -> Vec<String> {
std::fs::read_to_string(env.dir.join("fake/calls.log"))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.filter(|l| !l.starts_with("is-active"))
.collect()
}
async fn wait_engine(env: &Env, running: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let r = env.call("GET", "/api/v1/engine", None).await;
assert_eq!(r.status, 200, "{}", r.text);
if r.json["state"] == "running" && r.json["running"] == running {
return r.json;
}
if Instant::now() > deadline {
panic!("engine is {}\n{}", r.text, env.control_log());
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn switch_to_caddy_and_back() {
let env = env().await;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = json!({"host": {"hostname": "a.test", "upstreams": [echo.url()],
"tls": "domi", "auth": "none", "share_links": true}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let e = wait_engine(&env, "caddy").await;
assert!(e["last_error"].is_null(), "{e}");
assert_eq!(
calls(&env),
["stop ianitor-edge.service", "start caddy-fallback.service"]
);
assert_eq!(
std::fs::read_to_string(env.dir.join("engine")).unwrap(),
"caddy"
);
// Caddy starts from the current tree.
let caddy = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(caddy.contains("a.test"));
// While Caddy serves: changes and share links wait, the overview says so.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text);
assert_eq!(ov.json["paused"]["code"], "engine.caddy", "{}", ov.text);
assert_eq!(ov.json["site"]["share_links_available"], false);
let add = env
.call(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "b.test", "upstreams": ["http://127.0.0.1:9"], "tls": "domi"}})),
)
.await;
assert_eq!(add.status, 409, "{}", add.text);
let share = env
.call(
"POST",
"/api/v1/hosts/a.test/share-links",
Some(json!({"path_prefix": "/", "expires_in_s": 86400})),
)
.await;
assert_eq!(share.status, 409, "{}", share.text);
assert_eq!(share.json["error"]["code"], "share.engine_caddy");
// The same target again is refused.
let again = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(again.status, 409);
assert_eq!(again.json["error"]["code"], "engine.same");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "pingora"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(&env, "pingora").await;
assert_eq!(
calls(&env)[2..],
["stop caddy-fallback.service", "start ianitor-edge.service"]
);
assert_eq!(
std::fs::read_to_string(env.dir.join("engine")).unwrap(),
"pingora"
);
let ov = env.call("GET", "/api/v1/overview", None).await;
assert!(ov.json["paused"].is_null(), "{}", ov.text);
let share = env
.call(
"POST",
"/api/v1/hosts/a.test/share-links",
Some(json!({"path_prefix": "/", "expires_in_s": 86400})),
)
.await;
assert_eq!(share.status, 201, "{}", share.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_target_that_does_not_start_switches_back() {
let env = env().await;
std::fs::write(env.dir.join("fake/fail-start"), "caddy-fallback.service\n").unwrap();
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
// It ends where it started, and says why.
let deadline = Instant::now() + Duration::from_secs(30);
let e = loop {
let r = env.call("GET", "/api/v1/engine", None).await;
if r.json["state"] == "running" && !r.json["last_error"].is_null() {
break r.json;
}
assert!(Instant::now() < deadline, "{}", r.text);
tokio::time::sleep(Duration::from_millis(100)).await;
};
assert_eq!(e["running"], "pingora");
assert_eq!(e["last_error"]["code"], "engine.switch_failed");
assert_eq!(
calls(&env),
[
"stop ianitor-edge.service",
"start caddy-fallback.service",
"stop caddy-fallback.service",
"start ianitor-edge.service"
]
);
assert_eq!(
std::fs::read_to_string(env.dir.join("engine")).unwrap(),
"pingora"
);
// Changes go on as before.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert!(ov.json["paused"].is_null(), "{}", ov.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn without_engine_settings_nothing_switches() {
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "engine.unmanaged");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "nginx"})))
.await;
assert_eq!(r.status, 409);
let e = env.call("GET", "/api/v1/engine", None).await;
assert_eq!(e.json["switchable"], false);
}
}