OXYGENHUB

Coverage / crates/flow/src/runner.rs 44.6%

822 of 1845 lines run, 94 of 422 functions · run #208 on main · run missed

1
//! `flow runner` (docs/m0.md §5): claim a job from OxygenHub, fetch the
2
//! repository into a cache with the job's token, write the state into a
3
//! workspace, run it in its tier, stream the log, report the receipt.
4
//! One job at a time.
5
6
use crate::home::{Home, RunnerConfig, RunnerKey};
7
use crate::{microvm, workspace};
8
use anyhow::{bail, Context, Result};
9
use flow_core::api::{Claim, ClaimRequest, Decline, Finish, LogBatch, Record, Register, Registered, RunnerInfo, MAX_RECORD_TEXT};
10
use flow_core::{scope_tree_hash, Receipt};
11
use oxy_core::hash::ChangeHash;
12
use oxy_core::repo::Repo;
13
use std::path::{Path, PathBuf};
14
use std::time::{Duration, Instant};
15
16
/// A request the hub refused (4xx). On a job's endpoints, 409 means the
17
/// job no longer runs: it was cancelled, or given up.
18
#[derive(Debug)]
19
pub struct Refused {
20
    pub code: u16,
21
    pub text: String,
22
}
23
24
impl std::fmt::Display for Refused {
250×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260×
        write!(f, "HTTP {}: {}", self.code, self.text)
270×
    }
28
}
29
30
impl std::error::Error for Refused {}
31
32
/// Whether `e` is the hub saying the job no longer runs.
333×
fn job_gone(e: &anyhow::Error) -> bool {
343×
    e.downcast_ref::<Refused>().is_some_and(|r| r.code == 409)
353×
}
36
37
/// What a job ends with when its run was cancelled: nothing is reported,
38
/// as the hub has ended it already.
39
const CANCELLED: &str = "the run was cancelled";
40
410×
fn cancelled() -> Finish {
420×
    Finish {
430×
        exit_code: None,
440×
        duration_ms: 0,
450×
        receipt: None,
460×
        signed_receipt: None,
470×
        error: Some(CANCELLED.into()),
480×
        peak_disk_mib: None,
490×
        peak_memory_mib: None,
500×
        phases: Default::default(),
510×
    }
520×
}
53
54
pub struct Hub {
55
    base: String,
56
    token: String,
57
    agent: ureq::Agent,
58
}
59
60
impl Hub {
610×
    pub fn new(cfg: &RunnerConfig) -> Result<Hub> {
620×
        let tls = oxy_core::protocol::tls_client_config(cfg.ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
630×
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
640×
        Ok(Hub { base: cfg.hub.trim_end_matches('/').to_string(), token: cfg.token.clone(), agent })
650×
    }
66
67
    /// POST to the hub. A server error (5xx) means nothing was committed,
68
    /// so it is tried again after 1, 2 and 4 seconds before giving up: a
69
    /// busy hub costs a job a few seconds, not its log lines or its claim.
708×
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
718×
        self.post_with(path, body, &RETRY_DELAYS)
728×
    }
73
7411×
    fn post_with(&self, path: &str, body: &impl serde::Serialize, delays: &[Duration]) -> Result<Option<ureq::Response>> {
7511×
        let url = format!("{}/api/v1{path}", self.base);
7616×
        let r = retrying(&url, delays, false, || {
7716×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
7816×
        })?;
796×
        Ok(if r.status() == 204 { None } else { Some(r) })
8011×
    }
81
82
    /// POST what a job leaves behind (oxygenflow#49): through a hub that is
83
    /// away for a few minutes, as while a deploy restarts it, so a job's
84
    /// declines and uploads outlast it.
851×
    fn post_patiently(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
861×
        let url = format!("{}/api/v1{path}", self.base);
871×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
881×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
891×
        })?;
901×
        Ok(if r.status() == 204 { None } else { Some(r) })
911×
    }
92
930×
    pub fn claim(&self, req: &ClaimRequest) -> Result<Option<Claim>> {
940×
        match self.post("/flow/claim", req)? {
950×
            Some(r) => Ok(Some(r.into_json()?)),
960×
            None => Ok(None),
97
        }
980×
    }
99
100
    /// Hand job `job` back, saying why this runner will not run it.
1010×
    pub fn decline(&self, job: i64, reason: &str) -> Result<()> {
1020×
        self.post_patiently(&format!("/flow/jobs/{job}/decline"), &Decline { reason: reason.into() })?;
1030×
        Ok(())
1040×
    }
105
106
    /// Hand back a job this runner holds as it leaves (oxygenflow#76): the
107
    /// hub queues it again ahead of new work for another runner.
1081×
    pub fn release(&self, job: i64, reason: &str) -> Result<()> {
1091×
        self.post_patiently(&format!("/flow/jobs/{job}/release"), &Decline { reason: reason.into() })?;
1101×
        Ok(())
1111×
    }
112
113
    /// Say this runner is there while it claims nothing: its slots are full,
114
    /// or it is draining (oxygenhub#243). Once, no retries: the next comes
115
    /// soon. A hub without the endpoint (404) is not an error.
116
    /// A ten-minute certificate for `identity`, asked with a job's token
117
    /// (keyless, oxygenhub#241), and the identity of the hub's key that
118
    /// issued it, from `/.well-known/oxyhub-key`.
1193×
    pub fn certify(
1203×
        &self,
1213×
        job_token: &str,
1223×
        identity: &oxy_core::identity::Identity,
1233×
        proof: &oxy_core::identity::Signature,
1243×
    ) -> Result<(oxy_core::cert::SignedCertificate, oxy_core::identity::Identity)> {
125
        use oxy_core::dsse::{base64, base64_decode};
1263×
        let body = serde_json::json!({
1273×
            "identity": base64(&identity.encode()),
1283×
            "proof": base64(&oxy_core::cbor::encode(&proof.to_value())),
1293×
            "scope": "seal",
130
        });
1313×
        let url = format!("{}/api/v1/keyless/certify", self.base);
1323×
        let r = self
1333×
            .agent
1343×
            .post(&url)
1353×
            .set("Authorization", &format!("Bearer {job_token}"))
1363×
            .send_json(body)
1373×
            .map_err(|e| anyhow::anyhow!("asking the hub to certify the key: {e}"))?;
1383×
        let v: serde_json::Value = r.into_json()?;
1393×
        let cert = base64_decode(v["certificate"].as_str().unwrap_or(""))
1403×
            .context("the hub's answer has no certificate")
1413×
            .and_then(|b| oxy_core::cert::SignedCertificate::decode(&b).map_err(|e| anyhow::anyhow!("{e}")))?;
1423×
        let mut bytes = Vec::new();
1433×
        std::io::Read::read_to_end(
1443×
            &mut self.agent.get(&format!("{}/.well-known/oxyhub-key", self.base)).call()?.into_reader(),
1453×
            &mut bytes,
1460×
        )?;
1473×
        let issuer = oxy_core::identity::Identity::decode(&bytes)?;
1483×
        if issuer.hash() != cert.cert.issuer || cert.verify(&issuer).is_err() {
1491×
            bail!("the certificate is not signed by the hub's published key");
1502×
        }
1512×
        if cert.cert.key_id() != identity.hash() {
1521×
            bail!("the hub certified another key");
1531×
        }
1541×
        Ok((cert, issuer))
1553×
    }
156
1570×
    pub fn heartbeat(&self) -> Result<()> {
1580×
        match self.post_with("/flow/runners/heartbeat", &serde_json::json!({}), &[]) {
1590×
            Ok(_) => Ok(()),
1600×
            Err(e) if format!("{e:#}").contains("404") => Ok(()),
1610×
            Err(e) => Err(e),
162
        }
1630×
    }
164
165
    /// The update policy for this runner and the build it should run
166
    /// (oxygenhub#322); `None` from a hub without runner updates.
1670×
    pub fn update_answer(&self) -> Result<Option<flow_core::api::UpdateAnswer>> {
1680×
        let url = format!("{}/api/v1/flow/runner/update", self.base);
1690×
        match self.agent.get(&url).set("Authorization", &format!("Bearer {}", self.token)).call() {
1700×
            Ok(r) => Ok(Some(r.into_json()?)),
1710×
            Err(ureq::Error::Status(404, _)) => Ok(None),
1720×
            Err(e) => Err(anyhow::anyhow!("{url}: {e}")),
173
        }
1740×
    }
175
176
    /// Tell the hub what this runner did about its update.
1770×
    pub fn report_update(&self, note: &str) -> Result<()> {
1780×
        self.post_with("/flow/runner/update", &flow_core::api::UpdateReport { note: note.to_string() }, &[])?;
1790×
        Ok(())
1800×
    }
181
182
    /// Download an offered build to `to`, refusing it unless its BLAKE3
183
    /// is the one the hub attests and it is the size it said.
1842×
    pub fn download_build(&self, offer: &flow_core::api::UpdateOffer, to: &Path) -> Result<()> {
185
        use std::io::{Read, Write};
1862×
        let url = format!("{}{}", self.base, offer.url);
1872×
        let r = self.agent.get(&url).timeout(Duration::from_secs(1800)).call().map_err(|e| anyhow::anyhow!("{url}: {e}"))?;
1882×
        let part = to.with_extension("partial");
1892×
        let mut out = std::fs::File::create(&part).with_context(|| format!("writing {}", part.display()))?;
1902×
        let (mut hasher, mut n, mut buf) = (blake3::Hasher::new(), 0u64, vec![0u8; 1 << 16]);
1912×
        let mut body = r.into_reader().take(offer.size + 1);
192
        loop {
1934×
            let k = body.read(&mut buf)?;
1944×
            if k == 0 {
1952×
                break;
1962×
            }
1972×
            hasher.update(&buf[..k]);
1982×
            out.write_all(&buf[..k])?;
1992×
            n += k as u64;
200
        }
2012×
        drop(out);
2022×
        let got = hasher.finalize().to_hex().to_string();
2032×
        if n != offer.size || got != offer.blake3 {
2041×
            let _ = std::fs::remove_file(&part);
2051×
            bail!("{} does not match what the hub attests ({n} bytes, BLAKE3 {}…)", offer.asset, &got[..12]);
2061×
        }
2071×
        std::fs::rename(&part, to)?;
2081×
        Ok(())
2092×
    }
210
2118×
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
2128×
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
2135×
        Ok(())
2148×
    }
215
216
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
217
    /// a blob of the job's repository and answers with its ObjectRef.
2180×
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
2190×
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
2200×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2210×
            self.agent
2220×
                .post(&url)
