Merge fix/bus-01-notes (coordinator review): bus shadow check refuses on the session runtime; worker children die with their parent (PDEATHSIG, spawned from async worker threads, never spawn_blocking); digest-mismatch test
This commit is contained in:
commit
48aedd25ff
7 changed files with 194 additions and 0 deletions
|
|
@ -518,6 +518,12 @@ check() {
|
|||
esac
|
||||
done
|
||||
set -- "${pass[@]}"
|
||||
# Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session
|
||||
# runtime during the window, the verdict no longer covers what would be cut over.
|
||||
if [ -f "$RUNTIME_DROPIN" ]; then
|
||||
echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)"
|
||||
exit 1
|
||||
fi
|
||||
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
|
||||
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
|
||||
# present (G1-a).
|
||||
|
|
|
|||
|
|
@ -867,6 +867,23 @@ if command -v python3 >/dev/null 2>&1; then
|
|||
else
|
||||
fail "fly-shadow-run check --bus must pass --require-arm bus/process to fly-shadow check ($(cat "$cb_tmp/args" 2>/dev/null))"
|
||||
fi
|
||||
# BUS-01 review N1: `check` (plain and --bus) refuses while the live fly runs the session
|
||||
# runtime, which writes no trace for the shadow to follow, and never asks fly-shadow.
|
||||
printf '[Service]\nExecStart=/opt/fly/current/flysim-session\n' > "$cb_tmp/10-runtime.conf"
|
||||
for ck_args in "" "--bus"; do
|
||||
rm -f "$cb_tmp/args"
|
||||
ck_rc=0
|
||||
# shellcheck disable=SC2086
|
||||
ck_out="$(PATH="$cb_tmp/bin:$PATH" FLY_SHADOW_DIR="$cb_tmp/shadow" FLY_SHADOW_BIN="$cb_tmp/fly-shadow" \
|
||||
FLY_SHADOW_REMOTE_DROPIN_DIR="$cb_tmp/none.d" FLY_ENV_FILE="$cb_tmp/none.env" \
|
||||
FLY_RUNTIME_DROPIN="$cb_tmp/10-runtime.conf" \
|
||||
"$INFRA_DIR/bin/fly-shadow-run" check $ck_args 2>&1)" || ck_rc=$?
|
||||
if [ "$ck_rc" -ne 0 ] && echo "$ck_out" | grep -q 'runs the session runtime' && [ ! -e "$cb_tmp/args" ]; then
|
||||
pass "fly-shadow-run check${ck_args:+ $ck_args} refuses while the live fly runs the session runtime"
|
||||
else
|
||||
fail "fly-shadow-run check${ck_args:+ $ck_args} must refuse while the session runtime drop-in exists (rc=$ck_rc): $ck_out"
|
||||
fi
|
||||
done
|
||||
rm -rf "$cb_tmp"
|
||||
fi
|
||||
# SHADOW-02: `check` in remote mode also needs the relay healthy now (relay.json under a minute
|
||||
|
|
|
|||
1
services/flysim/Cargo.lock
generated
1
services/flysim/Cargo.lock
generated
|
|
@ -505,6 +505,7 @@ dependencies = [
|
|||
"flybrain-gb",
|
||||
"flybus",
|
||||
"flysim-store",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ flate2 = { workspace = true }
|
|||
flysim-store = { path = "../flysim-store" }
|
||||
|
||||
serde_json = { workspace = true }
|
||||
# PR_SET_PDEATHSIG for worker processes (a child never outlives its parent, systemd or not).
|
||||
libc = "0.2"
|
||||
# `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread
|
||||
# worker each build their own runtime sized to the launcher's thread allocation.
|
||||
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "io-util"] }
|
||||
|
|
|
|||
|
|
@ -548,6 +548,32 @@ pub fn default_worker_program() -> PathBuf {
|
|||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
/// Makes `command`'s child die with its parent (BUS-01 review N2): the kernel sends it SIGKILL when
|
||||
/// the parent *thread* that spawned it exits, so a worker never outlives its coordinator even outside
|
||||
/// systemd's cgroup kill (a hung worker used to survive a killed parent, once for 47 hours).
|
||||
///
|
||||
/// Linux delivers the signal when the spawning thread ends, not the whole process, so spawn from a
|
||||
/// thread that lives as long as the process: a runtime worker or the main thread, never a
|
||||
/// short-lived blocking-pool thread. Setting the signal races a parent that already died; the child
|
||||
/// checks its parent id after setting it and exits if it was already re-parented.
|
||||
pub fn die_with_parent(command: &mut std::process::Command) {
|
||||
use std::os::unix::process::CommandExt;
|
||||
let parent = std::process::id() as libc::pid_t;
|
||||
// SAFETY: the closure runs between fork and exec and calls only async-signal-safe functions
|
||||
// (prctl, getppid, _exit); it allocates nothing and takes no locks.
|
||||
unsafe {
|
||||
command.pre_exec(move || {
|
||||
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if libc::getppid() != parent {
|
||||
libc::_exit(1);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Launcher {
|
||||
/// Connects the supervisor and prepares the launcher. Nothing is started yet.
|
||||
pub async fn start(
|
||||
|
|
@ -1011,6 +1037,7 @@ impl Launcher {
|
|||
}
|
||||
}
|
||||
command.stdin(std::process::Stdio::null());
|
||||
die_with_parent(&mut command);
|
||||
let child = command.spawn().map_err(|e| {
|
||||
DomainError::new(
|
||||
ErrorCode::BackendFailure,
|
||||
|
|
|
|||
75
services/flysim/crates/fly-session/tests/orphans.rs
Normal file
75
services/flysim/crates/fly-session/tests/orphans.rs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
//! BUS-01 review N2: a worker process never outlives its parent, outside systemd too.
|
||||
//!
|
||||
//! The test re-executes its own binary as the "parent" (selected by an environment variable),
|
||||
//! which spawns one worker through the launcher's `die_with_parent` and one plain control child,
|
||||
//! then waits. The outer test `kill -9`s the parent and checks the worker is gone within a bound
|
||||
//! while the control child, which has no death signal, survives (so the check can fail).
|
||||
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ROLE: &str = "FLY_TEST_ORPHAN_PARENT";
|
||||
const BOUND: Duration = Duration::from_secs(5);
|
||||
|
||||
/// True while `pid` is a live process (a zombie awaiting its reaper counts as gone).
|
||||
fn alive(pid: u32) -> bool {
|
||||
match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
|
||||
Ok(stat) => {
|
||||
let state = stat.rsplit(')').next().unwrap_or("").trim().chars().next();
|
||||
state != Some('Z') && state != Some('X')
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_gone(pid: u32) -> bool {
|
||||
let start = Instant::now();
|
||||
while start.elapsed() < BOUND {
|
||||
if !alive(pid) {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_killed_parent_takes_its_workers_with_it() {
|
||||
if std::env::var_os(ROLE).is_some() {
|
||||
// The parent: spawn a protected worker and an unprotected control, report, then wait.
|
||||
let mut worker = Command::new("sleep");
|
||||
worker.arg("300");
|
||||
fly_session::launcher::die_with_parent(&mut worker);
|
||||
let mut worker = worker.spawn().unwrap();
|
||||
let mut control = Command::new("sleep").arg("300").spawn().unwrap();
|
||||
println!("{} {}", worker.id(), control.id());
|
||||
let _ = worker.wait();
|
||||
let _ = control.wait();
|
||||
return;
|
||||
}
|
||||
let mut parent = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "a_killed_parent_takes_its_workers_with_it", "--nocapture", "--test-threads=1"])
|
||||
.env(ROLE, "1")
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut lines = BufReader::new(parent.stdout.take().unwrap()).lines();
|
||||
let (worker, control) = loop {
|
||||
let line = lines.next().expect("the parent reports its children").unwrap();
|
||||
let ids: Vec<u32> = line.split_whitespace().filter_map(|t| t.parse().ok()).collect();
|
||||
if ids.len() == 2 {
|
||||
break (ids[0], ids[1]);
|
||||
}
|
||||
};
|
||||
assert!(alive(worker) && alive(control));
|
||||
// SIGKILL: no cleanup runs in the parent, so only the kernel can take the worker down.
|
||||
unsafe { libc::kill(parent.id() as i32, libc::SIGKILL) };
|
||||
parent.wait().unwrap();
|
||||
let worker_gone = wait_gone(worker);
|
||||
let control_survived = alive(control);
|
||||
unsafe { libc::kill(control as i32, libc::SIGKILL) };
|
||||
unsafe { libc::kill(worker as i32, libc::SIGKILL) };
|
||||
assert!(worker_gone, "the worker outlived its killed parent");
|
||||
assert!(control_survived, "the control child should have survived (the check cannot fail otherwise)");
|
||||
}
|
||||
|
|
@ -589,6 +589,72 @@ both_transports!(
|
|||
hello_reports_the_contract_digest_and_valid_limits,
|
||||
);
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// Review note N3 (BUS-01): the SDK refuses a router whose contract digest is not its own, at
|
||||
// Hello, with the explicit version-mismatch error. The wire change that added `readLocation`
|
||||
// moved the digest, so a client and router built from different sources must not talk.
|
||||
|
||||
/// Serves one Hello on `server` the way the router does, announcing `digest`.
|
||||
async fn answer_hello_with(server: tokio::io::DuplexStream, digest: String) {
|
||||
let (mut rd, mut wr) = tokio::io::split(server);
|
||||
let bytes = read_frame(&mut rd).await.unwrap().expect("a hello frame");
|
||||
let hello = Envelope::decode(&bytes).unwrap();
|
||||
assert_eq!(hello.op, "bus.hello");
|
||||
let value = json!({
|
||||
"routerId": "router-1", "connectionId": "conn-1",
|
||||
"selectedMajor": 1, "selectedMinor": 0,
|
||||
"contractDigest": digest,
|
||||
"limits": Limits::default().to_json(),
|
||||
});
|
||||
let mut body = Map::new();
|
||||
body.insert("ok".into(), json!(true));
|
||||
body.insert("value".into(), value);
|
||||
let mut reply = Envelope::new("bus-1".into(), Kind::Reply, "bus.hello", body);
|
||||
reply.reply_to = Some(hello.id);
|
||||
write_frame(&mut wr, &reply.encode().unwrap()).await.unwrap();
|
||||
// Keep the connection open until the client has decided.
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_client_refuses_a_router_with_a_different_contract_digest_at_hello() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let wrong = "0".repeat(64);
|
||||
assert_ne!(wrong, contract_digest());
|
||||
let (client_end, server_end) = tokio::io::duplex(64 * 1024);
|
||||
tokio::spawn(answer_hello_with(server_end, wrong));
|
||||
let refused = within(
|
||||
"hello",
|
||||
flybus::Client::connect(
|
||||
flybus::Transport::from_stream(client_end),
|
||||
flybus::ClientConfig::new("digest-client", dir.path()),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let Err(err) = refused else {
|
||||
panic!("a mismatched digest must be refused");
|
||||
};
|
||||
assert_eq!(err.code, flybus::ErrorCode::VersionMismatch);
|
||||
assert_eq!(err.message, "router speaks a different contract");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn the_same_fake_router_with_the_right_digest_is_accepted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (client_end, server_end) = tokio::io::duplex(64 * 1024);
|
||||
tokio::spawn(answer_hello_with(server_end, contract_digest()));
|
||||
let client = within(
|
||||
"hello",
|
||||
flybus::Client::connect(
|
||||
flybus::Transport::from_stream(client_end),
|
||||
flybus::ClientConfig::new("digest-client", dir.path()),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("a matching digest is accepted");
|
||||
assert_eq!(client.info().contract_digest, contract_digest());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// bus-v1 §11 acceptance test 1: "In-memory transport must pass the same tests as Unix
|
||||
// sockets." Every test above already runs on both (that is what `both_transports!` is for);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue