Files
ianitor/tests/diff/tests/apply_sequence.rs
T

244 lines
8.8 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/.
//! The differential suite after every apply (ROADMAP §6 phase 2, "Done"): control applies a
//! sequence of changes to a routes repository; after each one, Ianitor runs the edge config
//! control wrote and Caddy runs the Caddy JSON control wrote, and the corpus (the cases for
//! hosts that exist at that point) must get the same answers from both.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy); run it in WSL2",
file!()
);
}
#[cfg(unix)]
mod unix {
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
use ianitor_control::engine::{Change, Control};
use ianitor_control::hostspec::HostSpec;
use ianitor_control::repo::{Repo, RouteTree};
use ianitor_diff::{Env, case_host, run_cases, settle, start_caddy, start_edge};
use ianitor_testkit::proc::require_binary;
fn compile_of(o: &ianitor_core::compile::CompileOptions) -> Compile {
Compile {
http_listen: o.http_listen,
https_listen: o.https_listen,
cert_dir: o.cert_dir.clone(),
state_dir: o.state_dir.clone(),
access_log: o.access_log.clone(),
caddy_credentials_dir: o.caddy_credentials_dir.clone(),
caddy_admin: o.caddy_admin,
caddy_admin_socket: o.caddy_admin_socket.clone(),
trusted_proxies: o.trusted_proxies.clone(),
}
}
fn wait_free(addrs: &[SocketAddr]) {
let deadline = Instant::now() + Duration::from_secs(15);
while addrs
.iter()
.any(|a| std::net::TcpStream::connect(a).is_ok())
&& Instant::now() < deadline
{
std::thread::sleep(Duration::from_millis(50));
}
}
async fn apply(ctl: &Control, change: Change) {
let rec = ctl
.submit(change, None, "diff")
.unwrap_or_else(|f| panic!("{f:?}"));
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let r = ctl.record(&rec.id).unwrap();
if !r.is_active() {
assert_eq!(r.state, "kept", "{} : {:?}", r.summary, r.reason);
return;
}
assert!(Instant::now() < deadline, "apply did not finish");
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
fn spec(env: &Env, name: &str) -> HostSpec {
let (_, text) = env
.hosts
.iter()
.find(|(p, _)| p == &format!("hosts/{name}.toml"))
.unwrap();
HostSpec::from_toml(text).unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_diff_suite_is_green_after_every_apply() {
let Some(caddy_bin) = require_binary("caddy") else {
return;
};
let env = Env::start().await;
let edge_opts = env.options("edge");
let caddy_opts = env.options("caddy");
let d = |p: &str| env.dir.join(p);
for p in ["ctl-state", "ctl-edge", "ctl-caddy"] {
std::fs::create_dir_all(d(p)).unwrap();
}
let cfg = Config {
listen: "127.0.0.1:1".parse().unwrap(),
allowed_hosts: Vec::new(),
state_dir: d("ctl-state"),
credentials_dir: Some(d("creds")),
git: PathBuf::from("git"),
watch_secs: 1,
watch_every_secs: 1,
trial_margin_secs: 1,
health_poll_secs: 1,
routes: Routes {
repo: d("routes.git"),
branch: "main".into(),
remote: None,
remote_name: "Gitea".into(),
push_username: "ianitor".into(),
push_credential: None,
},
// No edge attached: control writes both files, and each file is tested below.
edge: Edge {
config: d("ctl-edge/edge.json"),
trial: None,
admin_socket: None,
share_revocations: d("ctl-edge/share-revocations.json"),
},
caddy: Caddy {
config: d("ctl-caddy/caddy.json"),
},
compile: compile_of(&edge_opts),
compile_caddy: Some(compile_of(&caddy_opts)),
pki: None,
ui: None,
engine: None,
};
// Start from the site file and every host except three; then a sequence of applies
// ends at the full diff routes.
let later = ["hc.test", "hcdown.test", "rr.test"];
let repo = Repo::open_seeded(
&cfg.git,
&cfg.routes.repo,
&cfg.state_dir,
"main",
&env.site,
)
.unwrap();
let head = repo.head_required().unwrap();
let mut tree: RouteTree = (*repo.tree(&head).unwrap()).clone();
for (p, c) in &env.hosts {
if !later.iter().any(|l| p == &format!("hosts/{l}.toml")) {
tree.files.insert(p.clone(), c.clone());
}
}
let t = repo.write_tree(&tree, None).unwrap();
let c = repo.commit(&t, &[&head], "Diff routes", "test").unwrap();
repo.update_ref(&c, Some(&head)).unwrap();
drop(repo);
let ctl = Control::open(cfg.clone()).await.unwrap();
tokio::spawn(ctl.clone().worker());
let steps: Vec<(&str, Option<Change>)> = vec![
("start", None),
(
"add hc.test",
Some(Change::Put {
spec: spec(&env, "hc.test"),
create: true,
}),
),
(
"add hcdown.test",
Some(Change::Put {
spec: spec(&env, "hcdown.test"),
create: true,
}),
),
(
"remove nows.test",
Some(Change::Delete {
hostname: "nows.test".into(),
}),
),
(
"add rr.test",
Some(Change::Put {
spec: spec(&env, "rr.test"),
create: true,
}),
),
(
"restore nows.test",
Some(Change::Put {
spec: spec(&env, "nows.test"),
create: true,
}),
),
];
let all_hosts: Vec<String> = env
.model
.hosts()
.iter()
.map(|h| h.hostname.to_string())
.collect();
let mut ran = 0;
for (label, change) in steps {
if let Some(ch) = change {
apply(&ctl, ch).await;
}
let edge_text = std::fs::read_to_string(&cfg.edge.config).unwrap();
let caddy_text = std::fs::read_to_string(&cfg.caddy.config).unwrap();
let present: Vec<String> = {
let v: serde_json::Value = serde_json::from_str(&edge_text).unwrap();
v["hosts"]
.as_array()
.unwrap()
.iter()
.map(|h| h["hostname"].as_str().unwrap().to_owned())
.collect()
};
{
let ianitor = start_edge(&env, "ianitor", &edge_text);
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_text);
settle().await;
// Cases for hosts that exist now, plus the ones about unknown hosts.
let report = run_cases(&ianitor, &caddy, env.roots(), |c| {
let h = case_host(c);
present.contains(&h) || !all_hosts.contains(&h)
})
.await;
println!("{}", report.render(&format!("after: {label}")));
assert!(report.outcomes.len() >= 5, "{label}: too few cases");
assert!(report.mismatches().is_empty(), "{}", report.render(label));
ran += report.outcomes.len();
}
wait_free(&[
edge_opts.https_listen,
edge_opts.http_listen,
caddy_opts.https_listen,
caddy_opts.http_listen,
]);
}
// The last step is the full routes: every corpus case ran there.
assert!(ran > ianitor_diff::corpus().len());
let records = ctl.records();
assert_eq!(records.iter().filter(|r| r.state == "kept").count(), 5);
}
}