2230×
                .timeout(Duration::from_secs(600))
2240×
                .set("Authorization", &format!("Bearer {}", self.token))
2250×
                .set("Content-Type", "application/octet-stream")
2260×
                .send_bytes(bytes)
2270×
                .map_err(Box::new)
2280×
        })?;
2290×
        let v: serde_json::Value = r.into_json()?;
2300×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2310×
    }
232
233
    /// Keep a checkpoint of job `job` (oxygenflow#77) as its runner hands
234
    /// it back: the hub answers with its blob, which the next attempt's
235
    /// claim names.
2360×
    pub fn save_checkpoint(&self, job: i64, bytes: &[u8]) -> Result<String> {
2370×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2380×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2390×
            self.agent
2400×
                .post(&url)
2410×
                .timeout(Duration::from_secs(600))
2420×
                .set("Authorization", &format!("Bearer {}", self.token))
2430×
                .set("Content-Type", "application/octet-stream")
2440×
                .send_bytes(bytes)
2450×
                .map_err(Box::new)
2460×
        })?;
2470×
        let v: serde_json::Value = r.into_json()?;
2480×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2490×
    }
250
251
    /// The checkpoint an earlier attempt of job `job` saved (oxygenflow#77),
252
    /// which the caller checks against the blob its claim names.
2530×
    pub fn checkpoint(&self, job: i64) -> Result<Vec<u8>> {
2540×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2550×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2560×
            self.agent
2570×
                .get(&url)
2580×
                .timeout(Duration::from_secs(600))
2590×
                .set("Authorization", &format!("Bearer {}", self.token))
2600×
                .call()
2610×
                .map_err(Box::new)
2620×
        })?;
2630×
        let mut bytes = Vec::new();
2640×
        std::io::Read::read_to_end(&mut std::io::Read::take(r.into_reader(), crate::checkpoint::MAX_BYTES as u64 + 1), &mut bytes)?;
2650×
        Ok(bytes)
2660×
    }
267
268
    /// Input `index` of job `job` (oxygenflow#58): the bytes of the
269
    /// producing job's artifact, which the caller checks against the blob the
270
    /// claim names.
2710×
    pub fn input(&self, job: i64, index: usize) -> Result<Vec<u8>> {
2720×
        let url = format!("{}/api/v1/flow/jobs/{job}/inputs/{index}", self.base);
2730×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2740×
            self.agent
2750×
                .get(&url)
2760×
                .timeout(Duration::from_secs(600))
2770×
                .set("Authorization", &format!("Bearer {}", self.token))
2780×
                .call()
2790×
                .map_err(Box::new)
2800×
        })?;
2810×
        let mut bytes = Vec::new();
2820×
        let mut reader = r.into_reader();
2830×
        std::io::Read::read_to_end(&mut std::io::Read::take(&mut reader, MAX_INPUT_BYTES as u64 + 1), &mut bytes)?;
2840×
        if bytes.len() > MAX_INPUT_BYTES {
2850×
            bail!("larger than {} MiB", MAX_INPUT_BYTES >> 20);
2860×
        }
2870×
        Ok(bytes)
2880×
    }
289
290
    /// Upload file `path` of report `name` of job `job` (oxygenhub#127);
291
    /// the hub keeps it as a blob and answers with its ObjectRef. The
292
    /// report's manifest follows through [`Hub::artifact`].
2930×
    pub fn report_file(&self, job: i64, name: &str, path: &str, bytes: &[u8]) -> Result<String> {
2940×
        let url = format!("{}/api/v1/flow/jobs/{job}/reports/{name}/files", self.base);
2950×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2960×
            self.agent
2970×
                .post(&url)
2980×
                .timeout(Duration::from_secs(600))
2990×
                .set("Authorization", &format!("Bearer {}", self.token))
3000×
                .set("Content-Type", "application/octet-stream")
3010×
                .set("X-Flow-Report-Path", path)
3020×
                .send_bytes(bytes)
3030×
                .map_err(Box::new)
3040×
        })?;
3050×
        let v: serde_json::Value = r.into_json()?;
3060×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
3070×
    }
308
309
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
310
    /// cannot be reached or fails (5xx), try again after `first_wait`,
311
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
312
    /// already, say) is final. A result lost here leaves the job running
313
    /// on the hub until its time limit.
3142×
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
3152×
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
3162×
        let deadline = std::time::Instant::now() + patience;
3172×
        let mut wait = first_wait;
318
        loop {
3196×
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
3201×
                Ok(_) => return Ok(()),
3215×
                Err(ureq::Error::Status(code, r)) if code < 500 => {
3221×
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
323
                }
3244×
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
3250×
                Err(e) => e.to_string(),
326
            };
3274×
            if std::time::Instant::now() + wait > deadline {
3280×
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
3294×
            }
3304×
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
3314×
            std::thread::sleep(wait);
3324×
            wait = (wait * 2).min(Duration::from_secs(60));
333
        }
3342×
    }
335
}
336
337
/// How long a runner keeps trying to report a job's end.
338
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
339
340
/// Where a job's result waits until the hub has it, so a runner that
341
/// restarts still reports it.
3420×
fn pending_path(home: &Home, job: i64) -> PathBuf {
3430×
    home.root.join("pending").join(format!("{job}.json"))
3440×
}
345
346
/// Report `f`, keeping it on disk until the hub has it.
3470×
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
3480×
    let path = pending_path(home, job);
3490×
    let kept = std::fs::create_dir_all(path.parent().unwrap())
3500×
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
3510×
        .is_ok();
3520×
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
3530×
        Ok(()) => {}
3540×
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
355
    }
3560×
    if kept {
3570×
        let _ = std::fs::remove_file(&path);
3580×
    }
3590×
}
360
361
/// Results a previous run of the runner could not report, to send again.
3620×
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
3630×
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
3640×
        return Vec::new();
365
    };
3660×
    dir.filter_map(|e| {
3670×
        let p = e.ok()?.path();
3680×
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
3690×
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
3700×
        Some((job, f))
3710×
    })
3720×
    .collect()
3730×
}
374
375
/// `flow runner register`: exchange a one-time registration token from
376
/// the hub for this runner's credential, binding the runner's signing key,
377
/// and keep hub, credential and name in runner.toml.
3781×
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
3791×
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
3800×
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
3811×
    }
3821×
    let key = home.runner_key(name)?;
3831×
    let hub = hub.trim_end_matches('/').to_string();
3841×
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
3851×
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
3861×
    let req = Register {
3871×
        token: token.trim().to_string(),
3881×
        name: name.to_string(),
3891×
        identity: hex::encode(key.identity.encode()),
3901×
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
3911×
    };
3921×
    let url = format!("{hub}/api/v1/flow/runners/register");
3931×
    let got: Registered = match agent.post(&url).send_json(&req) {
3941×
        Ok(r) => r.into_json()?,
3950×
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
3960×
        Err(e) => bail!("{url}: {e}"),
397
    };
3981×
    let mut text = format!(
399
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
400
        got.credential, got.name
401
    );
4021×
    if let Some(ca) = &ca {
4030×
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
4041×
    }
4051×
    if !labels.is_empty() {
4061×
        text.push_str(&format!("labels = {labels:?}\n"));
4071×
    }
4081×
    let path = home.root.join(crate::home::RUNNER_TOML);
409
    {
410
        use std::io::Write;
4111×
        let tmp = path.with_extension("toml.tmp");
4121×
        let mut f = crate::portable::private(std::fs::OpenOptions::new().write(true).create(true).truncate(true)).open(&tmp)?;
4131×
        f.write_all(text.as_bytes())?;
4141×
        f.sync_all()?;
4151×
        std::fs::rename(&tmp, &path)?;
416
    }
4171×
    Ok(got)
4181×
}
419
420
/// Waits before trying a hub request again after a server error.
421
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
422
423
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
424
/// all, longer than a hub takes to restart.
425
/// Check an input's bytes against the blob the producing job's receipt
426
/// names, then write them at its path under `tree` (the workspace's `/src`).
4276×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
4286×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
429
    else {
4304×
        bail!("path {:?} is not a clean path under /src", i.path);
431
    };
4322×
    let blob = Repo::blob_ref(bytes);
4332×
    if blob.to_hex() != i.blob {
4341×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
4351×
    }
4361×
    let dest = tree.join(rel);
4371×
    if let Some(dir) = dest.parent() {
4381×
        std::fs::create_dir_all(dir)?;
4390×
    }
4401×
    std::fs::write(&dest, bytes)?;
4411×
    Ok(blob.0)
4426×
}
443
444
/// The largest input a job takes: the hub's artifact limit.
445
pub const MAX_INPUT_BYTES: usize = 512 << 20;
446
447
const PATIENT_DELAYS: [Duration; 15] = {
448
    let mut d = [Duration::from_secs(15); 15];
449
    d[0] = Duration::from_secs(1);
450
    d[1] = Duration::from_secs(2);
451
    d[2] = Duration::from_secs(4);
452
    d[3] = Duration::from_secs(8);
453
    d
454
};
455
456
/// Send a request until the hub answers, waiting `delays` in turn after a
457
/// server error (5xx: nothing was committed) and, when `connection`, after
458
/// the hub could not be reached at all. A refusal (4xx) is final, as a
459
/// [`Refused`] the caller can look at.
46014×
fn retrying(
46114×
    url: &str,
46214×
    delays: &[Duration],
46314×
    connection: bool,
46414×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
46514×
) -> Result<ureq::Response> {
46614×
    let mut delays = delays.iter();
467
    loop {
46823×
        let why = match send().map_err(|e| *e) {
4698×
            Ok(r) => return Ok(r),
4709×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4712×
                let text = r.into_string().unwrap_or_default();
4722×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
473
            }
4747×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4753×
            Err(e) if connection => e.to_string(),
4763×
            Err(e) => bail!("{url}: {e}"),
477
        };
47810×
        match delays.next() {
4799×
            Some(d) => std::thread::sleep(*d),
4801×
            None => bail!("{url}: {why}"),
481
        }
482
    }
