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