[diff] Pair: ianitor-pair runs edge and two Caddys (all cores, GOMAXPROCS=2) on the same compiled routes for the conformance and load scripts
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
// 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/.
|
||||
|
||||
//! `ianitor-pair`: Ianitor (edge, in this process) and Caddy side by side on 127.0.0.1,
|
||||
//! serving the same routes compiled by core, for the conformance and load scripts
|
||||
//! (scripts/conformance.sh, scripts/bench.sh; ROADMAP §5 layers 2 and 5).
|
||||
//!
|
||||
//! One host, `localhost` (a Domi-style certificate from a throwaway test CA), proxied to a
|
||||
//! small upstream that answers `200 ok` and records nothing; it runs as a child process
|
||||
//! (`ianitor-pair --upstream`), so this process's memory is edge's (plus a small runtime). Two Caddys run:
|
||||
//! one as Go starts it (every core) and one with `GOMAXPROCS=2`, since edge runs Pingora with
|
||||
//! two worker threads (crates/edge/src/lib.rs). Prints one JSON line with the addresses and the
|
||||
//! CA file, then serves until SIGTERM or SIGINT.
|
||||
//!
|
||||
//! `ianitor-pair [--caddy <path>]` (default: `caddy` on PATH or `$IANITOR_CADDY_BIN`).
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn main() {
|
||||
eprintln!("ianitor-pair needs Linux (the Pingora runner and Caddy); run it in WSL2");
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn main() {
|
||||
#[allow(clippy::expect_used)]
|
||||
let rt = tokio::runtime::Runtime::new().expect("a tokio runtime");
|
||||
rt.block_on(unix::main());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod unix {
|
||||
use std::convert::Infallible;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use http_body_util::Full;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use ianitor_core::compile::{self, CompileOptions};
|
||||
use ianitor_core::{SourceFile, load};
|
||||
use ianitor_diff::{Target, start_caddy_in, start_edge_in};
|
||||
use ianitor_testkit::proc::{ChildGuard, TempDir, find_binary, free_port, local};
|
||||
use ianitor_testkit::tls::TestCa;
|
||||
use serde_json::json;
|
||||
|
||||
/// `--upstream`: serve `200 ok` on a free loopback port, print it, run until killed.
|
||||
async fn serve_upstream() {
|
||||
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
println!("{}", l.local_addr().unwrap());
|
||||
loop {
|
||||
let Ok((s, _)) = l.accept().await else {
|
||||
continue;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let svc = service_fn(|_req| async {
|
||||
Ok::<_, Infallible>(hyper::Response::new(Full::new(bytes::Bytes::from_static(
|
||||
b"ok\n",
|
||||
))))
|
||||
});
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(s), svc)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The upstream as a child process; its address.
|
||||
fn upstream() -> (ChildGuard, SocketAddr) {
|
||||
use std::io::BufRead;
|
||||
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.arg("--upstream")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let out = child.stdout.take().unwrap();
|
||||
let mut line = String::new();
|
||||
std::io::BufReader::new(out).read_line(&mut line).unwrap();
|
||||
(ChildGuard(child), line.trim().parse().unwrap())
|
||||
}
|
||||
|
||||
fn options(dir: &TempDir, engine: &str) -> CompileOptions {
|
||||
CompileOptions {
|
||||
http_listen: local(free_port()),
|
||||
https_listen: local(free_port()),
|
||||
cert_dir: dir.str("certs"),
|
||||
state_dir: dir.str(&format!("state-{engine}")),
|
||||
access_log: dir.str(&format!("logs/{engine}-access.log")),
|
||||
caddy_credentials_dir: dir.str("creds"),
|
||||
caddy_admin: None,
|
||||
caddy_admin_socket: None,
|
||||
trusted_proxies: Vec::new(),
|
||||
proxy_socket: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn addrs(t: &Target) -> serde_json::Value {
|
||||
json!({ "http": t.http.to_string(), "https": t.https.to_string() })
|
||||
}
|
||||
|
||||
pub async fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.iter().any(|a| a == "--upstream") {
|
||||
serve_upstream().await;
|
||||
return;
|
||||
}
|
||||
let caddy = args
|
||||
.iter()
|
||||
.position(|a| a == "--caddy")
|
||||
.and_then(|i| args.get(i + 1))
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| find_binary("caddy"))
|
||||
.unwrap_or_else(|| panic!("no caddy: pass --caddy <path> or put it on PATH"));
|
||||
|
||||
let (upstream_child, up) = upstream();
|
||||
let dir = TempDir::new("pair");
|
||||
for d in [
|
||||
"certs",
|
||||
"creds",
|
||||
"logs",
|
||||
"state-edge",
|
||||
"state-caddy",
|
||||
"state-caddy2",
|
||||
"xdg",
|
||||
] {
|
||||
std::fs::create_dir_all(dir.join(d)).unwrap();
|
||||
}
|
||||
let ca = TestCa::new("Ianitor Pair Test CA");
|
||||
let leaf = ca.issue(&["localhost"]);
|
||||
std::fs::write(dir.join("certs/localhost.crt"), leaf.cert_pem).unwrap();
|
||||
std::fs::write(dir.join("certs/localhost.key"), leaf.key_pem).unwrap();
|
||||
std::fs::write(dir.join("ca.pem"), &ca.cert_pem).unwrap();
|
||||
|
||||
let host =
|
||||
format!("hostname = \"localhost\"\ntls = \"domi\"\nupstreams = [\"http://{up}\"]\n");
|
||||
let model = load(
|
||||
&SourceFile {
|
||||
name: "ianitor.toml",
|
||||
contents: "",
|
||||
},
|
||||
&[SourceFile {
|
||||
name: "hosts/localhost.toml",
|
||||
contents: &host,
|
||||
}],
|
||||
)
|
||||
.expect("valid routes");
|
||||
|
||||
let edge_cfg = compile::edge(&model, &options(&dir, "edge")).unwrap();
|
||||
let caddy_cfg = compile::caddy(&model, &options(&dir, "caddy")).unwrap();
|
||||
let caddy2_cfg = compile::caddy(&model, &options(&dir, "caddy2")).unwrap();
|
||||
let ianitor = start_edge_in(dir.path(), "ianitor", &edge_cfg);
|
||||
let caddy_all = start_caddy_in(dir.path(), "caddy", &caddy, &caddy_cfg, &[]);
|
||||
let caddy_two = start_caddy_in(
|
||||
dir.path(),
|
||||
"caddy2",
|
||||
&caddy,
|
||||
&caddy2_cfg,
|
||||
&[("GOMAXPROCS", "2")],
|
||||
);
|
||||
let caddy_version = std::process::Command::new(&caddy)
|
||||
.arg("version")
|
||||
.output()
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())
|
||||
.unwrap_or_default();
|
||||
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"host": "localhost",
|
||||
"ca": dir.join("ca.pem"),
|
||||
"dir": dir.path(),
|
||||
"upstream": up.to_string(),
|
||||
"ianitor": addrs(&ianitor),
|
||||
"caddy": addrs(&caddy_all),
|
||||
"caddy_gomaxprocs2": addrs(&caddy_two),
|
||||
"edge_threads": 2,
|
||||
"build": if cfg!(debug_assertions) { "debug" } else { "release" },
|
||||
"caddy_version": caddy_version,
|
||||
})
|
||||
);
|
||||
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut term = signal(SignalKind::terminate()).unwrap();
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {}
|
||||
_ = term.recv() => {}
|
||||
}
|
||||
drop((ianitor, caddy_all, caddy_two, upstream_child));
|
||||
}
|
||||
}
|
||||
+28
-9
@@ -215,12 +215,17 @@ impl Drop for Target {
|
||||
|
||||
/// Start Ianitor edge in this process from an edge config text.
|
||||
pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
|
||||
start_edge_in(env.dir.path(), name, config_text)
|
||||
}
|
||||
|
||||
/// [`start_edge`] with the credentials in `<dir>/creds`.
|
||||
pub fn start_edge_in(dir: &std::path::Path, name: &'static str, config_text: &str) -> Target {
|
||||
let cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(config_text).unwrap();
|
||||
let (http, https) = (
|
||||
cfg.http_listen.parse().unwrap(),
|
||||
cfg.https_listen.parse().unwrap(),
|
||||
);
|
||||
let rt = ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime");
|
||||
let rt = ianitor_edge::runtime::build(cfg, Some(&dir.join("creds"))).expect("edge runtime");
|
||||
let opts = ianitor_edge::Options::default();
|
||||
let shared = ianitor_edge::shared_for(rt, &opts);
|
||||
let server = ianitor_edge::server(shared, &opts).expect("edge server");
|
||||
@@ -245,9 +250,21 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target {
|
||||
/// Start `caddy run` on a generated Caddy JSON; a start that does not come up is retried
|
||||
/// (twice), since a port can be briefly unavailable right after the previous server on it.
|
||||
pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target {
|
||||
start_caddy_in(env.dir.path(), name, caddy, json, &[])
|
||||
}
|
||||
|
||||
/// [`start_caddy`] in `dir` (its files, `<dir>/xdg` as home), with extra environment variables
|
||||
/// (the benchmark sets `GOMAXPROCS`).
|
||||
pub fn start_caddy_in(
|
||||
dir: &std::path::Path,
|
||||
name: &'static str,
|
||||
caddy: &std::path::Path,
|
||||
json: &str,
|
||||
envs: &[(&str, &str)],
|
||||
) -> Target {
|
||||
let mut last = String::new();
|
||||
for _ in 0..3 {
|
||||
match try_start_caddy(env, name, caddy, json) {
|
||||
match try_start_caddy(dir, name, caddy, json, envs) {
|
||||
Ok(t) => return t,
|
||||
Err(e) => {
|
||||
last = e;
|
||||
@@ -259,10 +276,11 @@ pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json:
|
||||
}
|
||||
|
||||
fn try_start_caddy(
|
||||
env: &Env,
|
||||
dir: &std::path::Path,
|
||||
name: &'static str,
|
||||
caddy: &std::path::Path,
|
||||
json: &str,
|
||||
envs: &[(&str, &str)],
|
||||
) -> Result<Target, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(json).unwrap();
|
||||
let servers = &v["apps"]["http"]["servers"];
|
||||
@@ -276,16 +294,17 @@ fn try_start_caddy(
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
let file = env.dir.join(&format!("{name}.json"));
|
||||
let file = dir.join(format!("{name}.json"));
|
||||
std::fs::write(&file, json).unwrap();
|
||||
let log = std::fs::File::create(env.dir.join(&format!("{name}.log"))).unwrap();
|
||||
let log = std::fs::File::create(dir.join(format!("{name}.log"))).unwrap();
|
||||
let child = Command::new(caddy)
|
||||
.arg("run")
|
||||
.arg("--config")
|
||||
.arg(&file)
|
||||
.env("HOME", env.dir.join("xdg"))
|
||||
.env("XDG_CONFIG_HOME", env.dir.join("xdg"))
|
||||
.env("XDG_DATA_HOME", env.dir.join("xdg"))
|
||||
.env("HOME", dir.join("xdg"))
|
||||
.env("XDG_CONFIG_HOME", dir.join("xdg"))
|
||||
.env("XDG_DATA_HOME", dir.join("xdg"))
|
||||
.envs(envs.iter().copied())
|
||||
.stdout(Stdio::from(log.try_clone().unwrap()))
|
||||
.stderr(Stdio::from(log))
|
||||
.spawn()
|
||||
@@ -296,7 +315,7 @@ fn try_start_caddy(
|
||||
{
|
||||
let _ = guard.0.kill();
|
||||
let _ = guard.0.wait();
|
||||
let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default();
|
||||
let out = std::fs::read_to_string(dir.join(format!("{name}.log"))).unwrap_or_default();
|
||||
return Err(format!("caddy did not listen on {https} / {http}:\n{out}"));
|
||||
}
|
||||
Ok(Target {
|
||||
|
||||
Reference in New Issue
Block a user