48314×
}
484
485
/// What the runner may run at once (flow.toml `[runner]`): at most
486
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
487
#[derive(Debug, Default, PartialEq, Eq)]
488
pub struct Budget {
489
    pub max_jobs: usize,
490
    pub memory_mib: Option<u32>,
491
    pub cpus: Option<u32>,
492
}
493
494
/// What is in use now.
495
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
496
pub struct Used {
497
    pub jobs: usize,
498
    pub memory_mib: u32,
499
    pub cpus: u32,
500
}
501
502
impl Budget {
5030×
    pub fn of(cfg: &RunnerConfig) -> Budget {
5040×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
5050×
    }
506
507
    /// The room to ask the hub for, or `None` when no job more can start.
508
    /// A lone job may use the whole budget even if it asks for more, so a
509
    /// large sandbox is never starved.
5107×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
5117×
        if used.jobs >= self.max_jobs {
5122×
            return None;
5135×
        }
5145×
        if used.jobs == 0 {
5152×
            return Some((None, None));
5163×
        }
5173×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
5183×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
5193×
        if mem == Some(0) || cpus == Some(0) {
5201×
            return None;
5212×
        }
5222×
        Some((mem, cpus))
5237×
    }
524
}
525
526
/// The isolation tiers this machine can honour now (spec §11.1): the
527
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
528
/// flow.toml pins Firecracker; the syscall tier when this binary may use
529
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
530
/// `Err` says why there are none; the reasons for missing tiers come back
531
/// with the ones there are.
5323×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
5333×
    let mut have = Vec::new();
5343×
    let mut missing = Vec::new();
5353×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
5363×
    match (kvm, home.config.microvm.is_some()) {
5373×
        _ if !cfg!(target_os = "linux") => missing.push("microvm: the tier runs only on Linux (Firecracker and KVM)".to_string()),
5380×
        (Ok(_), true) => have.push("microvm".to_string()),
5390×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
5403×
        (Err(e), _) => missing.push(format!(
541
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
542
        )),
543
    }
5443×
    match crate::syscall::available() {
5450×
        Ok(()) => have.push("syscall".to_string()),
5463×
        Err(e) => missing.push(format!("syscall: {e}")),
547
    }
548
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5493×
    have.push("wasm".to_string());
5503×
    if have.is_empty() {
5510×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5523×
    }
5533×
    Ok((have, missing))
5543×
}
555
556
/// Fetch `claim`'s image from the hub when this home lacks it
557
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
558
/// leaves it missing, and the preflight declines the job as before.
5590×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) -> Option<u64> {
5600×
    let hash = &claim.sandbox.rootfs;
5610×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5620×
        return None;
5630×
    }
5640×
    let note = |text: String| {
5650×
        eprintln!("job {}: {text}", claim.job_id);
5660×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5670×
    };
568
    // One fetch of an image at a time: two jobs wanting it wait for one.
569
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5700×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5710×
    if home.rootfs(hash).is_file() {
5720×
        return None;
5730×
    }
5740×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5750×
        Ok(c) => c,
5760×
        Err(e) => {
5770×
            note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12]));
5780×
            return None;
579
        }
580
    };
5810×
    let fetching = Instant::now();
5820×
    let fetched = match swarm {
5830×
        Some(sw) => {
5840×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5850×
            sw.fetch(home, hash)
586
        }
587
        None => {
5880×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
5890×
            client.fetch(home, hash)
590
        }
591
    };
5920×
    let took = fetching.elapsed().as_millis() as u64;
5930×
    match fetched {
5940×
        Ok(Some(m)) => note(format!(
595
            "image {}: fetched {} chunks, {}{} in {:.1} s",
5960×
            &hash[..12],
597
            m.chunks,
5980×
            crate::images::human(m.bytes),
5990×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
6000×
            m.elapsed.as_secs_f64()
601
        )),
6020×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
6030×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
604
    }
6050×
    Some(took)
6060×
}
607
608
/// Why this runner cannot run `claim` now (spec §11.5), checked before
609
/// anything is fetched: the tier, the architecture, the image and the
610
/// memory. The hub chose it from what the runner last said, which may be
611
/// out of date.
6120×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6130×
    let sb = &claim.sandbox;
6140×
    match sb.runtime {
615
        flow_core::Runtime::Microvm => {
6160×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6170×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6180×
            }
6190×
            if home.config.microvm.is_none() {
6200×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6210×
            }
622
        }
623
        flow_core::Runtime::Syscall => {
6240×
            if let Err(e) = crate::syscall::available() {
6250×
                return Some(format!("the syscall tier cannot run here: {e}"));
6260×
            }
627
        }
628
        // No image and no architecture: only the memory matters.
629
        flow_core::Runtime::Wasm => {
6300×
            return available_memory_mib()
6310×
                .filter(|free| *free < u64::from(sb.memory_mib))
6320×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
633
        }
634
    }
6350×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6360×
}
637
638
/// What stops `sb` running on this home's images, on a machine of
639
/// architecture `here` with `free_mib` of memory free.
6408×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6418×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6421×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6437×
    }
6447×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6457×
    let image = home.rootfs(&sb.rootfs);
6467×
    if !image.is_file() {
6471×
        return Some(format!("rootfs {short} is not on this runner"));
6486×
    }
6496×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6502×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6514×
    }
6524×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6531×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6543×
    }
6553×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6561×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6572×
    }
6582×
    None
6598×
}
660
661
/// The memory to claim with: the budget's room, never more than the host
662
/// has free now. An idle runner's budget is unlimited (a lone job may use
663
/// it all), so without this it was offered sandboxes it then declined for
664
/// want of memory, one after another, having fetched their images first
665
/// (an 8 GiB job on a 7 GB machine).
6665×
fn claim_memory(room: Option<u32>, host_free_mib: Option<u64>) -> Option<u32> {
6675×
    match (room, host_free_mib) {
6682×
        (Some(r), Some(h)) => Some(r.min(u32::try_from(h).unwrap_or(u32::MAX))),
6691×
        (None, Some(h)) => Some(u32::try_from(h).unwrap_or(u32::MAX)),
6702×
        (room, None) => room,
671
    }
6725×
}
673
674
/// `MemAvailable` from /proc/meminfo, in MiB.
6750×
fn available_memory_mib() -> Option<u64> {
6760×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6770×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6780×
    Some(kib / 1024)
6790×
}
680
6810×
pub fn serve(home: &Home) -> Result<()> {
6820×
    drain_on_stop();
6830×
    crate::update::note_runner(&home.root);
684
    // `flow runner update` swapped a new build in and asks this one to
685
    // leave with the notice it gave (#85).
686
    #[cfg(unix)]
6870×
    {
6880×
        let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
6890×
        unsafe { libc::signal(libc::SIGUSR1, handler) };
6900×
    }
6910×
    if let Some(p) = crate::update::pending(&home.root) {
692
        // On trial: a build that does not reach the hub in time goes back.
6930×
        let root = home.root.clone();
6940×
        std::thread::spawn(move || {
6950×
            std::thread::sleep(crate::update::PROVE_WITHIN);
6960×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
6970×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
6980×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
6990×
                    std::process::exit(1);
7000×
                }
7010×
            }
7020×
        });
7030×
    }
7040×
    let served = serve_until_drained(home);
7050×
    crate::update::forget_runner(&home.root);
706
    // Left for a new build: on Windows, end as a failure, so a Task
707
    // Scheduler task set to restart on failure starts it (systemd's
708
    // Restart=always starts it after a clean exit).
7090×
    if cfg!(windows) && served.is_ok() && LEFT_FOR_UPDATE.load(std::sync::atomic::Ordering::SeqCst) {
7100×
        eprintln!("flow runner: left for the new build; exiting 75 so it is started");
7110×
        std::process::exit(75);
7120×
    }
7130×
    served
7140×
}
715
716
/// Set once the runner leaves for a new build.
717
static LEFT_FOR_UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
718
719
/// Set by SIGUSR1: a new build is in place; leave for it.
720
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
721
722
#[cfg(unix)]
7230×
extern "C" fn on_update(_: libc::c_int) {
7240×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
7250×
}
726
727
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
728
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
729
/// it holds are done and reported. It may be started again afterwards.
7300×
pub fn serve_embedded(home: &Home) -> Result<()> {
7310×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
7320×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
7330×
    serve_until_drained(home)
7340×
}
735
736
/// A departure ([`leave_within`]): why, and when the runner must be gone.
737
#[derive(Clone, Debug)]
738
struct Leave {
739
    reason: String,
740
    by: Instant,
741
}
742
743
/// Set once the runner is leaving: a job whose expected rest fits before
744
/// the deadline finishes; the others are stopped and handed back
745
/// (oxygenflow#76).
746
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
747
7480×
fn leaving() -> Option<String> {
7490×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7500×
}
751
752
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
753
/// more, stop the jobs it holds and hand them back to the hub, which queues
754
/// them ahead of new work for another runner (oxygenflow#76), then return.
755
/// For a departure with no time to finish: a phone off the allowed network.
7560×
pub fn leave(reason: &str) {
7570×
    leave_within(reason, Duration::ZERO);
7580×
}
759
760
/// [`leave`], with `notice`: a job the hub expects to finish within it
761
/// (the claim's `expected_ms`, less the time it has run) finishes and is
762
/// reported; the others, and any still running when the notice is up, are
763
/// handed back. For a phone taken off charge, a spot reclaim.
7640×
pub fn leave_within(reason: &str, notice: Duration) {
7650×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7660×
    stop();
7670×
}
768
769
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
770
/// more, finish and report what it holds, then return (oxygenflow#76's
771
/// drain, for a phone taken off charge or off the allowed network).
7721×
pub fn stop() {
7731×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7741×
}
775
7760×
fn serve_until_drained(home: &Home) -> Result<()> {
7770×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
778
    // A runner offers only what it can run: a machine without KVM claims
779
    // nothing rather than taking MicroVM jobs and failing them (#36).
7800×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7810×
    for why in &missing {
7820×
        eprintln!("flow runner: not offering {why}");
7830×
    }
7840×
    let hub = Hub::new(&cfg)?;
7850×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
7860×
    let budget = Budget::of(&cfg);
7870×
    let key = home.runner_key(&name)?;
788
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
789
    // peers still runs jobs, fetching images from the hub alone.
7900×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
7910×
        eprintln!("flow runner: not joining the swarm: {e:#}");
7920×
        None
7930×
    });
7940×
    eprintln!(
795
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
796
        cfg.hub,
797
        budget.max_jobs,
7980×
        runtimes.join(", "),
7990×
        key.identity.hash().to_hex()
800
    );
8010×
    if let Some(addr) = &cfg.metrics {
8020×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
8030×
    }
804
    // The manifests of images held here that the hub keeps none of, so
805
    // peers in this runner's site can fetch them without anyone pushing
806
    // them (oxygenflow#94): at start and every ten minutes, which also
807
    // catches an image imported while it runs. Only a runner that serves
808
    // its peers has anything to offer.
