| 1 | #![cfg(any(unix, windows))] |
| 2 | |
| 3 | use std::io::{BufRead, BufReader}; |
| 4 | use std::path::PathBuf; |
| 5 | use std::process::{Child, Command, Stdio}; |
| 6 | use std::sync::mpsc; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use serde_json::{Value, json}; |
| 10 | |
| 11 | const TOKEN: &str = "owner-crash-reentry-fixture-token"; |
| 12 | const LISTENING: &str = "Runtime API listening on http://"; |
| 13 | |
| 14 | struct Fixture { |
| 15 | root: tempfile::TempDir, |
| 16 | } |
| 17 | |
| 18 | impl Fixture { |
| 19 | fn new() -> Self { |
| 20 | #[cfg(unix)] |
| 21 | let root = tempfile::Builder::new() |
| 22 | .prefix("cw-ocr-") |
| 23 | .tempdir_in( |
| 24 | std::env::temp_dir() |
| 25 | .canonicalize() |
| 26 | .expect("canonical temporary directory"), |
| 27 | ) |
| 28 | .expect("fixture root"); |
| 29 | #[cfg(windows)] |
| 30 | let root = tempfile::tempdir().expect("fixture root"); |
| 31 | for name in ["home", "state", "tmp", "work"] { |
| 32 | std::fs::create_dir_all(root.path().join(name)).expect("fixture directory"); |
| 33 | } |
| 34 | std::fs::write(root.path().join("config.toml"), "").expect("fixture config"); |
| 35 | Self { root } |
| 36 | } |
| 37 | |
| 38 | fn path(&self, name: &str) -> PathBuf { |
| 39 | self.root.path().join(name) |
| 40 | } |
| 41 | |
| 42 | fn command(&self) -> Command { |
| 43 | let mut command = Command::new( |
| 44 | std::env::var_os("CARGO_BIN_EXE_codewhale") |
| 45 | .filter(|value| !value.is_empty()) |
| 46 | .map(std::path::PathBuf::from) |
| 47 | .unwrap_or_else(|| std::path::PathBuf::from(env!("CARGO_BIN_EXE_codewhale"))), |
| 48 | ); |
| 49 | command.current_dir(self.path("work")).env_clear(); |
| 50 | for name in ["PATH", "SystemRoot", "WINDIR"] { |
| 51 | if let Some(value) = std::env::var_os(name) { |
| 52 | command.env(name, value); |
| 53 | } |
| 54 | } |
| 55 | let home = self.path("home"); |
| 56 | let tmp = self.path("tmp"); |
| 57 | command |
| 58 | .env("HOME", &home) |
| 59 | .env("USERPROFILE", &home) |
| 60 | .env("CODEWHALE_HOME", self.path("state")) |
| 61 | .env("CODEWHALE_SECRET_BACKEND", "file") |
| 62 | .env("CODEWHALE_TELEMETRY", "0") |
| 63 | .env("CODEWHALE_RUNTIME_TOKEN", TOKEN) |
| 64 | .env("TEMP", &tmp) |
| 65 | .env("TMP", &tmp) |
| 66 | .env("TMPDIR", &tmp) |
| 67 | .arg("--config") |
| 68 | .arg(self.path("config.toml")) |
| 69 | .arg("--no-project-config"); |
| 70 | command |
| 71 | } |
| 72 | |
| 73 | fn receipt(&self) -> (Vec<u8>, Value) { |
| 74 | #[cfg(unix)] |
| 75 | let path = codewhale_paths::daemon_socket::resolve_socket_path( |
| 76 | &codewhale_paths::daemon_socket::SocketPathInputs { |
| 77 | explicit: None, |
| 78 | codewhale_home_override: Some(self.path("state")), |
| 79 | xdg_runtime_dir: None, |
| 80 | user_home: Some(self.path("home")), |
| 81 | macos: cfg!(target_os = "macos"), |
| 82 | }, |
| 83 | ) |
| 84 | .expect("fixture socket path") |
| 85 | .with_file_name("daemon.sock.owner.json"); |
| 86 | #[cfg(windows)] |
| 87 | let path = self.path("state").join("run").join("daemon.owner.json"); |
| 88 | let bytes = std::fs::read(path).expect("published owner receipt"); |
| 89 | let value = serde_json::from_slice(&bytes).expect("owner receipt JSON"); |
| 90 | (bytes, value) |
| 91 | } |
| 92 | |
| 93 | fn stderr(&self, label: &str) -> String { |
| 94 | std::fs::read_to_string(self.path(&format!("{label}.stderr"))).unwrap_or_default() |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | struct Owner { |
| 99 | child: Child, |
| 100 | base: String, |
| 101 | } |
| 102 | |
| 103 | impl Drop for Owner { |
| 104 | fn drop(&mut self) { |
| 105 | let _ = self.child.kill(); |
| 106 | let _ = self.child.wait(); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn spawn_owner(fixture: &Fixture, label: &str) -> Owner { |
| 111 | let stderr = std::fs::File::create(fixture.path(&format!("{label}.stderr"))) |
| 112 | .expect("owner stderr capture"); |
| 113 | let mut child = fixture |
| 114 | .command() |
| 115 | .args(["app-server", "--http", "--host", "127.0.0.1", "--port", "0"]) |
| 116 | .stdin(Stdio::null()) |
| 117 | .stdout(Stdio::piped()) |
| 118 | .stderr(Stdio::from(stderr)) |
| 119 | .spawn() |
| 120 | .expect("spawn codewhale app-server"); |
| 121 | let stdout = child.stdout.take().expect("owner stdout"); |
| 122 | let (ready, listening) = mpsc::channel(); |
| 123 | std::thread::spawn(move || { |
| 124 | let mut ready = Some(ready); |
| 125 | for line in BufReader::new(stdout).lines() { |
| 126 | let Ok(line) = line else { break }; |
| 127 | if let Some(address) = line.strip_prefix(LISTENING) |
| 128 | && let Some(ready) = ready.take() |
| 129 | { |
| 130 | let _ = ready.send(address.trim().to_string()); |
| 131 | } |
| 132 | } |
| 133 | }); |
| 134 | let mut owner = Owner { |
| 135 | child, |
| 136 | base: String::new(), |
| 137 | }; |
| 138 | match listening.recv_timeout(Duration::from_secs(120)) { |
| 139 | Ok(address) => owner.base = format!("http://{address}"), |
| 140 | Err(_) => { |
| 141 | let status = owner.child.try_wait().ok().flatten(); |
| 142 | drop(owner); |
| 143 | panic!( |
| 144 | "{label} never reported readiness (exit: {status:?})\nstderr:\n{}", |
| 145 | fixture.stderr(label) |
| 146 | ); |
| 147 | } |
| 148 | } |
| 149 | owner |
| 150 | } |
| 151 | |
| 152 | fn http() -> reqwest::blocking::Client { |
| 153 | codewhale_release::tls::reqwest_blocking_client_builder() |
| 154 | .no_proxy() |
| 155 | .timeout(Duration::from_secs(30)) |
| 156 | .build() |
| 157 | .expect("loopback HTTP client") |
| 158 | } |
| 159 | |
| 160 | #[test] |
| 161 | fn killed_owner_is_replaced_by_the_next_app_server() { |
| 162 | let fixture = Fixture::new(); |
| 163 | let client = http(); |
| 164 | |
| 165 | let mut first = spawn_owner(&fixture, "first"); |
| 166 | let (first_bytes, first_receipt) = fixture.receipt(); |
| 167 | assert_eq!(first_receipt["pid"], json!(first.child.id())); |
| 168 | let created = client |
| 169 | .post(format!("{}/v1/threads", first.base)) |
| 170 | .bearer_auth(TOKEN) |
| 171 | .json(&json!({})) |
| 172 | .send() |
| 173 | .expect("create thread on the first owner"); |
| 174 | let status = created.status(); |
| 175 | let created: Value = created.json().expect("created thread JSON"); |
| 176 | assert!(status.is_success(), "create thread: {status} {created}"); |
| 177 | let thread_id = created["id"] |
| 178 | .as_str() |
| 179 | .expect("created thread id") |
| 180 | .to_string(); |
| 181 | |
| 182 | first.child.kill().expect("kill the first owner"); |
| 183 | first.child.wait().expect("reap the first owner"); |
| 184 | let (dead_bytes, dead_receipt) = fixture.receipt(); |
| 185 | assert_eq!(dead_bytes, first_bytes); |
| 186 | assert_eq!(dead_receipt["pid"], json!(first.child.id())); |
| 187 | |
| 188 | let second = spawn_owner(&fixture, "second"); |
| 189 | let (_, second_receipt) = fixture.receipt(); |
| 190 | assert_eq!(second_receipt["pid"], json!(second.child.id())); |
| 191 | assert_ne!( |
| 192 | second_receipt["lease_generation"], |
| 193 | first_receipt["lease_generation"] |
| 194 | ); |
| 195 | assert_eq!(second_receipt["data_dir"], first_receipt["data_dir"]); |
| 196 | assert_eq!( |
| 197 | second_receipt["execution_scope"], |
| 198 | first_receipt["execution_scope"] |
| 199 | ); |
| 200 | |
| 201 | let listed: Value = client |
| 202 | .get(format!("{}/v1/threads", second.base)) |
| 203 | .bearer_auth(TOKEN) |
| 204 | .send() |
| 205 | .expect("list threads on the second owner") |
| 206 | .json() |
| 207 | .expect("thread list JSON"); |
| 208 | assert!( |
| 209 | listed |
| 210 | .as_array() |
| 211 | .expect("thread list") |
| 212 | .iter() |
| 213 | .any(|thread| thread["id"] == json!(thread_id)), |
| 214 | "{thread_id} missing from {listed}" |
| 215 | ); |
| 216 | |
| 217 | let attached = fixture |
| 218 | .command() |
| 219 | .args(["thread", "list"]) |
| 220 | .stdin(Stdio::null()) |
| 221 | .output() |
| 222 | .expect("run codewhale thread list"); |
| 223 | let stdout = String::from_utf8_lossy(&attached.stdout); |
| 224 | assert!( |
| 225 | attached.status.success() && stdout.contains(&thread_id), |
| 226 | "thread list through the second owner failed ({})\nstdout:\n{stdout}\nstderr:\n{}", |
| 227 | attached.status, |
| 228 | String::from_utf8_lossy(&attached.stderr) |
| 229 | ); |
| 230 | } |
| 231 |