Files
ianitor/crates/control/tests/engine_switch.rs
T

396 lines
16 KiB
Rust

// 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 go on (changes_apply_while_caddy_serves), share links wait.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text);
assert!(ov.json["paused"].is_null(), "{}", ov.text);
assert_eq!(ov.json["site"]["share_links_available"], false);
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);
}
/// The fake systemctl that really runs Caddy for caddy-fallback.service (edge runs in this
/// process and keeps its own ports; Caddy gets others through [compile_caddy]).
fn fake_with_caddy(dir: &std::path::Path, caddy: &std::path::Path) -> String {
format!(
r#"#!/bin/sh
dir="{d}/fake/units"
mkdir -p "$dir"
[ "$1" = "--no-ask-password" ] && shift
echo "$*" >> "{d}/fake/calls.log"
case "$1:$2" in
start:caddy-fallback.service)
XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \
nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 &
echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;;
stop:caddy-fallback.service)
[ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;;
start:*) touch "$dir/$2" ;;
stop:*) rm -f "$dir/$2" ;;
is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;;
*) exit 2 ;;
esac
"#,
d = dir.display(),
c = caddy.display()
)
}
struct CaddyEnv {
env: Env,
https: std::net::SocketAddr,
}
impl Drop for CaddyEnv {
fn drop(&mut self) {
if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) {
let _ = std::process::Command::new("kill").arg(p.trim()).status();
}
}
}
async fn env_with_caddy() -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
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::create_dir_all(env.dir.join("caddy-state")).unwrap();
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
async fn visit(env: &Env, at: std::net::SocketAddr, host: &str) -> u16 {
match ianitor_testkit::client::https(
at,
host,
env.ca.roots(),
&ianitor_testkit::client::Req::get(host, "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
/// Mark, 2026-11-08: changes keep working while Caddy serves. An apply is loaded into
/// Caddy, watched through it, and kept, or reverted by loading the previous caddy.json;
/// Undo works the same way; share links stay off. Switching back brings edge up to date.
#[tokio::test(flavor = "multi_thread")]
async fn changes_apply_while_caddy_serves() {
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str, up: String| json!({"host": {"hostname": h, "upstreams": [up], "tls": "domi", "auth": "none", "share_links": true}});
assert_eq!(
env.apply("POST", "/api/v1/hosts", Some(host("a.test", echo.url())))
.await["state"],
"kept"
);
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
assert_eq!(
visit(env, ce.https, "a.test").await,
200,
"{}",
env.control_log()
);
// No pause while Caddy serves.
let ov = env.call("GET", "/api/v1/overview", None).await;
assert!(ov.json["paused"].is_null(), "{}", ov.text);
// Kept through Caddy.
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("b.test", echo.url())))
.await;
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
assert_eq!(visit(env, ce.https, "b.test").await, 200);
// A broken change is reverted by loading the previous caddy.json.
let broken = json!({"host": {"hostname": "c.test", "upstreams": [format!("http://127.0.0.1:{}", ianitor_testkit::upstream::closed_port())],
"tls": "domi", "auth": "none", "health_check": {"path": "/", "interval_secs": 1}}});
let rec = env.apply("POST", "/api/v1/hosts", Some(broken)).await;
assert_eq!(rec["state"], "reverted", "{rec}\n{}", env.control_log());
let caddy_json = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(!caddy_json.contains("c.test"));
assert_eq!(visit(env, ce.https, "a.test").await, 200);
assert_eq!(visit(env, ce.https, "b.test").await, 200);
// Undo (removes b.test) works under Caddy too.
let u = env.call("GET", "/api/v1/undo", None).await;
let target = u.json["target"]["change_id"].as_str().unwrap().to_owned();
let rec = env
.apply(
"POST",
"/api/v1/undo",
Some(json!({"target_change_id": target})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
assert_ne!(visit(env, ce.https, "b.test").await, 200);
// Share links stay off.
let s = env
.call(
"POST",
"/api/v1/hosts/a.test/share-links",
Some(json!({"path_prefix": "/", "expires_in_s": 86400})),
)
.await;
assert_eq!(s.status, 409, "{}", s.text);
assert_eq!(s.json["error"]["code"], "share.engine_caddy");
// Back to Pingora: edge serves what was kept under Caddy.
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;
let edge = env.edge.as_ref().unwrap();
assert_eq!(visit(env, edge.https, "a.test").await, 200);
assert_ne!(visit(env, edge.https, "b.test").await, 200);
let edge_json = std::fs::read_to_string(env.dir.join("edge/edge.json")).unwrap();
assert!(
edge_json.contains("a.test")
&& !edge_json.contains("b.test")
&& !edge_json.contains("c.test")
);
}
}