8090×
    if swarm.is_some() {
8100×
        let (root, cfg) = (home.root.clone(), cfg.clone());
8110×
        std::thread::spawn(move || loop {
8120×
            let offered = Home::locate(Some(&root))
8130×
                .and_then(|home| crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref())?.offer_held(&home));
8140×
            match offered {
8150×
                Ok(0) => {}
8160×
                Ok(n) => eprintln!("flow runner: sent the hub the manifests of {n} image(s) only runners hold"),
8170×
                Err(e) => eprintln!("flow runner: offering held images: {e:#}"),
818
            }
8190×
            std::thread::sleep(Duration::from_secs(600));
820
        });
8210×
    }
8220×
    let used = std::sync::Mutex::new(Used::default());
8230×
    let mut idle = Duration::from_secs(2);
8240×
    let pending = report_pending(home);
825
    // The jobs held now, told to the hub at each claim so it can end the
826
    // ones this runner lost: a job is held from its claim until its result
827
    // is reported.
8280×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
8290×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
8300×
    std::thread::scope(|scope| {
8310×
        for (job, f) in pending {
8320×
            let (hub, held) = (&hub, &held);
8330×
            scope.spawn(move || {
8340×
                eprintln!("job {job}: reporting the result kept from before the restart");
8350×
                report_finish(home, hub, job, &f);
8360×
                held.lock().unwrap().remove(&job);
8370×
            });
838
        }
839
        // The speed (spec §11.1): measured now, and again every 15 minutes
840
        // while no job runs, so a job never shares the CPU with it.
8410×
        let measure = || {
8420×
            let (speed, ms) = crate::facts::bench();
8430×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
8440×
            speed
8450×
        };
8460×
        let mut speed = measure();
8470×
        let mut benched = Instant::now();
8480×
        let mut said_draining = false;
849
        // When the hub last heard from us (oxygenhub#243): a claim, or a
850
        // heartbeat while there is no room to claim.
8510×
        let mut heard = Instant::now();
8520×
        let beat = |heard: &mut Instant| {
8530×
            if heard.elapsed() >= HUB_HEARTBEAT {
8540×
                if let Err(e) = hub.heartbeat() {
8550×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8560×
                }
8570×
                *heard = Instant::now();
8580×
            }
8590×
        };
8600×
        let mut on_trial = crate::update::pending(&home.root).is_some();
861
        // Runner updates (oxygenhub#322): asked of the hub once it has
862
        // answered a claim, then every 15 minutes.
8630×
        let mut update_asked: Option<Instant> = None;
8640×
        let mut update_said = String::new();
865
        loop {
8660×
            if !stopping() && crate::update::drain_requested(&home.root) {
8670×
                eprintln!("flow runner {name}: asked to drain (flow runner drain)");
8680×
                stop();
8690×
            }
8700×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) || crate::update::requested(&home.root) {
8710×
                let p = crate::update::pending(&home.root);
8720×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8730×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8740×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8750×
                LEFT_FOR_UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
8760×
                leave_within(&format!("updating to {to}"), notice);
8770×
            }
878
            // Draining (oxygenflow#50): told to stop, claim nothing more and
879
            // stop once every job held is done and reported.
8800×
            if stopping() {
8810×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8820×
                if jobs == 0 && holding == 0 {
8830×
                    eprintln!("flow runner {name}: drained, stopping");
8840×
                    break;
8850×
                }
8860×
                if !said_draining {
8870×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
8880×
                    said_draining = true;
8890×
                }
8900×
                beat(&mut heard);
8910×
                std::thread::sleep(Duration::from_millis(500));
8920×
                continue;
8930×
            }
8940×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
8950×
                speed = measure();
8960×
                benched = Instant::now();
8970×
            }
8980×
            let room = budget.room(*used.lock().unwrap());
8990×
            let Some((free_memory_mib, free_cpus)) = room else {
9000×
                beat(&mut heard);
9010×
                std::thread::sleep(Duration::from_millis(500));
9020×
                continue;
903
            };
9040×
            heard = Instant::now();
9050×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
9060×
            let req = ClaimRequest {
9070×
                runner: name.clone(),
9080×
                runtimes: runtimes.clone(),
9090×
                free_memory_mib: claim_memory(free_memory_mib, available_memory_mib()),
9100×
                free_cpus,
9110×
                info: Some(RunnerInfo {
9120×
                    version: env!("OXY_VERSION_LONG").into(),
9130×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
9140×
                }),
915
                // Read each time: an image imported while the runner runs counts.
9160×
                images: Some(home.images()),
9170×
                image_archs: Some(home.image_archs()),
9180×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
919
                fetches_images: true,
9200×
                facts: Some(crate::facts::now(home, Some(speed))),
9210×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
9220×
                caches: Some(cache_times.keys().cloned().collect()),
9230×
                cache_times: Some(cache_times),
924
            };
9250×
            let answer = hub.claim(&req);
9260×
            if on_trial && answer.is_ok() {
9270×
                crate::update::proven(&home.root);
9280×
                on_trial = false;
9290×
            }
9300×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
9310×
                update_asked = Some(Instant::now());
9320×
                if let Some(note) = crate::update::take_note(&home.root) {
9330×
                    let _ = hub.report_update(&note);
9340×
                }
9350×
                consider_update(home, &hub, &mut update_said);
9360×
            }
9370×
            match answer {
9380×
                Ok(Some(claim)) => {
9390×
                    idle = Duration::from_secs(2);
9400×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9410×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
9420×
                    {
9430×
                        let mut u = used.lock().unwrap();
9440×
                        u.jobs += 1;
9450×
                        u.memory_mib += mem;
9460×
                        u.cpus += cpus;
9470×
                    }
9480×
                    held.lock().unwrap().insert(claim.job_id);
9490×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
9500×
                    scope.spawn(move || {
9510×
                        let id = claim.job_id;
9520×
                        let image_ms = fetch_image(home, hub, cfg, swarm, &claim);
9530×
                        if let Some(why) = preflight(home, &claim) {
9540×
                            eprintln!("job {id}: declined: {why}");
9550×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9560×
                            if let Err(e) = hub.decline(id, &why) {
9570×
                                eprintln!("job {id}: decline: {e:#}");
9580×
                            }
9590×
                            held.lock().unwrap().remove(&id);
9600×
                            let mut u = used.lock().unwrap();
9610×
                            u.jobs -= 1;
9620×
                            u.memory_mib -= mem;
9630×
                            u.cpus -= cpus;
9640×
                            return;
9650×
                        }
9660×
                        eprintln!(
967
                            "job {id}: {} {} on {}",
968
                            claim.repo,
969
                            claim.job.name,
9700×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
971
                        );
9720×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9730×
                        let finish = run_claim(home, hub, cfg, key, &claim, image_ms).unwrap_or_else(|e| Finish {
9740×
                            exit_code: None,
975
                            duration_ms: 0,
9760×
                            receipt: None,
9770×
                            signed_receipt: None,
9780×
                            error: Some(format!("{e:#}")),
9790×
                            peak_disk_mib: None,
9800×
                            peak_memory_mib: None,
9810×
                            phases: Default::default(),
9820×
                        });
9830×
                        eprintln!(
984
                            "job {id}: exit {:?}{}",
985
                            finish.exit_code,
9860×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
987
                        );
9880×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
9890×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
9900×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
9910×
                        match leaving() {
992
                            // Stopped as the runner leaves: another runner takes it.
9930×
                            Some(why) if cancelled => {
9940×
                                eprintln!("job {id}: handed back: {why}");
9950×
                                if let Err(e) = hub.release(id, &why) {
9960×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
9970×
                                }
998
                            }
9990×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
10000×
                            _ => {}
1001
                        }
10020×
                        held.lock().unwrap().remove(&id);
10030×
                        let mut u = used.lock().unwrap();
10040×
                        u.jobs -= 1;
10050×
                        u.memory_mib -= mem;
10060×
                        u.cpus -= cpus;
10070×
                    });
1008
                }
10090×
                Ok(None) => std::thread::sleep(idle),
10100×
                Err(e) => {
10110×
                    eprintln!("claim: {e:#}");
10120×
                    std::thread::sleep(idle);
10130×
                    idle = (idle * 2).min(Duration::from_secs(60));
10140×
                }
1015
            }
1016
        }
10170×
        Ok(())
10180×
    })
10190×
}
1020
1021
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
1022
/// happened goes to its log, and a failure only means the next attempt
1023
/// starts again.
1024
#[allow(clippy::too_many_arguments)]
10250×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
10260×
    if !dir_tier {
10270×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
10280×
        return;
10290×
    }
10300×
    let dirs: Vec<(String, PathBuf)> = job
10310×
        .checkpoints
10320×
        .iter()
10330×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
10340×
        .collect();
10350×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
10360×
        Ok((blob, n)) => {
10370×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
1038
        }
10390×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
1040
    }
10410×
}
1042
1043
/// How many times the runner was told to stop (SIGTERM or SIGINT).
1044
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1045
10461×
extern "C" fn on_stop(_: libc::c_int) {
1047
    // A second stop means now: only async-signal-safe calls here.
10481×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
10490×
        unsafe { libc::_exit(143) };
10501×
    }
10511×
}
1052
1053
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
1054
/// so restarting a runner never kills the job it runs: the unit's
1055
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
10560×
fn drain_on_stop() {
10570×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10580×
    unsafe {
10590×
        libc::signal(libc::SIGTERM, handler);
10600×
        libc::signal(libc::SIGINT, handler);
10610×
    }
10620×
}
1063
10643×
fn stopping() -> bool {
10653×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10663×
}
1067
1068
/// Batches records to the hub every second (or every 200 lines). A quiet
1069
/// job's sink still asks the hub every few seconds whether the job runs,
1070
/// with an empty batch; once the hub answers 409 the job is not wanted.
1071
struct LogSink<'a> {
1072
    hub: &'a Hub,
1073
    job: i64,
1074
    buf: Vec<Record>,
1075
    last: Instant,
1076
    gone: bool,
1077
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1078
    /// handed back, unless its expected rest fits the notice.
1079
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1080
    /// When the job started, and how long the hub expects it to take.
1081
    started: Instant,
1082
    expected: Option<Duration>,
1083
}
1084
1085
/// The most log lines sent at once, as a busy job's sink flushes them.
1086
const BATCH: usize = 200;
1087
1088
/// The most log lines kept while the hub cannot be reached.
1089
const MAX_UNSENT: usize = 50_000;
1090
1091
/// How often a quiet job asks whether it was cancelled.
1092
const HEARTBEAT: Duration = Duration::from_secs(5);
1093
1094
impl microvm::Sink for LogSink<'_> {
10951×
    fn record(&mut self, r: Record) {
10961×
        self.push(r)
10971×
    }
