| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | | use anyhow::{bail, Context, Result}; |
| 9 | | use serde::{Deserialize, Serialize}; |
| 10 | | use std::path::{Path, PathBuf}; |
| 11 | | use std::time::Duration; |
| 12 | |
|
| 13 | |
|
| 14 | | pub const NEW: &str = "flow.new"; |
| 15 | |
|
| 16 | | pub const PREV: &str = "flow.prev"; |
| 17 | |
|
| 18 | | const PENDING: &str = "update.json"; |
| 19 | |
|
| 20 | | const LOG: &str = "updates.log"; |
| 21 | |
|
| 22 | | const PID: &str = "runner.pid"; |
| 23 | |
|
| 24 | |
|
| 25 | | const REQUEST: &str = "update.request"; |
| 26 | |
|
| 27 | | pub const MAX_STARTS: u32 = 3; |
| 28 | |
|
| 29 | | pub const PROVE_WITHIN: Duration = Duration::from_secs(10 * 60); |
| 30 | |
|
| 31 | |
|
| 32 | | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 33 | | pub struct Pending { |
| 34 | | pub from: String, |
| 35 | | pub to: String, |
| 36 | | |
| 37 | | pub exe: PathBuf, |
| 38 | | pub at_ms: u64, |
| 39 | | |
| 40 | | pub notice_secs: u64, |
| 41 | | |
| 42 | | pub starts: u32, |
| 43 | | } |
| 44 | |
|
| 45 | |
|
| 46 | | #[derive(Debug, PartialEq, Eq)] |
| 47 | | pub struct Installed { |
| 48 | | pub from: String, |
| 49 | | pub to: String, |
| 50 | | pub exe: PathBuf, |
| 51 | | |
| 52 | | pub told: Option<u32>, |
| 53 | | } |
| 54 | |
|
| 55 | |
|
| 56 | 4× | pub fn parse_version(line: &str) -> Option<String> { |
| 57 | 4× | let v = line.trim().strip_prefix("flow ")?.split_whitespace().next()?; |
| 58 | 8× | v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())).then(|| v.to_string()) |
| 59 | 4× | } |
| 60 | |
|
| 61 | |
|
| 62 | 3× | pub fn older(a: &str, b: &str) -> bool { |
| 63 | 17× | let parts = |v: &str| v.split('.').map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>(); |
| 64 | 3× | parts(a) < parts(b) |
| 65 | 3× | } |
| 66 | |
|
| 67 | |
|
| 68 | |
|
| 69 | 5× | pub fn beside(exe: &Path, stem: &str) -> PathBuf { |
| 70 | 5× | match exe.extension() { |
| 71 | 1× | Some(e) => exe.with_file_name(format!("{stem}.{}", e.to_string_lossy())), |
| 72 | 4× | None => exe.with_file_name(stem), |
| 73 | | } |
| 74 | 5× | } |
| 75 | |
|
| 76 | |
|
| 77 | 2× | fn pe_machine_here() -> Option<u16> { |
| 78 | 2× | Some(match std::env::consts::ARCH { |
| 79 | 2× | "x86_64" => 0x8664, |
| 80 | 0× | "aarch64" => 0xAA64, |
| 81 | 0× | _ => return None, |
| 82 | | }) |
| 83 | 2× | } |
| 84 | |
|
| 85 | |
|
| 86 | 3× | pub fn check_pe(bytes: &[u8]) -> Result<()> { |
| 87 | 3× | if bytes.len() < 0x40 || &bytes[..2] != b"MZ" { |
| 88 | 1× | bail!("not a Windows executable"); |
| 89 | 2× | } |
| 90 | 2× | let at = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize; |
| 91 | 2× | if bytes.len() < at + 6 || &bytes[at..at + 4] != b"PE\0\0" { |
| 92 | 0× | bail!("not a Windows executable (no PE header in its first {} bytes)", bytes.len()); |
| 93 | 2× | } |
| 94 | 2× | let machine = u16::from_le_bytes([bytes[at + 4], bytes[at + 5]]); |
| 95 | 2× | match pe_machine_here() { |
| 96 | 2× | Some(m) if m == machine => Ok(()), |
| 97 | 1× | Some(_) => bail!("a build for another machine (PE machine {machine:#x}); this runner is {}", std::env::consts::ARCH), |
| 98 | 0× | None => bail!("updates are not supported on {}", std::env::consts::ARCH), |
| 99 | | } |
| 100 | 3× | } |
| 101 | |
|
| 102 | |
|
| 103 | 2× | fn machine_here() -> Option<u16> { |
| 104 | 2× | Some(match std::env::consts::ARCH { |
| 105 | 2× | "x86_64" => 62, |
| 106 | 0× | "aarch64" => 183, |
| 107 | 0× | "riscv64" => 243, |
| 108 | 0× | _ => return None, |
| 109 | | }) |
| 110 | 2× | } |
| 111 | |
|
| 112 | |
|
| 113 | |
|
| 114 | |
|
| 115 | 3× | pub fn check_target(bytes: &[u8]) -> Result<()> { |
| 116 | 3× | if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" { |
| 117 | 1× | bail!("not an ELF executable"); |
| 118 | 2× | } |
| 119 | 2× | if bytes[4] != 2 || bytes[5] != 1 { |
| 120 | 0× | bail!("not a 64-bit little-endian build"); |
| 121 | 2× | } |
| 122 | 2× | let machine = u16::from_le_bytes([bytes[18], bytes[19]]); |
| 123 | 2× | match machine_here() { |
| 124 | 2× | Some(m) if m == machine => Ok(()), |
| 125 | 1× | Some(_) => bail!("a build for another machine (ELF machine {machine}); this runner is {}", std::env::consts::ARCH), |
| 126 | 0× | None => bail!("updates are not supported on {}", std::env::consts::ARCH), |
| 127 | | } |
| 128 | 3× | } |
| 129 | |
|
| 130 | |
|
| 131 | 0× | fn run(file: &Path, args: &[&str], limit: Duration) -> Result<String> { |
| 132 | 0× | let mut child = std::process::Command::new(file) |
| 133 | 0× | .args(args) |
| 134 | 0× | .stdin(std::process::Stdio::null()) |
| 135 | 0× | .stdout(std::process::Stdio::piped()) |
| 136 | 0× | .stderr(std::process::Stdio::piped()) |
| 137 | 0× | .spawn() |
| 138 | 0× | .with_context(|| format!("starting {}", file.display()))?; |
| 139 | 0× | let start = std::time::Instant::now(); |
| 140 | | loop { |
| 141 | 0× | if child.try_wait()?.is_some() { |
| 142 | 0× | break; |
| 143 | 0× | } |
| 144 | 0× | if start.elapsed() > limit { |
| 145 | 0× | let _ = child.kill(); |
| 146 | 0× | let _ = child.wait(); |
| 147 | 0× | bail!("`{} {}` did not finish within {} s", file.display(), args.join(" "), limit.as_secs()); |
| 148 | 0× | } |
| 149 | 0× | std::thread::sleep(Duration::from_millis(50)); |
| 150 | | } |
| 151 | 0× | let out = child.wait_with_output()?; |
| 152 | 0× | if !out.status.success() { |
| 153 | 0× | bail!("`{} {}` failed ({}): {}", file.display(), args.join(" "), out.status, String::from_utf8_lossy(&out.stderr).trim()); |
| 154 | 0× | } |
| 155 | 0× | Ok(String::from_utf8_lossy(&out.stdout).into_owned()) |
| 156 | 0× | } |
| 157 | |
|
| 158 | |
|
| 159 | |
|
| 160 | |
|
| 161 | 3× | pub fn copy_checked(from: &Path, to: &Path, size: u64, blake3: &str) -> Result<()> { |
| 162 | 3× | let bytes = std::fs::read(from).with_context(|| format!("reading {}", from.display()))?; |
| 163 | 3× | let got = blake3::hash(&bytes).to_hex().to_string(); |
| 164 | 3× | if bytes.len() as u64 != size || got != blake3 { |
| 165 | 2× | bail!("{} is not the build the hub attests ({} bytes, BLAKE3 {}…)", from.display(), bytes.len(), &got[..12]); |
| 166 | 1× | } |
| 167 | 1× | let part = to.with_extension("partial"); |
| 168 | 1× | std::fs::write(&part, &bytes).with_context(|| format!("writing {}", part.display()))?; |
| 169 | 1× | std::fs::rename(&part, to)?; |
| 170 | 1× | Ok(()) |
| 171 | 3× | } |
| 172 | |
|
| 173 | |
|
| 174 | |
|
| 175 | |
|
| 176 | 0× | pub fn check(file: &Path, home: &Path) -> Result<String> { |
| 177 | 0× | let mut head = vec![0u8; 4096]; |
| 178 | 0× | let n = std::io::Read::read(&mut std::fs::File::open(file).with_context(|| format!("opening {}", file.display()))?, &mut head)?; |
| 179 | 0× | if cfg!(windows) { |
| 180 | 0× | check_pe(&head[..n])?; |
| 181 | | } else { |
| 182 | 0× | check_target(&head[..n])?; |
| 183 | | } |
| 184 | 0× | let limit = Duration::from_secs(30); |
| 185 | 0× | let line = run(file, &["--version"], limit)?; |
| 186 | 0× | let version = parse_version(&line).with_context(|| format!("{} does not say it is flow: {:?}", file.display(), line.trim()))?; |
| 187 | 0× | let home_s = home.to_string_lossy(); |
| 188 | 0× | let tiers = run(file, &["--home", &home_s, "tiers"], limit)?; |
| 189 | 0× | if !tiers.lines().any(|l| l.ends_with(": available")) { |
| 190 | 0× | bail!("flow {version} finds no tier it can run here:\n{}", tiers.trim()); |
| 191 | 0× | } |
| 192 | 0× | Ok(version) |
| 193 | 0× | } |
| 194 | |
|
| 195 | 2× | fn now_ms() -> u64 { |
| 196 | 2× | std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) |
| 197 | 2× | } |
| 198 | |
|
| 199 | 2× | fn log(home: &Path, event: &str, from: &str, to: &str, why: &str) { |
| 200 | | use std::io::Write; |
| 201 | 2× | let line = serde_json::json!({"at_ms": now_ms(), "event": event, "from": from, "to": to, "why": why}); |
| 202 | 2× | if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(home.join(LOG)) { |
| 203 | 2× | let _ = writeln!(f, "{line}"); |
| 204 | 2× | } |
| 205 | 2× | } |
| 206 | |
|
| 207 | |
|
| 208 | 9× | pub fn pending(home: &Path) -> Option<Pending> { |
| 209 | 9× | serde_json::from_slice(&std::fs::read(home.join(PENDING)).ok()?).ok() |
| 210 | 9× | } |
| 211 | |
|
| 212 | 5× | fn save(home: &Path, p: &Pending) -> Result<()> { |
| 213 | 5× | let tmp = home.join(format!("{PENDING}.tmp")); |
| 214 | 5× | std::fs::write(&tmp, serde_json::to_vec_pretty(p)?)?; |
| 215 | 5× | std::fs::rename(&tmp, home.join(PENDING))?; |
| 216 | 5× | Ok(()) |
| 217 | 5× | } |
| 218 | |
|
| 219 | |
|
| 220 | 0× | fn is_self(p: &Path) -> bool { |
| 221 | 0× | let canon = |p: &Path| std::fs::canonicalize(p).ok(); |
| 222 | 0× | std::env::current_exe().ok().and_then(|me| canon(&me)).is_some_and(|me| Some(me) == canon(p)) |
| 223 | 0× | } |
| 224 | |
|
| 225 | |
|
| 226 | |
|
| 227 | |
|
| 228 | 0× | fn rename_exe(from: &Path, to: &Path) -> Result<()> { |
| 229 | 0× | if cfg!(windows) && is_self(from) { |
| 230 | 0× | let helper = beside(from, "flow.rename"); |
| 231 | 0× | std::fs::copy(from, &helper).with_context(|| format!("copying {} to rename it", from.display()))?; |
| 232 | 0× | let out = std::process::Command::new(&helper).arg("__rename").arg(from).arg(to).output(); |
| 233 | 0× | let _ = std::fs::remove_file(&helper); |
| 234 | 0× | let out = out.with_context(|| format!("starting {}", helper.display()))?; |
| 235 | 0× | if !out.status.success() { |
| 236 | 0× | bail!("{}", String::from_utf8_lossy(&out.stderr).trim()); |
| 237 | 0× | } |
| 238 | 0× | return Ok(()); |
| 239 | 0× | } |
| 240 | 0× | Ok(crate::portable::rename(from, to)?) |
| 241 | 0× | } |
| 242 | |
|
| 243 | |
|
| 244 | |
|
| 245 | |
|
| 246 | |
|
| 247 | 1× | pub fn swap(exe: &Path, staged: &Path) -> Result<()> { |
| 248 | 1× | let prev = beside(exe, PREV); |
| 249 | 1× | if cfg!(windows) { |
| 250 | 0× | let _ = std::fs::remove_file(&prev); |
| 251 | 0× | rename_exe(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?; |
| 252 | 0× | if let Err(e) = crate::portable::rename(staged, exe) { |
| 253 | 0× | let _ = crate::portable::rename(&prev, exe); |
| 254 | 0× | return Err(e).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display())); |
| 255 | 0× | } |
| 256 | 0× | return Ok(()); |
| 257 | 1× | } |
| 258 | 1× | let _ = std::fs::remove_file(&prev); |
| 259 | 1× | if std::fs::hard_link(exe, &prev).is_err() { |
| 260 | 0× | std::fs::copy(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?; |
| 261 | 1× | } |
| 262 | 1× | std::fs::rename(staged, exe).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()))?; |
| 263 | 1× | Ok(()) |
| 264 | 1× | } |
| 265 | |
|
| 266 | |
|
| 267 | 1× | pub fn restore(exe: &Path) -> Result<()> { |
| 268 | 1× | let prev = beside(exe, PREV); |
| 269 | 1× | if !prev.is_file() { |
| 270 | 0× | bail!("{} is not there to go back to", prev.display()); |
| 271 | 1× | } |
| 272 | 1× | if cfg!(windows) { |
| 273 | | |
| 274 | 0× | let failed = beside(exe, "flow.failed"); |
| 275 | 0× | let _ = std::fs::remove_file(&failed); |
| 276 | 0× | rename_exe(exe, &failed).with_context(|| format!("moving {} aside", exe.display()))?; |
| 277 | 0× | return crate::portable::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display())); |
| 278 | 1× | } |
| 279 | 1× | std::fs::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()))?; |
| 280 | 1× | Ok(()) |
| 281 | 1× | } |
| 282 | |
|
| 283 | |
|
| 284 | |
|
| 285 | |
|
| 286 | 0× | pub fn install(home: &crate::home::Home, exe: &Path, file: &Path, notice: Duration, dry_run: bool, allow_older: bool) -> Result<Installed> { |
| 287 | 0× | if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) { |
| 288 | 0× | bail!("flow.toml says [runner.update] allow = false: this runner takes no updates"); |
| 289 | 0× | } |
| 290 | 0× | if let Some(p) = pending(&home.root) { |
| 291 | 0× | bail!("the update from {} to {} is not proven yet; wait for it (or for its rollback)", p.from, p.to); |
| 292 | 0× | } |
| 293 | 0× | let from = env!("CARGO_PKG_VERSION").to_string(); |
| 294 | 0× | let staged = beside(exe, NEW); |
| 295 | 0× | let _ = std::fs::remove_file(&staged); |
| 296 | 0× | std::fs::copy(file, &staged).with_context(|| format!("staging {} as {}", file.display(), staged.display()))?; |
| 297 | 0× | crate::portable::set_mode(&staged, 0o755)?; |
| 298 | 0× | let checked = check(&staged, &home.root).and_then(|to| { |
| 299 | 0× | if older(&to, &from) && !allow_older { |
| 300 | 0× | bail!("flow {to} is older than this runner's {from} (--allow-older to go back)"); |
| 301 | 0× | } |
| 302 | 0× | Ok(to) |
| 303 | 0× | }); |
| 304 | 0× | let to = match checked { |
| 305 | 0× | Ok(v) => v, |
| 306 | 0× | Err(e) => { |
| 307 | 0× | let _ = std::fs::remove_file(&staged); |
| 308 | 0× | return Err(e); |
| 309 | | } |
| 310 | | }; |
| 311 | 0× | if dry_run { |
| 312 | 0× | let _ = std::fs::remove_file(&staged); |
| 313 | 0× | return Ok(Installed { from, to, exe: exe.to_path_buf(), told: None }); |
| 314 | 0× | } |
| 315 | 0× | if let Err(e) = swap(exe, &staged) { |
| 316 | 0× | let _ = std::fs::remove_file(&staged); |
| 317 | 0× | return Err(e); |
| 318 | 0× | } |
| 319 | 0× | let p = |
| 320 | 0× | Pending { from: from.clone(), to: to.clone(), exe: exe.to_path_buf(), at_ms: now_ms(), notice_secs: notice.as_secs(), starts: 0 }; |
| 321 | 0× | save(&home.root, &p)?; |
| 322 | 0× | log(&home.root, "installed", &from, &to, "flow runner update --from"); |
| 323 | 0× | let told = running(&home.root).filter(|pid| cfg!(not(unix)) || tell(*pid)); |
| 324 | 0× | Ok(Installed { from, to, exe: exe.to_path_buf(), told }) |
| 325 | 0× | } |
| 326 | |
|
| 327 | |
|
| 328 | | #[cfg(unix)] |
| 329 | 0× | fn tell(pid: u32) -> bool { |
| 330 | 0× | unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) == 0 } |
| 331 | 0× | } |
| 332 | |
|
| 333 | |
|
| 334 | | #[cfg(not(unix))] |
| 335 | | fn tell(_pid: u32) -> bool { |
| 336 | | false |
| 337 | | } |
| 338 | |
|
| 339 | |
|
| 340 | |
|
| 341 | | const DRAIN: &str = "drain.request"; |
| 342 | |
|
| 343 | |
|
| 344 | 2× | pub fn ask_to_drain(home: &Path) -> std::io::Result<bool> { |
| 345 | 2× | std::fs::write(home.join(DRAIN), "")?; |
| 346 | 2× | Ok(home.join(PID).is_file()) |
| 347 | 2× | } |
| 348 | |
|
| 349 | |
|
| 350 | 3× | pub fn drain_requested(home: &Path) -> bool { |
| 351 | 3× | std::fs::remove_file(home.join(DRAIN)).is_ok() |
| 352 | 3× | } |
| 353 | |
|
| 354 | |
|
| 355 | |
|
| 356 | 4× | pub fn requested(home: &Path) -> bool { |
| 357 | 4× | std::fs::remove_file(home.join(REQUEST)).is_ok() |
| 358 | 4× | } |
| 359 | |
|
| 360 | |
|
| 361 | |
|
| 362 | |
|
| 363 | |
|
| 364 | | #[cfg(unix)] |
| 365 | 1× | fn running(home: &Path) -> Option<u32> { |
| 366 | 1× | let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?; |
| 367 | 1× | let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?; |
| 368 | 1× | is_runner(&cmdline).then_some(pid) |
| 369 | 1× | } |
| 370 | |
|
| 371 | |
|
| 372 | |
|
| 373 | | #[cfg(not(unix))] |
| 374 | | fn running(home: &Path) -> Option<u32> { |
| 375 | | let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?; |
| 376 | | std::fs::write(home.join(REQUEST), pid.to_string()).ok()?; |
| 377 | | Some(pid) |
| 378 | | } |
| 379 | |
|
| 380 | |
|
| 381 | | #[cfg_attr(not(unix), allow(dead_code))] |
| 382 | 6× | fn is_runner(cmdline: &[u8]) -> bool { |
| 383 | 230× | let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).filter(|a| !a.is_empty()).collect(); |
| 384 | 6× | let Some((argv0, rest)) = args.split_first() else { return false }; |
| 385 | 39× | let name = argv0.rsplit(|b| *b == b'/').next().unwrap_or(argv0); |
| 386 | 5× | name.starts_with(b"flow") && rest.last() == Some(&&b"runner"[..]) |
| 387 | 6× | } |
| 388 | |
|
| 389 | |
|
| 390 | 3× | pub fn note_runner(home: &Path) { |
| 391 | 3× | let _ = std::fs::remove_file(home.join(REQUEST)); |
| 392 | 3× | let _ = std::fs::remove_file(home.join(DRAIN)); |
| 393 | 3× | let _ = std::fs::write(home.join(PID), std::process::id().to_string()); |
| 394 | 3× | } |
| 395 | |
|
| 396 | |
|
| 397 | 0× | pub fn forget_runner(home: &Path) { |
| 398 | 0× | if std::fs::read_to_string(home.join(PID)).is_ok_and(|p| p.trim() == std::process::id().to_string()) { |
| 399 | 0× | let _ = std::fs::remove_file(home.join(PID)); |
| 400 | 0× | } |
| 401 | 0× | } |
| 402 | |
|
| 403 | |
|
| 404 | | #[derive(Debug, PartialEq, Eq)] |
| 405 | | pub enum Start { |
| 406 | | |
| 407 | | Settled, |
| 408 | | |
| 409 | | Trial(Pending), |
| 410 | | |
| 411 | | RolledBack(Pending), |
| 412 | | } |
| 413 | |
|
| 414 | |
|
| 415 | |
|
| 416 | 6× | pub fn on_start(home: &Path) -> Result<Start> { |
| 417 | 6× | let Some(mut p) = pending(home) else { return Ok(Start::Settled) }; |
| 418 | 4× | p.starts += 1; |
| 419 | 4× | if p.starts > MAX_STARTS { |
| 420 | 1× | roll_back(home, &p, &format!("{MAX_STARTS} starts without reaching the hub"))?; |
| 421 | 1× | return Ok(Start::RolledBack(p)); |
| 422 | 3× | } |
| 423 | 3× | save(home, &p)?; |
| 424 | 3× | Ok(Start::Trial(p)) |
| 425 | 6× | } |
| 426 | |
|
| 427 | |
|
| 428 | | const NOTE: &str = "update.note"; |
| 429 | |
|
| 430 | |
|
| 431 | 2× | fn note(home: &Path, note: &str) { |
| 432 | 2× | let _ = std::fs::write(home.join(NOTE), note); |
| 433 | 2× | } |
| 434 | |
|
| 435 | |
|
| 436 | 0× | pub fn take_note(home: &Path) -> Option<String> { |
| 437 | 0× | let n = std::fs::read_to_string(home.join(NOTE)).ok()?; |
| 438 | 0× | let _ = std::fs::remove_file(home.join(NOTE)); |
| 439 | 0× | Some(n).filter(|n| !n.trim().is_empty()) |
| 440 | 0× | } |
| 441 | |
|
| 442 | |
|
| 443 | 1× | pub fn proven(home: &Path) { |
| 444 | 1× | if let Some(p) = pending(home) { |
| 445 | 1× | let _ = std::fs::remove_file(home.join(PENDING)); |
| 446 | 1× | log(home, "proven", &p.from, &p.to, "reached the hub"); |
| 447 | 1× | note(home, &format!("runs flow {} (was {}); proven", p.to, p.from)); |
| 448 | 1× | eprintln!("flow runner: flow {} proven (it reached the hub); flow {} stays as {}", p.to, p.from, beside(&p.exe, PREV).display()); |
| 449 | 1× | } |
| 450 | 1× | } |
| 451 | |
|
| 452 | |
|
| 453 | 1× | pub fn roll_back(home: &Path, p: &Pending, why: &str) -> Result<()> { |
| 454 | 1× | restore(&p.exe)?; |
| 455 | 1× | let _ = std::fs::remove_file(home.join(PENDING)); |
| 456 | 1× | log(home, "rolled back", &p.to, &p.from, why); |
| 457 | 1× | note(home, &format!("rolled back from flow {} to {}: {why}", p.to, p.from)); |
| 458 | 1× | eprintln!("flow runner: rolled back from flow {} to {} ({why})", p.to, p.from); |
| 459 | 1× | Ok(()) |
| 460 | 1× | } |
| 461 | |
|
| 462 | | #[cfg(test)] |
| 463 | | mod tests { |
| 464 | |
|
| 465 | | #[test] |
| 466 | 1× | fn a_build_from_the_swarm_is_copied_only_when_it_is_the_one_attested() { |
| 467 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 468 | 1× | let (from, to) = (dir.path().join("cas.ext4"), dir.path().join("flow-0.5.2")); |
| 469 | 1× | std::fs::write(&from, b"flow build").unwrap(); |
| 470 | 1× | let hash = blake3::hash(b"flow build").to_hex().to_string(); |
| 471 | 1× | assert!(copy_checked(&from, &to, 9, &hash).is_err(), "the wrong size"); |
| 472 | 1× | assert!(copy_checked(&from, &to, 10, &"0".repeat(64)).is_err(), "the wrong hash"); |
| 473 | 1× | assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing left behind"); |
| 474 | 1× | copy_checked(&from, &to, 10, &hash).unwrap(); |
| 475 | 1× | assert_eq!(std::fs::read(&to).unwrap(), b"flow build"); |
| 476 | 1× | } |
| 477 | | use super::*; |
| 478 | |
|
| 479 | | #[test] |
| 480 | 1× | fn versions_are_read_and_compared() { |
| 481 | 1× | assert_eq!(parse_version("flow 0.3.1 (local build)\n").as_deref(), Some("0.3.1")); |
| 482 | 1× | assert_eq!(parse_version("flow 0.10.0"), Some("0.10.0".into())); |
| 483 | 1× | assert_eq!(parse_version("oxy 0.6.0"), None); |
| 484 | 1× | assert_eq!(parse_version("flow banana"), None); |
| 485 | 1× | assert!(older("0.3.1", "0.10.0"), "by number, not by text"); |
| 486 | 1× | assert!(!older("0.3.1", "0.3.1")); |
| 487 | 1× | assert!(older("0.3", "0.3.1")); |
| 488 | 1× | } |
| 489 | |
|
| 490 | | #[test] |
| 491 | 1× | fn only_a_build_for_this_machine_passes() { |
| 492 | 1× | let me = std::fs::read(std::env::current_exe().unwrap()).unwrap(); |
| 493 | 1× | check_target(&me[..64]).unwrap(); |
| 494 | 1× | assert!(check_target(b"#!/bin/sh\necho flow 9.9.9\n").unwrap_err().to_string().contains("not an ELF")); |
| 495 | 1× | let mut other = me[..64].to_vec(); |
| 496 | 1× | other[18..20].copy_from_slice(&(if std::env::consts::ARCH == "riscv64" { 62u16 } else { 243u16 }).to_le_bytes()); |
| 497 | 1× | assert!(check_target(&other).unwrap_err().to_string().contains("another machine")); |
| 498 | 1× | } |
| 499 | |
|
| 500 | | #[test] |
| 501 | 1× | fn a_swap_keeps_the_old_build_and_three_failed_starts_bring_it_back() { |
| 502 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 503 | 1× | let (bin, home) = (dir.path().join("bin"), dir.path().join("home")); |
| 504 | 1× | std::fs::create_dir_all(&bin).unwrap(); |
| 505 | 1× | std::fs::create_dir_all(&home).unwrap(); |
| 506 | 1× | let exe = bin.join("flow"); |
| 507 | 1× | std::fs::write(&exe, "old").unwrap(); |
| 508 | 1× | std::fs::write(bin.join(NEW), "new").unwrap(); |
| 509 | 1× | swap(&exe, &bin.join(NEW)).unwrap(); |
| 510 | 1× | assert_eq!(std::fs::read_to_string(&exe).unwrap(), "new"); |
| 511 | 1× | assert_eq!(std::fs::read_to_string(bin.join(PREV)).unwrap(), "old"); |
| 512 | 1× | assert!(!bin.join(NEW).exists()); |
| 513 | |
|
| 514 | 1× | assert_eq!(on_start(&home).unwrap(), Start::Settled, "no update, nothing to do"); |
| 515 | 1× | let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 600, starts: 0 }; |
| 516 | 1× | save(&home, &p).unwrap(); |
| 517 | 3× | for n in 1..=MAX_STARTS { |
| 518 | 3× | assert_eq!(on_start(&home).unwrap(), Start::Trial(Pending { starts: n, ..p.clone() })); |
| 519 | | } |
| 520 | 1× | assert!(matches!(on_start(&home).unwrap(), Start::RolledBack(_))); |
| 521 | 1× | assert_eq!(std::fs::read_to_string(&exe).unwrap(), "old", "the previous build is back"); |
| 522 | 1× | assert!(pending(&home).is_none()); |
| 523 | 1× | let log = std::fs::read_to_string(home.join(LOG)).unwrap(); |
| 524 | 1× | assert!(log.contains("rolled back") && log.contains("0.3.2"), "{log}"); |
| 525 | 1× | } |
| 526 | |
|
| 527 | | #[test] |
| 528 | 1× | fn a_windows_build_is_checked_as_pe_and_named_beside_with_its_extension() { |
| 529 | 1× | let mut pe = vec![0u8; 0x100]; |
| 530 | 1× | pe[..2].copy_from_slice(b"MZ"); |
| 531 | 1× | pe[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); |
| 532 | 1× | pe[0x80..0x84].copy_from_slice(b"PE\0\0"); |
| 533 | 1× | pe[0x84..0x86].copy_from_slice(&0x8664u16.to_le_bytes()); |
| 534 | 1× | if std::env::consts::ARCH == "x86_64" { |
| 535 | 1× | check_pe(&pe).unwrap(); |
| 536 | 1× | } |
| 537 | 1× | pe[0x84..0x86].copy_from_slice(&0x01c4u16.to_le_bytes()); |
| 538 | 1× | assert!(check_pe(&pe).is_err(), "another machine"); |
| 539 | 1× | assert!(check_pe(b"\x7fELF and more bytes than enough for a header, really, quite a few more") |
| 540 | 1× | .unwrap_err() |
| 541 | 1× | .to_string() |
| 542 | 1× | .contains("not a Windows")); |
| 543 | 1× | assert_eq!(beside(Path::new("C:/flow/flow.exe"), PREV), Path::new("C:/flow/flow.prev.exe")); |
| 544 | 1× | assert_eq!(beside(Path::new("/usr/local/bin/flow"), NEW), Path::new("/usr/local/bin/flow.new")); |
| 545 | 1× | } |
| 546 | |
|
| 547 | | #[test] |
| 548 | 1× | fn a_drain_is_asked_by_file_once() { |
| 549 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 550 | 1× | assert!(!ask_to_drain(dir.path()).unwrap(), "no runner running"); |
| 551 | 1× | assert!(drain_requested(dir.path()) && !drain_requested(dir.path())); |
| 552 | 1× | note_runner(dir.path()); |
| 553 | 1× | assert!(ask_to_drain(dir.path()).unwrap()); |
| 554 | 1× | note_runner(dir.path()); |
| 555 | 1× | assert!(!drain_requested(dir.path()), "a starting runner clears a stale request"); |
| 556 | 1× | } |
| 557 | |
|
| 558 | | #[test] |
| 559 | 1× | fn a_request_file_asks_once() { |
| 560 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 561 | 1× | assert!(!requested(dir.path())); |
| 562 | 1× | std::fs::write(dir.path().join(REQUEST), "1").unwrap(); |
| 563 | 1× | assert!(requested(dir.path()) && !requested(dir.path()), "read once"); |
| 564 | 1× | std::fs::write(dir.path().join(REQUEST), "1").unwrap(); |
| 565 | 1× | note_runner(dir.path()); |
| 566 | 1× | assert!(!requested(dir.path()), "a starting runner clears a stale request"); |
| 567 | 1× | } |
| 568 | |
|
| 569 | | #[test] |
| 570 | 1× | fn only_a_running_runner_is_told() { |
| 571 | 1× | assert!(is_runner(b"/usr/local/bin/flow\0runner\0")); |
| 572 | 1× | assert!(is_runner(b"flow\0--home\0/srv/flow\0runner\0")); |
| 573 | 1× | assert!(!is_runner(b"flow\0runner\0update\0--from\0x\0"), "not the update command itself"); |
| 574 | 1× | assert!(!is_runner(b"/usr/bin/vim\0runner\0")); |
| 575 | 1× | assert!(!is_runner(b"")); |
| 576 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 577 | 1× | std::fs::write(dir.path().join(PID), std::process::id().to_string()).unwrap(); |
| 578 | 1× | assert_eq!(running(dir.path()), None, "this test is not a flow runner"); |
| 579 | 1× | } |
| 580 | |
|
| 581 | | #[test] |
| 582 | 1× | fn a_proven_build_stays() { |
| 583 | 1× | let dir = tempfile::tempdir().unwrap(); |
| 584 | 1× | let exe = dir.path().join("flow"); |
| 585 | 1× | std::fs::write(&exe, "new").unwrap(); |
| 586 | 1× | let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 0, starts: 1 }; |
| 587 | 1× | save(dir.path(), &p).unwrap(); |
| 588 | 1× | proven(dir.path()); |
| 589 | 1× | assert!(pending(dir.path()).is_none()); |
| 590 | 1× | assert_eq!(on_start(dir.path()).unwrap(), Start::Settled); |
| 591 | 1× | assert!(std::fs::read_to_string(dir.path().join(LOG)).unwrap().contains("proven")); |
| 592 | 1× | } |
| 593 | | } |