1098
109910×
    fn cancelled(&mut self) -> bool {
110010×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
110110×
        if let Some(l) = leave {
1102
            // Finished if what is left of it fits the notice; else handed
1103
            // back as the runner leaves, what the job said so far first.
11045×
            let now = Instant::now();
11055×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
11065×
            if !fits || now >= l.by {
11074×
                self.flush();
11084×
                return true;
11091×
            }
11105×
        }
11116×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
11122×
            self.send();
11134×
        }
11146×
        self.gone
111510×
    }
1116
}
1117
1118
impl LogSink<'_> {
11191×
    fn push(&mut self, mut r: Record) {
11201×
        if self.gone {
11211×
            return;
11220×
        }
11230×
        if r.text.len() > MAX_RECORD_TEXT {
11240×
            let mut cut = MAX_RECORD_TEXT;
11250×
            while !r.text.is_char_boundary(cut) {
11260×
                cut -= 1;
11270×
            }
11280×
            r.text.truncate(cut);
11290×
        }
11300×
        self.buf.push(r);
11310×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
11320×
            self.flush();
11330×
        }
11341×
    }
1135
11365×
    fn flush(&mut self) {
11375×
        if !self.buf.is_empty() {
11381×
            self.send();
11394×
        }
11405×
        self.last = Instant::now();
11415×
    }
1142
1143
    /// Send what is buffered, even nothing, in batches of at most
1144
    /// `BATCH` lines.
11456×
    fn send(&mut self) {
1146
        loop {
11478×
            if self.gone {
11480×
                return;
11498×
            }
11508×
            let n = self.buf.len().min(BATCH);
11518×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
11528×
            match self.hub.log(self.job, batch.clone()) {
11535×
                Ok(()) => {}
11543×
                Err(e) if job_gone(&e) => self.gone = true,
11552×
                Err(e) => {
1156
                    // The hub is away (a restart, say): keep the lines for
1157
                    // the next batch, up to a bound, so the log loses none
1158
                    // (oxygenflow#49).
11592×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11602×
                    let mut kept = batch;
11612×
                    kept.append(&mut self.buf);
11622×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11632×
                    if over > 0 {
11641×
                        kept.drain(..over);
11651×
                        kept.insert(
11661×
                            0,
11671×
                            Record {
11681×
                                t: 0,
11691×
                                stream: "flow".into(),
11701×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11711×
                            },
11721×
                        );
11731×
                    }
11742×
                    self.buf = kept;
11752×
                    break;
1176
                }
1177
            }
11786×
            if self.buf.is_empty() {
11794×
                break;
11802×
            }
1181
        }
11826×
        self.last = Instant::now();
11836×
    }
1184
}
1185
1186
/// How often a runner with no room to claim tells the hub it is there:
1187
/// well inside the hub's 90 s before it shows a runner offline.
1188
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1189
1190
/// How often a runner asks the hub whether it should run another build.
1191
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1192
1193
/// Notice a runner gives itself to leave for an update the hub offered.
1194
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1195
1196
/// Ask the hub for this runner's update, and act on it: download the build
1197
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1198
/// install it, or for a dry run say what would happen. What it did goes to
1199
/// the hub once per outcome (`said`).
12000×
fn consider_update(home: &Home, hub: &Hub, said: &mut String) {
12010×
    let answer = match hub.update_answer() {
12020×
        Ok(Some(a)) => a,
12030×
        Ok(None) => return,
12040×
        Err(e) => {
12050×
            eprintln!("flow runner: asking for an update: {e:#}");
12060×
            return;
1207
        }
1208
    };
12090×
    let Some(offer) = answer.offer else { return };
12100×
    let mut say = |note: String| {
12110×
        if *said != note {
12120×
            eprintln!("flow runner: {note}");
12130×
            if let Err(e) = hub.report_update(&note) {
12140×
                eprintln!("flow runner: telling the hub: {e:#}");
12150×
            }
12160×
            *said = note;
12170×
        }
12180×
    };
12190×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
12200×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
12210×
    }
12220×
    let dir = home.root.join("updates");
12230×
    let file = dir.join(format!("flow-{}", offer.version));
12240×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
12250×
    if !fresh {
12260×
        if let Err(e) = std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| hub.download_build(&offer, &file)) {
12270×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
12280×
        }
12290×
    }
12300×
    let exe = match std::env::current_exe() {
12310×
        Ok(e) => e,
12320×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1233
    };
12340×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
12350×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
12360×
        Ok(done) => {
12370×
            let _ = std::fs::remove_file(&file);
12380×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1239
        }
12400×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1241
    }
12420×
}
1243
1244
/// Held while a job takes its cache disks and images its workspace (see
1245
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1246
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1247
1248
/// Held while the first clone of any repository passes its token through
1249
/// the process environment.
1250
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1251
1252
/// One lock per cached repository: fetches into it, and exports from it,
1253
/// never overlap, while jobs of other repositories go on. A slow repository
1254
/// (one kept in a bucket, say) once held every job on the runner waiting
1255
/// behind a single global lock.
12560×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1257
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1258
        std::sync::OnceLock::new();
12590×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
12600×
    locks.entry(name.to_string()).or_default().clone()
12610×
}
1262
1263
/// Seconds, to one decimal place, for the job's log.
12640×
fn secs(d: std::time::Duration) -> String {
12650×
    format!("{:.1} s", d.as_secs_f64())
12660×
}
1267
1268
/// `image_ms`: how long fetching its image took, when the runner lacked it.
12690×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim, image_ms: Option<u64>) -> Result<Finish> {
12700×
    let started = Instant::now();
12710×
    let mut sink = LogSink {
12720×
        hub,
12730×
        job: claim.job_id,
12740×
        buf: Vec::new(),
12750×
        last: Instant::now(),
12760×
        gone: false,
12770×
        leaving: &LEAVING,
12780×
        started: Instant::now(),
12790×
        expected: claim.expected_ms.map(Duration::from_millis),
12800×
    };
12810×
    let note =
12820×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
12830×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
12840×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1285
    // Preparing a workspace: fetches into a cached repository, and exports
1286
    // from it, are one job at a time per repository (`repo_lock`); taking
1287
    // cache disks and imaging the workspace are one job at a time on the
1288
    // runner (`PREPARE`); a first clone, whose token goes through the process
1289
    // environment, one at a time (`CLONE`).
12900×
    let main_lock = repo_lock(&claim.repo);
12910×
    let asked = Instant::now();
12920×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
12930×
    if asked.elapsed().as_secs() >= 2 {
12940×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
12950×
    }
12960×
    let fetching = Instant::now();
12970×
    let repo = cached_repo(home, cfg, claim)?;
12980×
    let fetched = fetching.elapsed();
12990×
    let mut preparing = None;
13000×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
13010×
    let _ = std::fs::remove_dir_all(&scratch);
13020×
    std::fs::create_dir_all(scratch.join("tree"))?;
13030×
    let result = (|| -> Result<Finish> {
13040×
        let exporting = Instant::now();
13050×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
13060×
        main_guard.take();
13070×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1308
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1309
        // workspace and of the scope hash.
13100×
        for sub in &claim.subrepos {
13110×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
13120×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
13130×
            }
13140×
            note(
13150×
                &mut sink,
13160×
                format!(
1317
                    "fetching subrepo {} at {} for {}",
1318
                    sub.repo,
13190×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1320
                    sub.path
1321
                ),
1322
            );
13230×
            let sub_lock = repo_lock(&sub.repo);
13240×
            let asked = Instant::now();
13250×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
13260×
            if asked.elapsed().as_secs() >= 2 {
13270×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
13280×
            }
13290×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
13300×
            let sub_heads: Vec<ChangeHash> =
13310×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
13320×
            let dir = scratch.join("tree").join(&sub.path);
13330×
            std::fs::create_dir_all(&dir)?;
13340×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
13350×
            drop(sub_guard);
13360×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1337
        }
13380×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1339
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1340
        // against the blob its receipt names, then put at its path. Not part
1341
        // of the scope: they are the run's, not the repository's.
13420×
        let mut input_blobs = Vec::new();
13430×
        for (index, i) in claim.inputs.iter().enumerate() {
13440×
            let what = format!("input {} from {}", i.artifact, i.from);
13450×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
13460×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
13470×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
13480×
            input_blobs.push(blob);
1349
        }
1350
        // The syscall tier runs on the tree itself; a microVM gets an image.
13510×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
13520×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1353
        // The syscall and WASM tiers see the job's files as a directory;
1354
        // the MicroVM tier as an ext4 image.
13550×
        let dir_tier = syscall_tier || wasm_tier;
13560×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1357
        // Disk mounts that name a cache start from a kept disk (#28): a
1358
        // microVM takes an image already in place as it is, the syscall tier
1359
        // a directory (#70). Taken before the workspace is imaged: the
1360
        // sources the disk was built from give unchanged files their old
1361
        // times back (#52).
13620×
        let asked = Instant::now();
13630×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
13640×
        if asked.elapsed().as_secs() >= 2 {
13650×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
13660×
        }
13670×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
13680×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
13690×
        let cache_ctx =
13700×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
13710×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
13720×
        let mut built_from: Option<crate::cache::Sources> = None;
13730×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
13740×
            let Some(name) = &m.cache else { continue };
13750×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
13760×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
13770×
                Some(t) => {
13780×
                    if built_from.is_none() {
13790×
                        built_from = t.sources;
13800×
                    }
13810×
                    t.how
1382
                }
13830×
                None => format!("cache {name}: none kept yet, an empty disk"),
1384
            };
13850×
            note(&mut sink, format!("{} ({})", how, m.target));
1386
            // What the job reads is seen when the disk is pruned (#72).
13870×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
13880×
                note(&mut sink, format!("cache {name}: {e:#}"));
13890×
            }
13900×
            cached.push((i, key, how));
1391
        }
1392
        // What the job reads or writes on its cache from now on is what it
1393
        // used; the rest may be pruned before the cache is kept (#72).
13940×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
13950×
        let sources = if cached.is_empty() {
13960×
            crate::cache::Sources::new()
1397
        } else {
13980×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
13990×
            if built_from.is_some() {
14000×
                note(
14010×
                    &mut sink,
14020×
                    format!(
14030×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
14040×
                        sources.len()
14050×
                    ),
14060×
                );
14070×
            }
14080×
            sources
1409
        };
1410
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1411
        // over the cache, before the same exec runs again; the receipt
1412
        // lists it among the job's inputs.
14130×
        if let Some(blob) = &claim.checkpoint {
14140×
            if dir_tier {
14150×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
14160×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
14170×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
14180×
                }
14190×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
14200×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
14210×
                note(
14220×
                    &mut sink,
14230×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
14240×
                );
14250×
                input_blobs.push(Repo::blob_ref(&bytes).0);
14260×
            } else {
14270×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
14280×
            }
14290×
        }
14300×
        if !dir_tier {
14310×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
14320×
            std::fs::remove_dir_all(scratch.join("tree"))?;
14330×
        }
14340×
        preparing.take();
1435
        // Cancelled while it was being prepared: no sandbox.
14360×
        if microvm::Sink::cancelled(&mut sink) {
14370×
            return Ok(cancelled());
14380×
        }
14390×
        if wasm_tier {
14400×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
14410×
        } else {
14420×
            note(
14430×
                &mut sink,
14440×
                format!(
1445
                    "{}: {} {}, {} MiB, rootfs {}",
14460×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1447
                    claim.sandbox.cpus,
14480×
                    if syscall_tier { "CPU" } else { "vCPU" },
1449
                    claim.sandbox.memory_mib,
14500×
                    &claim.sandbox.rootfs[..12]
1451
                ),
1452
            );
1453
        }
14540×
        let timeout = Duration::from_secs(claim.timeout_s);
1455
        // Where the time goes (oxygenflow#35): what came before the
1456
        // sandbox, the sandbox, and what comes after.
14570×
        let prepare_ms = started.elapsed().as_millis() as u64;
14580×
        let sandbox_started = Instant::now();
14590×
        let mut outcome = if wasm_tier {
14600×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
14610×
        } else if syscall_tier {
14620×
            let group = format!("job-{}", claim.job_id);
14630×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1464
        } else {
14650×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1466
        };
14670×
        let run_ms = sandbox_started.elapsed().as_millis() as u64;
14680×
        if outcome.cancelled {
1469
            // Handed back as the runner leaves: its checkpoints first, for
1470
            // the next attempt (oxygenflow#77).
14710×
            if leaving().is_some() && !job.checkpoints.is_empty() {
14720×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
14730×
            }
14740×
            return Ok(cancelled());
14750×
        }
1476
        // The receipt says what a cached disk started from.
14770×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
14780×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
14790×
        for (i, key, how) in &cached {
14800×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
14810×
        }
1482
        // A passing job's artifacts, read from its disks and uploaded; a
1483
        // declared artifact that cannot be kept fails the job. A failing
1484
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1485
        // its receipt, and one it cannot keep is only noted.
14860×
        let mut outputs = vec![];
14870×
        let mut output_error = None;
14880×
        let passed = outcome.exit_code == Some(0);
14890×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
14900×
        for o in wanted {
14910×
            if o.kind == flow_core::OutputKind::Report {
14920×
                let read = if dir_tier {
14930×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14940×
                    crate::outputs::read_report_dir(&dir, &inner)
1495
                } else {
14960×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14970×
                    crate::outputs::read_report(&image, &inner, &scratch)
1498
                };
14990×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
15000×
                match kept {
15010×
                    Ok((blob, files, bytes)) => {
15020×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15030×
                        let hex = blob.to_hex();
15040×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
15050×
                        if passed {
15060×
                            outputs.push(blob.0);
15070×
                        }
1508
                    }
15090×
                    Err(e) if passed => {
15100×
                        output_error = Some(format!("report {}: {e:#}", o.name));
15110×
                        break;
1512
                    }
15130×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1514
                }
15150×
                continue;
15160×
            }
15170×
            let read = if dir_tier {
15180×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15190×
                crate::outputs::read_dir_file(&dir, &inner)
1520
            } else {
15210×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15220×
                crate::outputs::read(&image, &inner, &scratch)
1523
            };
15240×
            let kept = read.and_then(|bytes| {
15250×
                let blob = Repo::blob_ref(&bytes);
15260×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
15270×
                if named != blob.to_hex() {
15280×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
15290×
                }
15300×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15310×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
15320×
                Ok(blob.0)
15330×
            });
15340×
            match kept {
15350×
                Ok(b) if passed => outputs.push(b),
15360×
                Ok(_) => {}
15370×
                Err(e) if passed => {
15380×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
15390×
                    break;
1540
                }
15410×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1542
            }
1543
        }
15440×
        if let Some(e) = &output_error {
15450×
            note(&mut sink, e.clone());
15460×
        }
15470×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
15480×
            job_name: claim.job.name.clone(),
15490×
            pipeline_hash: hex32(&claim.pipeline_hash),
15500×
            scope_tree_hash: scope_hash,
15510×
            inputs: input_blobs.clone(),
15520×
            environment: outcome.environment.hash(),
15530×
            outputs,
15540×
            exit_code: code as u32,
15550×
            duration_ms: outcome.duration_ms,
15560×
        });
15570×
        let signed_receipt = match &receipt {
15580×
            Some(r) => {
15590×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
15600×
                if cfg.keyless {
15610×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
15620×
                        Ok(k) => signed = k,
15630×
                        Err(e) => {
15640×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1565
                        }
1566
                    }
15670×
                }
15680×
                Some(hex::encode(signed.encode()))
1569
            }
15700×
            None => None,
1571
        };
1572
        // Measured before a cached disk leaves the scratch directory.
15730×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1574
        // A passing job's cached disks are pruned and kept (#72); a
1575
        // failing job's are thrown away, so nothing it wrote reaches a
1576
        // later job.
15770×
        let kept = passed && output_error.is_none();
15780×
        for (i, key, _) in &cached {
15790×
            let disk = crate::cache::disk_path(form, &scratch, *i);
15800×
            let m = disk_mounts[*i];
15810×
            let prune = crate::cache::Prune {
15820×
                started: cache_started,
15830×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
15840×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1585
            };
15860×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
15870×
                Ok(Some(line)) => note(&mut sink, line),
15880×
                Ok(None) => {}
15890×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1590
            }
1591
        }
15920×
        let total_ms = started.elapsed().as_millis() as u64;
15930×
        let mut phases: std::collections::BTreeMap<String, u64> =
15940×
            [("prepare", prepare_ms), ("run", run_ms), ("finish", total_ms.saturating_sub(prepare_ms + run_ms))]
15950×
                .into_iter()
15960×
                .map(|(k, v)| (k.to_string(), v))
15970×
                .collect();
15980×
        if let Some(ms) = image_ms {
15990×
            phases.insert("image".into(), ms);
16000×
        }
1601
        Ok(Finish {
16020×
            phases,
16030×
            exit_code: outcome.exit_code,
16040×
            duration_ms: total_ms,
16050×
            receipt,
16060×
            signed_receipt,
16070×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1608
            // What the job took (oxygenflow#41): its disks are sparse files
1609
            // in the scratch directory, so their blocks now are their peak.
16100×
            peak_disk_mib,
16110×
            peak_memory_mib: outcome.peak_memory_mib,
1612
        })
1613
    })();
16140×
    let _ = workspace::remove_tree(&scratch);
16150×
    sink.flush();
16160×
    result
16170×
}
1618
1619
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1620
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1621
/// the claim, so the runner vouches only for what it fetched.
1622
/// Upload a report's files, then its manifest under the report's name, and
1623
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1624
/// the manifest's blob, the file count and their total size.
16250×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
16260×
    let mut listed = Vec::with_capacity(files.len());
16270×
    let mut total = 0u64;
16280×
    for (path, bytes) in files {
16290×
        let blob = Repo::blob_ref(bytes).to_hex();
16300×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
16310×
        if named != blob {
16320×
            bail!("the hub kept {path} as {named}, not {blob}");
16330×
        }
16340×
        total += bytes.len() as u64;
16350×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1636
    }
16370×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
16380×
    let blob = Repo::blob_ref(&manifest);
16390×
    let named = hub.artifact(job, name, &manifest)?;
16400×
    if named != blob.to_hex() {
16410×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
16420×
    }
16430×
    Ok((blob, files.len(), total))
16440×
}
1645
16460×
fn sign_receipt(
16470×
    repo: &Repo,
16480×
    heads: &[ChangeHash],
16490×
    cfg: &RunnerConfig,
16500×
    key: &RunnerKey,
16510×
    claim: &Claim,
16520×
    receipt: &Receipt,
16530×
) -> Result<oxy_core::receipt::SignedReceipt> {
16540×
    let state = state_of(heads);
16550×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16560×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
16570×
}
1658
1659
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1660
/// just before signing, so the certificate covers the moment the hub
1661
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1662
/// receipt signed: nothing long-lived signs.
16630×
fn sign_keyless(
16640×
    repo: &Repo,
16650×
    heads: &[ChangeHash],
16660×
    cfg: &RunnerConfig,
16670×
    hub: &Hub,
16680×
    claim: &Claim,
16690×
    receipt: &Receipt,
16700×
) -> Result<oxy_core::receipt::SignedReceipt> {
16710×
    let sk = oxy_core::identity::SecretKey::generate();
16720×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
16730×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
16740×
    let id = sk.identity(&name, "", now);
16750×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
16760×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
16770×
    let state = state_of(heads);
16780×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16790×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
16800×
}
1681
1682
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
16830×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1684
    use oxy_core::hash::{hash_object, ObjectType};
16850×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
16860×
}
1687
16880×
fn hex32(s: &str) -> [u8; 32] {
16890×
    let mut out = [0; 32];
16900×
    if let Ok(v) = hex::decode(s) {
16910×
        if v.len() == 32 {
16920×
            out.copy_from_slice(&v);
16930×
        }
16940×
    }
16950×
    out
16960×
}
1697
1698
/// Whether a network error is worth another try: DNS, a refused or reset
1699
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1700
/// hub restarts (oxygenhub#111).
17018×
fn transient(msg: &str) -> bool {
17028×
    let m = msg.to_lowercase();
17038×
    [
17048×
        "dns failed",
17058×
        "name resolution",
17068×
        "connection refused",
17078×
        "connection reset",
17088×
        "timed out",
17098×
        "timeout",
17108×
        "http 502",
17118×
        "http 503",
17128×
        "http 504",
17138×
        "broken pipe",
17148×
        "unexpected eof",
17158×
    ]
17168×
    .iter()
171747×
    .any(|k| m.contains(k))
17188×
}
1719
1720
/// Run `f` again after a transient network error, waiting `waits` between
1721
/// tries (about a minute in all), and give up on any other error at once.
17223×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
17233×
    let mut tries = waits.iter();
1724
    loop {
17257×
        match f() {
17261×
            Ok(v) => return Ok(v),
17276×
            Err(e) => match tries.next() {
17285×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
17292×
                _ => return Err(e),
1730
            },
1731
        }
1732
    }
17333×
}
1734
1735
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1736
const FETCH_WAITS: [Duration; 5] =
1737
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1738
1739
/// The runner's copy of a repository, fetched up to date with the job's token.
17400×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
17410×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
17420×
}
1743
1744
/// The runner's copy of `repo`, cloned or fetched with `token`.
17450×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
17460×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
17470×
    let set_remote = |repo: &mut Repo| -> Result<()> {
17480×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
17490×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
17500×
        if let Some(ca) = &cfg.ca {
17510×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
17520×
        }
17530×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
17540×
    };
17550×
    if dir.join(".oxy").is_dir() {
17560×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
17570×
        set_remote(&mut repo)?;
17580×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
17590×
        return Ok(repo);
17600×
    }
1761
    // First job for this repository: clone with the job's token, which goes
1762
    // through the process environment, so one clone at a time.
17630×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
17640×
    std::env::set_var("OXY_TOKEN", token);
17650×
    if let Some(ca) = &cfg.ca {
17660×
        std::env::set_var("OXY_CA", ca);
17670×
    }
17680×
    let cloned = with_retries(&FETCH_WAITS, || {
17690×
        let _ = std::fs::remove_dir_all(&dir);
17700×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
17710×
    });
17720×
    std::env::remove_var("OXY_TOKEN");
17730×
    std::env::remove_var("OXY_CA");
17740×
    let mut repo = cloned.map_err(|e| {
17750×
        let _ = std::fs::remove_dir_all(&dir);
17760×
        anyhow::anyhow!("clone {}: {e}", clone_url)
17770×
    })?;
17780×
    set_remote(&mut repo)?;
17790×
    Ok(repo)
17800×
}
1781
1782
#[cfg(test)]
1783
mod tests {
1784
1785
    #[test]
17861×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
17871×
        let dir = tempfile::tempdir().unwrap();
17881×
        let bytes = b"the reviewed plan";
17891×
        let blob = Repo::blob_ref(bytes).to_hex();
17901×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
17916×
            artifact: "tfplan".into(),
17926×
            from: "plan".into(),
17936×
            path: path.into(),
17946×
            blob: blob.into(),
17956×
        };
17961×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
17971×
        assert_eq!(hex::encode(got), blob);
17981×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
17991×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
18001×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
18011×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
18024×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
18034×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1804
        }
18051×
    }
1806
1807
    use super::*;
1808
1809
    #[test]
18101×
    fn a_runner_names_what_stops_a_sandbox() {
18111×
        let dir = tempfile::tempdir().unwrap();
18121×
        let home = Home::locate(Some(dir.path())).unwrap();
18131×
        let bytes = b"not really ext4";
18141×
        let hash = blake3::hash(bytes).to_hex().to_string();
18151×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18161×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1817
        }))
18181×
        .unwrap();
18196×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
18201×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
18211×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
18221×
        sb.rootfs = hash.clone();
18231×
        assert_eq!(problem(&sb, Some(4096)), None);
18241×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
18251×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
18261×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
18271×
        sb.arch = Some("aarch64".into());
18281×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
18291×
        sb.arch = None;
18301×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
18311×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
18321×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
18331×
    }
1834
1835
    #[test]
18361×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1837
        // An image fetched or imported with no recorded architecture, built
1838
        // for riscv64: the runner reads its shell, records it, and declines
1839
        // instead of running it and failing (spec §11.2, §11.5).
18401×
        let dir = tempfile::tempdir().unwrap();
18411×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
18421×
        let tree = dir.path().join("tree");
18431×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
18441×
        let mut elf = vec![0u8; 64];
18451×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
18461×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
18471×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
18481×
        let img = dir.path().join("rootfs.ext4");
18491×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
18501×
        if !made.is_ok_and(|s| s.success()) {
18510×
            eprintln!("mkfs.ext4 not found: skipped");
18520×
            return;
18531×
        }
18541×
        let hash = crate::home::hash_file(&img).unwrap();
18551×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
18561×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
18571×
        assert!(!home.image_manifest(&hash).exists());
18581×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18591×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1860
        }))
18611×
        .unwrap();
18621×
        assert_eq!(
18631×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
18641×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1865
        );
18661×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1867
        // Learned: recorded once, and reported with the runner's claims.
18681×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
18691×
        assert_eq!(manifest["arch"], "riscv64");
18701×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
18711×
    }
1872
1873
    #[test]
18741×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
18751×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
18761×
        assert!(transient("HTTP 503: the hub is restarting"));
18771×
        assert!(!transient("HTTP 404: no such repository"));
18781×
        let mut n = 0;
18793×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
18803×
            n += 1;
18813×
            if n < 3 {
18822×
                Err(anyhow::anyhow!("connection refused"))
1883
            } else {
18841×
                Ok(7)
1885
            }
18863×
        });
18871×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
18881×
        let mut m = 0;
18891×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
18901×
            m += 1;
18911×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
18921×
        });
18931×
        assert!(got.is_err());
18941×
        assert_eq!(m, 1, "a refusal is not tried again");
18951×
        let mut k = 0;
18963×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
18973×
            k += 1;
18983×
            Err(anyhow::anyhow!("timed out"))
18993×
        });
19001×
        assert!(got.is_err());
19011×
        assert_eq!(k, 3, "gives up after the last wait");
19021×
    }
1903
1904
    /// A hub that answers each request with the next of `codes`, counting them.
19059×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
19069×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
19079×
    }
1908
1909
    /// A hub at `listener` answering each request with the next of `codes`.
191011×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1911
        use std::io::{Read, Write};
191211×
        let addr = listener.local_addr().unwrap();
191311×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
191411×
        let count = seen.clone();
191511×
        std::thread::spawn(move || {
191623×
            for code in codes {
191723×
                let (mut s, _) = listener.accept().unwrap();
1918
                // Read the whole request (headers, then Content-Length bytes
1919
                // of body) before answering: closing early would reset the
1920
                // connection while the client is still sending.
192123×
                let mut req = Vec::new();
192223×
                let mut buf = [0u8; 8192];
1923
                loop {
192436×
                    let n = s.read(&mut buf).unwrap_or(0);
192536×
                    if n == 0 {
19260×
                        break;
192736×
                    }
192836×
                    req.extend_from_slice(&buf[..n]);
192936×
                    let text = String::from_utf8_lossy(&req);
193036×
                    if let Some(end) = text.find("\r\n\r\n") {
193136×
                        let len = text[..end]
193236×
                            .lines()
1933284×
                            .find_map(|l| {
1934284×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1935284×
                            })
193636×
                            .unwrap_or(0);
193736×
                        if req.len() >= end + 4 + len {
193823×
                            break;
193913×
                        }
19400×
                    }
1941
                }
194223×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
194323×
                let reason = if code == 204 { "No Content" } else { "Error" };
194423×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1945
            }
194611×
        });
194711×
        (format!("http://{addr}"), seen)
194811×
    }
1949
1950
    /// A hub that answers one request with `body` (status 200) and hands
1951
    /// back what it was sent.
19521×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1953
        use std::io::{Read, Write};
19541×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19551×
        let addr = listener.local_addr().unwrap();
19561×
        let (tx, rx) = std::sync::mpsc::channel();
19571×
        std::thread::spawn(move || {
19581×
            let (mut s, _) = listener.accept().unwrap();
19591×
            let mut req = Vec::new();
19601×
            let mut buf = [0u8; 65536];
1961
            loop {
19621×
                let n = s.read(&mut buf).unwrap_or(0);
19631×
                if n == 0 {
19640×
                    break;
19651×
                }
19661×
                req.extend_from_slice(&buf[..n]);
19671×
                let text = String::from_utf8_lossy(&req);
19681×
                if let Some(end) = text.find("\r\n\r\n") {
19691×
                    let len = text[..end]
19701×
                        .lines()
19717×
                        .find_map(|l| {
19727×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
19737×
                        })
19741×
                        .unwrap_or(0);
19751×
                    if req.len() >= end + 4 + len {
19761×
                        break;
19770×
                    }
19780×
                }
1979
            }
19801×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
19811×
            let _ = write!(
19821×
                s,
1983
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
19841×
                body.len()
1985
            );
19861×
        });
19871×
        (format!("http://{addr}"), rx)
19881×
    }
1989
1990
    #[test]
19911×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1992
        use std::os::unix::fs::PermissionsExt;
19931×
        let dir = tempfile::tempdir().unwrap();
19941×
        let home = Home::locate(Some(dir.path())).unwrap();
19951×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
19961×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
19971×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
19981×
        let req = sent.recv().unwrap();
19991×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
20001×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
20011×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
20021×
        let key = home.runner_key("plex").unwrap();
20031×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
20041×
        let path = dir.path().join(crate::home::RUNNER_TOML);
20051×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
2006
        // The runner then starts from runner.toml.
20071×
        let again = Home::locate(Some(dir.path())).unwrap();
20081×
        let cfg = again.config.runner.unwrap();
20091×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
20101×
        assert_eq!(cfg.labels, ["gpu"]);
20111×
    }
2012
2013
    /// A hub that answers certify with a certificate `sign_as` signs for
2014
    /// `cert_key`, and publishes `published` as its key: two requests.
20153×
    fn fake_certify_hub(
20163×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
20173×
        cert_key: oxy_core::identity::Identity,
20183×
        published: oxy_core::identity::Identity,
20193×
    ) -> String {
2020
        use std::io::{Read, Write};
20213×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20223×
        let addr = listener.local_addr().unwrap();
20233×
        std::thread::spawn(move || {
20243×
            for _ in 0..2 {
20256×
                let Ok((mut s, _)) = listener.accept() else { return };
20266×
                let mut req = Vec::new();
20276×
                let mut buf = [0u8; 65536];
2028
                loop {
20296×
                    let n = s.read(&mut buf).unwrap_or(0);
20306×
                    if n == 0 {
20310×
                        break;
20326×
                    }
20336×
                    req.extend_from_slice(&buf[..n]);
20346×
                    let text = String::from_utf8_lossy(&req);
20356×
                    if let Some(end) = text.find("\r\n\r\n") {
20366×
                        let len = text[..end]
20376×
                            .lines()
203839×
                            .find_map(|l| {
203939×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
204039×
                            })
20416×
                            .unwrap_or(0);
20426×
                        if req.len() >= end + 4 + len {
20436×
                            break;
20440×
                        }
20450×
                    }
2046
                }
20476×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
20486×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
20493×
                    let cert = oxy_core::cert::SignedCertificate::sign(
20503×
                        oxy_core::cert::Certificate {
20513×
                            key: cert_key.clone(),
20523×
                            issuer: sign_as.0.hash(),
20533×
                            subject: "repo:andy/demo:bookmark:main".into(),
20543×
                            claims: vec![],
20553×
                            scope: oxy_core::identity::Scope::SEAL,
20563×
                            not_before: 1,
20573×
                            expires: 600_001,
20583×
                            grant: None,
20593×
                        },
20603×
                        &sign_as.0,
20613×
                        &sign_as.1,
2062
                    );
20633×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
2064
                } else {
20653×
                    published.encode()
2066
                };
20676×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
20686×
                let _ = s.write_all(&body);
2069
            }
20703×
        });
20713×
        format!("http://{addr}")
20723×
    }
2073
2074
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2075
    /// is for its fresh key and signed by the key the hub publishes.
2076
    #[test]
20771×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2078
        use oxy_core::identity::SecretKey;
20791×
        let hub_sk = SecretKey::generate();
20801×
        let hub_id = hub_sk.identity("hub", "", 1);
20811×
        let sk = SecretKey::generate();
20821×
        let id = sk.identity("earth-1 job 7", "", 1);
20831×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2084
20851×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
20861×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
20871×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2088
20891×
        let mallory_sk = SecretKey::generate();
20901×
        let mallory = mallory_sk.identity("mallory", "", 1);
20911×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
20921×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20931×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2094
20951×
        let other = SecretKey::generate().identity("other", "", 1);
20961×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
20971×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20981×
        assert!(e.contains("another key"), "{e}");
20991×
    }
2100
210116×
    fn hub_at(base: String) -> Hub {
210216×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
210316×
    }
2104
2105
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2106
    /// hub attests; a peer or a proxy cannot change what is installed.
2107
    #[test]
21081×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
21091×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
21102×
        let serve = |bytes: Vec<u8>| {
21112×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
21122×
            let addr = listener.local_addr().unwrap();
21132×
            std::thread::spawn(move || {
2114
                use std::io::{Read, Write};
21152×
                let (mut s, _) = listener.accept().unwrap();
21162×
                let mut buf = [0u8; 4096];
21172×
                let _ = s.read(&mut buf);
21182×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
21192×
                let _ = s.write_all(&bytes);
21202×
            });
21212×
            format!("http://{addr}")
21222×
        };
21231×
        let offer = flow_core::api::UpdateOffer {
21241×
            version: "0.3.2".into(),
21251×
            asset: "flow-linux-x86_64".into(),
21261×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
21271×
            blake3: blake3::hash(&body).to_hex().to_string(),
21281×
            size: body.len() as u64,
21291×
            ..Default::default()
21301×
        };
21311×
        let dir = tempfile::tempdir().unwrap();
21321×
        let to = dir.path().join("flow-0.3.2");
21331×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
21341×
        assert_eq!(std::fs::read(&to).unwrap(), body);
21351×
        std::fs::remove_file(&to).unwrap();
21361×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
21371×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
21381×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
21391×
    }
2140
2141
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2142
    /// through server errors, and a refusal ends the trying at once.
2143
    #[test]
21441×
    fn a_result_is_reported_until_the_hub_takes_it() {
21451×
        let f = Finish {
21461×
            exit_code: Some(0),
21471×
            duration_ms: 1,
21481×
            receipt: None,
21491×
            signed_receipt: None,
21501×
            error: None,
21511×
            peak_disk_mib: None,
21521×
            peak_memory_mib: None,
21531×
            phases: Default::default(),
21541×
        };
21551×
        let quick = Duration::from_millis(10);
21561×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
21571×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
21581×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
21591×
        let (base, seen) = fake_hub(vec![409]);
21601×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
21611×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21621×
    }
2163
2164
    #[test]
21651×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
21661×
        let quick = [Duration::from_millis(10); 3];
21671×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
21681×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
21691×
        assert!(r.is_none());
21701×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2171
21721×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
21731×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
21741×
        assert!(e.contains("HTTP 500"), "{e}");
21751×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2176
21771×
        let (base, seen) = fake_hub(vec![401]);
21781×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
21791×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21801×
    }
2181
2182
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2183
2184
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2185
    /// cancelled, having sent what the job said so far, and the job is
2186
    /// handed back to the hub.
2187
    #[test]
21881×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2189
        use microvm::Sink;
21901×
        let leaving = std::sync::Mutex::new(None);
21911×
        let (base, seen) = fake_hub(vec![204, 204]);
21921×
        let hub = hub_at(base);
21931×
        let mut sink = LogSink {
21941×
            hub: &hub,
21951×
            job: 7,
21961×
            buf: Vec::new(),
21971×
            last: Instant::now(),
21981×
            gone: false,
21991×
            leaving: &leaving,
22001×
            started: Instant::now(),
22011×
            expected: None,
22021×
        };
22031×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
22041×
        assert!(!sink.cancelled());
22051×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
22061×
        assert!(sink.cancelled());
22071×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
22081×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
22091×
        hub.release(7, "off Wi-Fi").unwrap();
22101×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
22111×
    }
2212
2213
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2214
    /// it runs on; one that will not, or whose time is unknown, is handed
2215
    /// back at once, and any job still running when the notice is up.
2216
    #[test]
22171×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2218
        use microvm::Sink;
22191×
        let (base, _) = fake_hub(vec![204; 8]);
22201×
        let hub = hub_at(base);
22211×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
22221×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
22234×
            hub: &hub,
2224
            job: 1,
22254×
            buf: Vec::new(),
22264×
            last: Instant::now(),
2227
            gone: false,
22284×
            leaving: &leaving,
22294×
            started: Instant::now() - Duration::from_secs(ran),
22304×
            expected: expected.map(Duration::from_secs),
22314×
        };
22321×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
22331×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
22341×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
22351×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
22361×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
22371×
    }
2238
2239
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2240
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2241
    #[test]
22421×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2243
        use microvm::Sink;
22442×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
22451×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
22461×
        let (base, seen) = fake_hub(vec![204]);
22471×
        let hub = hub_at(base);
22481×
        let mut sink = LogSink {
22491×
            hub: &hub,
22501×
            job: 1,
22511×
            buf: Vec::new(),
22521×
            last: quiet,
22531×
            gone: false,
22541×
            leaving: &NOT_LEAVING,
22551×
            started: Instant::now(),
22561×
            expected: None,
22571×
        };
22581×
        assert!(!sink.cancelled());
22591×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
22601×
        assert_eq!(n(&seen), 1);
2261
22621×
        let (base, seen) = fake_hub(vec![409]);
22631×
        let hub = hub_at(base);
22641×
        let mut sink = LogSink {
22651×
            hub: &hub,
22661×
            job: 1,
22671×
            buf: Vec::new(),
22681×
            last: quiet,
22691×
            gone: false,
22701×
            leaving: &NOT_LEAVING,
22711×
            started: Instant::now(),
22721×
            expected: None,
22731×
        };
22741×
        assert!(sink.cancelled());
22751×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
22761×
        sink.flush();
22771×
        assert!(sink.cancelled());
22781×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
22791×
    }
2280
2281
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2282
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2283
    /// no lines.
2284
    #[test]
22851×
    fn a_job_outlasts_a_hub_restart() {
22862×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2287
        // A port nobody listens on yet: the hub is restarting.
22881×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22891×
        let base = format!("http://127.0.0.1:{port}");
22901×
        let hub = hub_at(base.clone());
2291
2292
        // Log lines sent while it is away are kept, and go when it is back.
22931×
        let mut sink = LogSink {
22941×
            hub: &hub,
22951×
            job: 1,
22961×
            buf: Vec::new(),
22971×
            last: Instant::now(),
22981×
            gone: false,
22991×
            leaving: &NOT_LEAVING,
23001×
            started: Instant::now(),
23011×
            expected: None,
23021×
        };
2303450×
        for i in 0..450 {
2304450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2305450×
        }
23061×
        sink.send();
23071×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
23081×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
23091×
        sink.send();
23101×
        assert!(sink.buf.is_empty() && !sink.gone);
23111×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2312
2313
        // An upload waits for the hub to come back, through refused
2314
        // connections and server errors alike.
23151×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23161×
        let url = format!("http://127.0.0.1:{port}/x");
23171×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
23181×
        let later = std::thread::spawn(move || {
23191×
            std::thread::sleep(Duration::from_millis(150));
23201×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
23211×
        });
23221×
        let quick = [Duration::from_millis(50); 20];
23235×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
23241×
        assert_eq!(r.status(), 204);
23251×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2326
        // Without `connection`, a hub that cannot be reached ends it at once.
23271×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23281×
        let url = format!("http://127.0.0.1:{port}/x");
23291×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
23301×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
23311×
    }
2332
2333
    /// oxygenflow#50: the first stop drains (the second, not called here,
2334
    /// exits at once).
2335
    #[test]
23361×
    fn a_stop_drains_the_runner() {
23371×
        assert!(!stopping());
23381×
        on_stop(libc::SIGTERM);
23391×
        assert!(stopping(), "told to stop, it claims nothing more");
2340
        // An embedded runner starts afresh, and stop() drains it the same way.
23411×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23421×
        stop();
23431×
        assert!(stopping());
23441×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23451×
    }
2346
2347
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2348
    #[test]
23491×
    fn unsent_log_lines_are_bounded() {
23501×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23511×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
23521×
        let mut sink = LogSink {
23531×
            hub: &hub,
23541×
            job: 1,
23551×
            buf: Vec::new(),
23561×
            last: Instant::now(),
23571×
            gone: false,
23581×
            leaving: &NOT_LEAVING,
23591×
            started: Instant::now(),
23601×
            expected: None,
23611×
        };
236250010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
23631×
        sink.send();
23641×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
23651×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
23661×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
23671×
    }
2368
2369
    #[test]
23701×
    fn the_budget_admits_jobs_that_fit() {
23711×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
23727×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
23731×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
23741×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
23751×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
23761×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
23771×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
23781×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
23791×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
23801×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
23811×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
23821×
    }
2383
2384
    #[test]
23851×
    fn a_claim_never_asks_for_more_memory_than_the_host_has_free() {
23861×
        assert_eq!(claim_memory(None, Some(6541)), Some(6541), "idle: the host's free memory, not unlimited");
23871×
        assert_eq!(claim_memory(Some(16_384), Some(6541)), Some(6541));
23881×
        assert_eq!(claim_memory(Some(4096), Some(6541)), Some(4096), "the budget when it is smaller");
23891×
        assert_eq!(claim_memory(None, None), None, "nothing known: no limit, as before");
23901×
        assert_eq!(claim_memory(Some(4096), None), Some(4096));
23911×
    }
2392
}