OXYGENHUB

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

842 of 1867 lines run, 96 of 427 functions · run #215 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×
        let kept = keep_ca(&home.root, ca)?;
4040×
        text.push_str(&format!("ca = {:?}\n", kept.display().to_string()));
4051×
    }
4061×
    if !labels.is_empty() {
4071×
        text.push_str(&format!("labels = {labels:?}\n"));
4081×
    }
4091×
    let path = home.root.join(crate::home::RUNNER_TOML);
410
    {
411
        use std::io::Write;
4121×
        let tmp = path.with_extension("toml.tmp");
4131×
        let mut f = crate::portable::private(std::fs::OpenOptions::new().write(true).create(true).truncate(true)).open(&tmp)?;
4141×
        f.write_all(text.as_bytes())?;
4151×
        f.sync_all()?;
4161×
        std::fs::rename(&tmp, &path)?;
417
    }
4181×
    Ok(got)
4191×
}
420
421
/// Copy the hub's CA certificate `ca` into the Flow home `root` (#98) and
422
/// give the copy's absolute path, for runner.toml: a service starts in
423
/// another directory, and the file given may move or go.
4242×
fn keep_ca(root: &Path, ca: &Path) -> Result<PathBuf> {
4252×
    let kept = root.join(crate::home::CA_PEM);
4262×
    let same = matches!((std::fs::canonicalize(ca), std::fs::canonicalize(&kept)), (Ok(a), Ok(b)) if a == b);
4272×
    if !same {
4281×
        std::fs::copy(ca, &kept).with_context(|| format!("copy {} into {}", ca.display(), root.display()))?;
4291×
    }
4302×
    Ok(std::fs::canonicalize(&kept)?)
4312×
}
432
433
/// Waits before trying a hub request again after a server error.
434
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
435
436
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
437
/// all, longer than a hub takes to restart.
438
/// Check an input's bytes against the blob the producing job's receipt
439
/// names, then write them at its path under `tree` (the workspace's `/src`).
4406×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
4416×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
442
    else {
4434×
        bail!("path {:?} is not a clean path under /src", i.path);
444
    };
4452×
    let blob = Repo::blob_ref(bytes);
4462×
    if blob.to_hex() != i.blob {
4471×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
4481×
    }
4491×
    let dest = tree.join(rel);
4501×
    if let Some(dir) = dest.parent() {
4511×
        std::fs::create_dir_all(dir)?;
4520×
    }
4531×
    std::fs::write(&dest, bytes)?;
4541×
    Ok(blob.0)
4556×
}
456
457
/// The largest input a job takes: the hub's artifact limit.
458
pub const MAX_INPUT_BYTES: usize = 512 << 20;
459
460
const PATIENT_DELAYS: [Duration; 15] = {
461
    let mut d = [Duration::from_secs(15); 15];
462
    d[0] = Duration::from_secs(1);
463
    d[1] = Duration::from_secs(2);
464
    d[2] = Duration::from_secs(4);
465
    d[3] = Duration::from_secs(8);
466
    d
467
};
468
469
/// Send a request until the hub answers, waiting `delays` in turn after a
470
/// server error (5xx: nothing was committed) and, when `connection`, after
471
/// the hub could not be reached at all. A refusal (4xx) is final, as a
472
/// [`Refused`] the caller can look at.
47314×
fn retrying(
47414×
    url: &str,
47514×
    delays: &[Duration],
47614×
    connection: bool,
47714×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
47814×
) -> Result<ureq::Response> {
47914×
    let mut delays = delays.iter();
480
    loop {
48123×
        let why = match send().map_err(|e| *e) {
4828×
            Ok(r) => return Ok(r),
4839×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4842×
                let text = r.into_string().unwrap_or_default();
4852×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
486
            }
4877×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4883×
            Err(e) if connection => e.to_string(),
4893×
            Err(e) => bail!("{url}: {e}"),
490
        };
49110×
        match delays.next() {
4929×
            Some(d) => std::thread::sleep(*d),
4931×
            None => bail!("{url}: {why}"),
494
        }
495
    }
49614×
}
497
498
/// What the runner may run at once (flow.toml `[runner]`): at most
499
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
500
#[derive(Debug, Default, PartialEq, Eq)]
501
pub struct Budget {
502
    pub max_jobs: usize,
503
    pub memory_mib: Option<u32>,
504
    pub cpus: Option<u32>,
505
}
506
507
/// What is in use now.
508
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
509
pub struct Used {
510
    pub jobs: usize,
511
    pub memory_mib: u32,
512
    pub cpus: u32,
513
}
514
515
impl Budget {
5160×
    pub fn of(cfg: &RunnerConfig) -> Budget {
5170×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
5180×
    }
519
520
    /// The room to ask the hub for, or `None` when no job more can start.
521
    /// A lone job may use the whole budget even if it asks for more, so a
522
    /// large sandbox is never starved.
5237×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
5247×
        if used.jobs >= self.max_jobs {
5252×
            return None;
5265×
        }
5275×
        if used.jobs == 0 {
5282×
            return Some((None, None));
5293×
        }
5303×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
5313×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
5323×
        if mem == Some(0) || cpus == Some(0) {
5331×
            return None;
5342×
        }
5352×
        Some((mem, cpus))
5367×
    }
537
}
538
539
/// The isolation tiers this machine can honour now (spec §11.1): the
540
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
541
/// flow.toml pins Firecracker; the syscall tier when this binary may use
542
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
543
/// `Err` says why there are none; the reasons for missing tiers come back
544
/// with the ones there are.
5453×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
5463×
    let mut have = Vec::new();
5473×
    let mut missing = Vec::new();
5483×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
5493×
    match (kvm, home.config.microvm.is_some()) {
5503×
        _ if !cfg!(target_os = "linux") => missing.push("microvm: the tier runs only on Linux (Firecracker and KVM)".to_string()),
5510×
        (Ok(_), true) => have.push("microvm".to_string()),
5520×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
5533×
        (Err(e), _) => missing.push(format!(
554
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
555
        )),
556
    }
5573×
    match crate::syscall::available() {
5580×
        Ok(()) => have.push("syscall".to_string()),
5593×
        Err(e) => missing.push(format!("syscall: {e}")),
560
    }
561
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5623×
    have.push("wasm".to_string());
5633×
    if have.is_empty() {
5640×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5653×
    }
5663×
    Ok((have, missing))
5673×
}
568
569
/// Fetch `claim`'s image from the hub when this home lacks it
570
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
571
/// leaves it missing, and the preflight declines the job as before.
5720×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) -> Option<u64> {
5730×
    let hash = &claim.sandbox.rootfs;
5740×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5750×
        return None;
5760×
    }
5770×
    let note = |text: String| {
5780×
        eprintln!("job {}: {text}", claim.job_id);
5790×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5800×
    };
581
    // One fetch of an image at a time: two jobs wanting it wait for one.
582
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5830×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5840×
    if home.rootfs(hash).is_file() {
5850×
        return None;
5860×
    }
5870×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5880×
        Ok(c) => c,
5890×
        Err(e) => {
5900×
            note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12]));
5910×
            return None;
592
        }
593
    };
5940×
    let fetching = Instant::now();
5950×
    let fetched = match swarm {
5960×
        Some(sw) => {
5970×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5980×
            sw.fetch(home, hash)
599
        }
600
        None => {
6010×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
6020×
            client.fetch(home, hash)
603
        }
604
    };
6050×
    let took = fetching.elapsed().as_millis() as u64;
6060×
    match fetched {
6070×
        Ok(Some(m)) => note(format!(
608
            "image {}: fetched {} chunks, {}{} in {:.1} s",
6090×
            &hash[..12],
610
            m.chunks,
6110×
            crate::images::human(m.bytes),
6120×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
6130×
            m.elapsed.as_secs_f64()
614
        )),
6150×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
6160×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
617
    }
6180×
    Some(took)
6190×
}
620
621
/// Why this runner cannot run `claim` now (spec §11.5), checked before
622
/// anything is fetched: the tier, the architecture, the image and the
623
/// memory. The hub chose it from what the runner last said, which may be
624
/// out of date.
6250×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6260×
    let sb = &claim.sandbox;
6270×
    match sb.runtime {
628
        flow_core::Runtime::Microvm => {
6290×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6300×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6310×
            }
6320×
            if home.config.microvm.is_none() {
6330×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6340×
            }
635
        }
636
        flow_core::Runtime::Syscall => {
6370×
            if let Err(e) = crate::syscall::available() {
6380×
                return Some(format!("the syscall tier cannot run here: {e}"));
6390×
            }
640
        }
641
        // No image and no architecture: only the memory matters.
642
        flow_core::Runtime::Wasm => {
6430×
            return available_memory_mib()
6440×
                .filter(|free| *free < u64::from(sb.memory_mib))
6450×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
646
        }
647
    }
6480×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6490×
}
650
651
/// What stops `sb` running on this home's images, on a machine of
652
/// architecture `here` with `free_mib` of memory free.
6538×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6548×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6551×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6567×
    }
6577×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6587×
    let image = home.rootfs(&sb.rootfs);
6597×
    if !image.is_file() {
6601×
        return Some(format!("rootfs {short} is not on this runner"));
6616×
    }
6626×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6632×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6644×
    }
6654×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6661×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6673×
    }
6683×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6691×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6702×
    }
6712×
    None
6728×
}
673
674
/// The memory to claim with: the budget's room, never more than the host
675
/// has free now. An idle runner's budget is unlimited (a lone job may use
676
/// it all), so without this it was offered sandboxes it then declined for
677
/// want of memory, one after another, having fetched their images first
678
/// (an 8 GiB job on a 7 GB machine).
6795×
fn claim_memory(room: Option<u32>, host_free_mib: Option<u64>) -> Option<u32> {
6805×
    match (room, host_free_mib) {
6812×
        (Some(r), Some(h)) => Some(r.min(u32::try_from(h).unwrap_or(u32::MAX))),
6821×
        (None, Some(h)) => Some(u32::try_from(h).unwrap_or(u32::MAX)),
6832×
        (room, None) => room,
684
    }
6855×
}
686
687
/// `MemAvailable` from /proc/meminfo, in MiB.
6880×
fn available_memory_mib() -> Option<u64> {
6890×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6900×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6910×
    Some(kib / 1024)
6920×
}
693
6940×
pub fn serve(home: &Home) -> Result<()> {
6950×
    drain_on_stop();
6960×
    crate::update::note_runner(&home.root);
697
    // `flow runner update` swapped a new build in and asks this one to
698
    // leave with the notice it gave (#85).
699
    #[cfg(unix)]
7000×
    {
7010×
        let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
7020×
        unsafe { libc::signal(libc::SIGUSR1, handler) };
7030×
    }
7040×
    if let Some(p) = crate::update::pending(&home.root) {
705
        // On trial: a build that does not reach the hub in time goes back.
7060×
        let root = home.root.clone();
7070×
        std::thread::spawn(move || {
7080×
            std::thread::sleep(crate::update::PROVE_WITHIN);
7090×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
7100×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
7110×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
7120×
                    std::process::exit(1);
7130×
                }
7140×
            }
7150×
        });
7160×
    }
7170×
    let served = serve_until_drained(home);
7180×
    crate::update::forget_runner(&home.root);
719
    // Left for a new build: on Windows, end as a failure, so a Task
720
    // Scheduler task set to restart on failure starts it (systemd's
721
    // Restart=always starts it after a clean exit).
7220×
    if cfg!(windows) && served.is_ok() && LEFT_FOR_UPDATE.load(std::sync::atomic::Ordering::SeqCst) {
7230×
        eprintln!("flow runner: left for the new build; exiting 75 so it is started");
7240×
        std::process::exit(75);
7250×
    }
7260×
    served
7270×
}
728
729
/// Set once the runner leaves for a new build.
730
static LEFT_FOR_UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
731
732
/// Set by SIGUSR1: a new build is in place; leave for it.
733
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
734
735
#[cfg(unix)]
7360×
extern "C" fn on_update(_: libc::c_int) {
7370×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
7380×
}
739
740
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
741
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
742
/// it holds are done and reported. It may be started again afterwards.
7430×
pub fn serve_embedded(home: &Home) -> Result<()> {
7440×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
7450×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
7460×
    serve_until_drained(home)
7470×
}
748
749
/// A departure ([`leave_within`]): why, and when the runner must be gone.
750
#[derive(Clone, Debug)]
751
struct Leave {
752
    reason: String,
753
    by: Instant,
754
}
755
756
/// Set once the runner is leaving: a job whose expected rest fits before
757
/// the deadline finishes; the others are stopped and handed back
758
/// (oxygenflow#76).
759
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
760
7610×
fn leaving() -> Option<String> {
7620×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7630×
}
764
765
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
766
/// more, stop the jobs it holds and hand them back to the hub, which queues
767
/// them ahead of new work for another runner (oxygenflow#76), then return.
768
/// For a departure with no time to finish: a phone off the allowed network.
7690×
pub fn leave(reason: &str) {
7700×
    leave_within(reason, Duration::ZERO);
7710×
}
772
773
/// [`leave`], with `notice`: a job the hub expects to finish within it
774
/// (the claim's `expected_ms`, less the time it has run) finishes and is
775
/// reported; the others, and any still running when the notice is up, are
776
/// handed back. For a phone taken off charge, a spot reclaim.
7770×
pub fn leave_within(reason: &str, notice: Duration) {
7780×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7790×
    stop();
7800×
}
781
782
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
783
/// more, finish and report what it holds, then return (oxygenflow#76's
784
/// drain, for a phone taken off charge or off the allowed network).
7851×
pub fn stop() {
7861×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7871×
}
788
7890×
fn serve_until_drained(home: &Home) -> Result<()> {
7900×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
791
    // A runner offers only what it can run: a machine without KVM claims
792
    // nothing rather than taking MicroVM jobs and failing them (#36).
7930×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7940×
    for why in &missing {
7950×
        eprintln!("flow runner: not offering {why}");
7960×
    }
7970×
    let hub = Hub::new(&cfg)?;
7980×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
7990×
    let budget = Budget::of(&cfg);
8000×
    let key = home.runner_key(&name)?;
801
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
802
    // peers still runs jobs, fetching images from the hub alone.
8030×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
8040×
        eprintln!("flow runner: not joining the swarm: {e:#}");
8050×
        None
8060×
    });
8070×
    eprintln!(
808
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
809
        cfg.hub,
810
        budget.max_jobs,
8110×
        runtimes.join(", "),
8120×
        key.identity.hash().to_hex()
813
    );
8140×
    if let Some(addr) = &cfg.metrics {
8150×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
8160×
    }
817
    // The manifests of images held here that the hub keeps none of, so
818
    // peers in this runner's site can fetch them without anyone pushing
819
    // them (oxygenflow#94): at start and every ten minutes, which also
820
    // catches an image imported while it runs. Only a runner that serves
821
    // its peers has anything to offer.
8220×
    if swarm.is_some() {
8230×
        let (root, cfg) = (home.root.clone(), cfg.clone());
8240×
        std::thread::spawn(move || loop {
8250×
            let offered = Home::locate(Some(&root))
8260×
                .and_then(|home| crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref())?.offer_held(&home));
8270×
            match offered {
8280×
                Ok(0) => {}
8290×
                Ok(n) => eprintln!("flow runner: sent the hub the manifests of {n} image(s) only runners hold"),
8300×
                Err(e) => eprintln!("flow runner: offering held images: {e:#}"),
831
            }
8320×
            std::thread::sleep(Duration::from_secs(600));
833
        });
8340×
    }
8350×
    let used = std::sync::Mutex::new(Used::default());
8360×
    let mut idle = Duration::from_secs(2);
8370×
    let pending = report_pending(home);
838
    // The jobs held now, told to the hub at each claim so it can end the
839
    // ones this runner lost: a job is held from its claim until its result
840
    // is reported.
8410×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
8420×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
8430×
    std::thread::scope(|scope| {
8440×
        for (job, f) in pending {
8450×
            let (hub, held) = (&hub, &held);
8460×
            scope.spawn(move || {
8470×
                eprintln!("job {job}: reporting the result kept from before the restart");
8480×
                report_finish(home, hub, job, &f);
8490×
                held.lock().unwrap().remove(&job);
8500×
            });
851
        }
852
        // The speed (spec §11.1): measured now, and again every 15 minutes
853
        // while no job runs, so a job never shares the CPU with it.
8540×
        let measure = || {
8550×
            let (speed, ms) = crate::facts::bench();
8560×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
8570×
            speed
8580×
        };
8590×
        let mut speed = measure();
8600×
        let mut benched = Instant::now();
8610×
        let mut said_draining = false;
862
        // When the hub last heard from us (oxygenhub#243): a claim, or a
863
        // heartbeat while there is no room to claim.
8640×
        let mut heard = Instant::now();
8650×
        let beat = |heard: &mut Instant| {
8660×
            if heard.elapsed() >= HUB_HEARTBEAT {
8670×
                if let Err(e) = hub.heartbeat() {
8680×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8690×
                }
8700×
                *heard = Instant::now();
8710×
            }
8720×
        };
8730×
        let mut on_trial = crate::update::pending(&home.root).is_some();
874
        // Runner updates (oxygenhub#322): asked of the hub once it has
875
        // answered a claim, then every 15 minutes.
8760×
        let mut update_asked: Option<Instant> = None;
8770×
        let mut update_said = String::new();
878
        loop {
8790×
            if !stopping() && crate::update::drain_requested(&home.root) {
8800×
                eprintln!("flow runner {name}: asked to drain (flow runner drain)");
8810×
                stop();
8820×
            }
8830×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) || crate::update::requested(&home.root) {
8840×
                let p = crate::update::pending(&home.root);
8850×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8860×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8870×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8880×
                LEFT_FOR_UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
8890×
                leave_within(&format!("updating to {to}"), notice);
8900×
            }
891
            // Draining (oxygenflow#50): told to stop, claim nothing more and
892
            // stop once every job held is done and reported.
8930×
            if stopping() {
8940×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8950×
                if jobs == 0 && holding == 0 {
8960×
                    eprintln!("flow runner {name}: drained, stopping");
8970×
                    break;
8980×
                }
8990×
                if !said_draining {
9000×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
9010×
                    said_draining = true;
9020×
                }
9030×
                beat(&mut heard);
9040×
                std::thread::sleep(Duration::from_millis(500));
9050×
                continue;
9060×
            }
9070×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
9080×
                speed = measure();
9090×
                benched = Instant::now();
9100×
            }
9110×
            let room = budget.room(*used.lock().unwrap());
9120×
            let Some((free_memory_mib, free_cpus)) = room else {
9130×
                beat(&mut heard);
9140×
                std::thread::sleep(Duration::from_millis(500));
9150×
                continue;
916
            };
9170×
            heard = Instant::now();
9180×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
9190×
            let req = ClaimRequest {
9200×
                runner: name.clone(),
9210×
                runtimes: runtimes.clone(),
9220×
                free_memory_mib: claim_memory(free_memory_mib, available_memory_mib()),
9230×
                free_cpus,
9240×
                info: Some(RunnerInfo {
9250×
                    version: env!("OXY_VERSION_LONG").into(),
9260×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
9270×
                }),
928
                // Read each time: an image imported while the runner runs counts.
9290×
                images: Some(home.images()),
9300×
                image_archs: Some(home.image_archs()),
9310×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
932
                fetches_images: true,
9330×
                facts: Some(crate::facts::now(home, Some(speed))),
9340×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
9350×
                caches: Some(cache_times.keys().cloned().collect()),
9360×
                cache_times: Some(cache_times),
937
            };
9380×
            let answer = hub.claim(&req);
9390×
            if on_trial && answer.is_ok() {
9400×
                crate::update::proven(&home.root);
9410×
                on_trial = false;
9420×
            }
9430×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
9440×
                update_asked = Some(Instant::now());
9450×
                if let Some(note) = crate::update::take_note(&home.root) {
9460×
                    let _ = hub.report_update(&note);
9470×
                }
9480×
                consider_update(home, &hub, &mut update_said);
9490×
            }
9500×
            match answer {
9510×
                Ok(Some(claim)) => {
9520×
                    idle = Duration::from_secs(2);
9530×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9540×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
9550×
                    {
9560×
                        let mut u = used.lock().unwrap();
9570×
                        u.jobs += 1;
9580×
                        u.memory_mib += mem;
9590×
                        u.cpus += cpus;
9600×
                    }
9610×
                    held.lock().unwrap().insert(claim.job_id);
9620×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
9630×
                    scope.spawn(move || {
9640×
                        let id = claim.job_id;
9650×
                        let image_ms = fetch_image(home, hub, cfg, swarm, &claim);
9660×
                        if let Some(why) = preflight(home, &claim) {
9670×
                            eprintln!("job {id}: declined: {why}");
9680×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9690×
                            if let Err(e) = hub.decline(id, &why) {
9700×
                                eprintln!("job {id}: decline: {e:#}");
9710×
                            }
9720×
                            held.lock().unwrap().remove(&id);
9730×
                            let mut u = used.lock().unwrap();
9740×
                            u.jobs -= 1;
9750×
                            u.memory_mib -= mem;
9760×
                            u.cpus -= cpus;
9770×
                            return;
9780×
                        }
9790×
                        eprintln!(
980
                            "job {id}: {} {} on {}",
981
                            claim.repo,
982
                            claim.job.name,
9830×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
984
                        );
9850×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9860×
                        let finish = run_claim(home, hub, cfg, key, &claim, image_ms).unwrap_or_else(|e| Finish {
9870×
                            exit_code: None,
988
                            duration_ms: 0,
9890×
                            receipt: None,
9900×
                            signed_receipt: None,
9910×
                            error: Some(format!("{e:#}")),
9920×
                            peak_disk_mib: None,
9930×
                            peak_memory_mib: None,
9940×
                            phases: Default::default(),
9950×
                        });
9960×
                        eprintln!(
997
                            "job {id}: exit {:?}{}",
998
                            finish.exit_code,
9990×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
1000
                        );
10010×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
10020×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
10030×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
10040×
                        match leaving() {
1005
                            // Stopped as the runner leaves: another runner takes it.
10060×
                            Some(why) if cancelled => {
10070×
                                eprintln!("job {id}: handed back: {why}");
10080×
                                if let Err(e) = hub.release(id, &why) {
10090×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
10100×
                                }
1011
                            }
10120×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
10130×
                            _ => {}
1014
                        }
10150×
                        held.lock().unwrap().remove(&id);
10160×
                        let mut u = used.lock().unwrap();
10170×
                        u.jobs -= 1;
10180×
                        u.memory_mib -= mem;
10190×
                        u.cpus -= cpus;
10200×
                    });
1021
                }
10220×
                Ok(None) => std::thread::sleep(idle),
10230×
                Err(e) => {
10240×
                    eprintln!("claim: {e:#}");
10250×
                    std::thread::sleep(idle);
10260×
                    idle = (idle * 2).min(Duration::from_secs(60));
10270×
                }
1028
            }
1029
        }
10300×
        Ok(())
10310×
    })
10320×
}
1033
1034
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
1035
/// happened goes to its log, and a failure only means the next attempt
1036
/// starts again.
1037
#[allow(clippy::too_many_arguments)]
10380×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
10390×
    if !dir_tier {
10400×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
10410×
        return;
10420×
    }
10430×
    let dirs: Vec<(String, PathBuf)> = job
10440×
        .checkpoints
10450×
        .iter()
10460×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
10470×
        .collect();
10480×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
10490×
        Ok((blob, n)) => {
10500×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
1051
        }
10520×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
1053
    }
10540×
}
1055
1056
/// How many times the runner was told to stop (SIGTERM or SIGINT).
1057
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1058
10591×
extern "C" fn on_stop(_: libc::c_int) {
1060
    // A second stop means now: only async-signal-safe calls here.
10611×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
10620×
        unsafe { libc::_exit(143) };
10631×
    }
10641×
}
1065
1066
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
1067
/// so restarting a runner never kills the job it runs: the unit's
1068
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
10690×
fn drain_on_stop() {
10700×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10710×
    unsafe {
10720×
        libc::signal(libc::SIGTERM, handler);
10730×
        libc::signal(libc::SIGINT, handler);
10740×
    }
10750×
}
1076
10773×
fn stopping() -> bool {
10783×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10793×
}
1080
1081
/// Batches records to the hub every second (or every 200 lines). A quiet
1082
/// job's sink still asks the hub every few seconds whether the job runs,
1083
/// with an empty batch; once the hub answers 409 the job is not wanted.
1084
struct LogSink<'a> {
1085
    hub: &'a Hub,
1086
    job: i64,
1087
    buf: Vec<Record>,
1088
    last: Instant,
1089
    gone: bool,
1090
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1091
    /// handed back, unless its expected rest fits the notice.
1092
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1093
    /// When the job started, and how long the hub expects it to take.
1094
    started: Instant,
1095
    expected: Option<Duration>,
1096
}
1097
1098
/// The most log lines sent at once, as a busy job's sink flushes them.
1099
const BATCH: usize = 200;
1100
1101
/// The most log lines kept while the hub cannot be reached.
1102
const MAX_UNSENT: usize = 50_000;
1103
1104
/// How often a quiet job asks whether it was cancelled.
1105
const HEARTBEAT: Duration = Duration::from_secs(5);
1106
1107
impl microvm::Sink for LogSink<'_> {
11081×
    fn record(&mut self, r: Record) {
11091×
        self.push(r)
11101×
    }
1111
111210×
    fn cancelled(&mut self) -> bool {
111310×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
111410×
        if let Some(l) = leave {
1115
            // Finished if what is left of it fits the notice; else handed
1116
            // back as the runner leaves, what the job said so far first.
11175×
            let now = Instant::now();
11185×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
11195×
            if !fits || now >= l.by {
11204×
                self.flush();
11214×
                return true;
11221×
            }
11235×
        }
11246×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
11252×
            self.send();
11264×
        }
11276×
        self.gone
112810×
    }
1129
}
1130
1131
impl LogSink<'_> {
11321×
    fn push(&mut self, mut r: Record) {
11331×
        if self.gone {
11341×
            return;
11350×
        }
11360×
        if r.text.len() > MAX_RECORD_TEXT {
11370×
            let mut cut = MAX_RECORD_TEXT;
11380×
            while !r.text.is_char_boundary(cut) {
11390×
                cut -= 1;
11400×
            }
11410×
            r.text.truncate(cut);
11420×
        }
11430×
        self.buf.push(r);
11440×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
11450×
            self.flush();
11460×
        }
11471×
    }
1148
11495×
    fn flush(&mut self) {
11505×
        if !self.buf.is_empty() {
11511×
            self.send();
11524×
        }
11535×
        self.last = Instant::now();
11545×
    }
1155
1156
    /// Send what is buffered, even nothing, in batches of at most
1157
    /// `BATCH` lines.
11586×
    fn send(&mut self) {
1159
        loop {
11608×
            if self.gone {
11610×
                return;
11628×
            }
11638×
            let n = self.buf.len().min(BATCH);
11648×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
11658×
            match self.hub.log(self.job, batch.clone()) {
11665×
                Ok(()) => {}
11673×
                Err(e) if job_gone(&e) => self.gone = true,
11682×
                Err(e) => {
1169
                    // The hub is away (a restart, say): keep the lines for
1170
                    // the next batch, up to a bound, so the log loses none
1171
                    // (oxygenflow#49).
11722×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11732×
                    let mut kept = batch;
11742×
                    kept.append(&mut self.buf);
11752×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11762×
                    if over > 0 {
11771×
                        kept.drain(..over);
11781×
                        kept.insert(
11791×
                            0,
11801×
                            Record {
11811×
                                t: 0,
11821×
                                stream: "flow".into(),
11831×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11841×
                            },
11851×
                        );
11861×
                    }
11872×
                    self.buf = kept;
11882×
                    break;
1189
                }
1190
            }
11916×
            if self.buf.is_empty() {
11924×
                break;
11932×
            }
1194
        }
11956×
        self.last = Instant::now();
11966×
    }
1197
}
1198
1199
/// How often a runner with no room to claim tells the hub it is there:
1200
/// well inside the hub's 90 s before it shows a runner offline.
1201
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1202
1203
/// How often a runner asks the hub whether it should run another build.
1204
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1205
1206
/// Notice a runner gives itself to leave for an update the hub offered.
1207
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1208
1209
/// Ask the hub for this runner's update, and act on it: download the build
1210
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1211
/// install it, or for a dry run say what would happen. What it did goes to
1212
/// the hub once per outcome (`said`).
12130×
fn consider_update(home: &Home, hub: &Hub, said: &mut String) {
12140×
    let answer = match hub.update_answer() {
12150×
        Ok(Some(a)) => a,
12160×
        Ok(None) => return,
12170×
        Err(e) => {
12180×
            eprintln!("flow runner: asking for an update: {e:#}");
12190×
            return;
1220
        }
1221
    };
12220×
    let Some(offer) = answer.offer else { return };
12230×
    let mut say = |note: String| {
12240×
        if *said != note {
12250×
            eprintln!("flow runner: {note}");
12260×
            if let Err(e) = hub.report_update(&note) {
12270×
                eprintln!("flow runner: telling the hub: {e:#}");
12280×
            }
12290×
            *said = note;
12300×
        }
12310×
    };
12320×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
12330×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
12340×
    }
12350×
    let dir = home.root.join("updates");
12360×
    let file = dir.join(format!("flow-{}", offer.version));
12370×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
12380×
    if !fresh {
12390×
        if let Err(e) = std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| hub.download_build(&offer, &file)) {
12400×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
12410×
        }
12420×
    }
12430×
    let exe = match std::env::current_exe() {
12440×
        Ok(e) => e,
12450×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1246
    };
12470×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
12480×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
12490×
        Ok(done) => {
12500×
            let _ = std::fs::remove_file(&file);
12510×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1252
        }
12530×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1254
    }
12550×
}
1256
1257
/// Held while a job takes its cache disks and images its workspace (see
1258
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1259
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1260
1261
/// Held while the first clone of any repository passes its token through
1262
/// the process environment.
1263
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1264
1265
/// One lock per cached repository: fetches into it, and exports from it,
1266
/// never overlap, while jobs of other repositories go on. A slow repository
1267
/// (one kept in a bucket, say) once held every job on the runner waiting
1268
/// behind a single global lock.
12690×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1270
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1271
        std::sync::OnceLock::new();
12720×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
12730×
    locks.entry(name.to_string()).or_default().clone()
12740×
}
1275
1276
/// Seconds, to one decimal place, for the job's log.
12770×
fn secs(d: std::time::Duration) -> String {
12780×
    format!("{:.1} s", d.as_secs_f64())
12790×
}
1280
1281
/// `image_ms`: how long fetching its image took, when the runner lacked it.
12820×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim, image_ms: Option<u64>) -> Result<Finish> {
12830×
    let started = Instant::now();
12840×
    let mut sink = LogSink {
12850×
        hub,
12860×
        job: claim.job_id,
12870×
        buf: Vec::new(),
12880×
        last: Instant::now(),
12890×
        gone: false,
12900×
        leaving: &LEAVING,
12910×
        started: Instant::now(),
12920×
        expected: claim.expected_ms.map(Duration::from_millis),
12930×
    };
12940×
    let note =
12950×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
12960×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
12970×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1298
    // Preparing a workspace: fetches into a cached repository, and exports
1299
    // from it, are one job at a time per repository (`repo_lock`); taking
1300
    // cache disks and imaging the workspace are one job at a time on the
1301
    // runner (`PREPARE`); a first clone, whose token goes through the process
1302
    // environment, one at a time (`CLONE`).
13030×
    let main_lock = repo_lock(&claim.repo);
13040×
    let asked = Instant::now();
13050×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
13060×
    if asked.elapsed().as_secs() >= 2 {
13070×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
13080×
    }
13090×
    let fetching = Instant::now();
13100×
    let repo = cached_repo(home, cfg, claim)?;
13110×
    let fetched = fetching.elapsed();
13120×
    let mut preparing = None;
13130×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
13140×
    let _ = std::fs::remove_dir_all(&scratch);
13150×
    std::fs::create_dir_all(scratch.join("tree"))?;
13160×
    let result = (|| -> Result<Finish> {
13170×
        let exporting = Instant::now();
13180×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
13190×
        main_guard.take();
13200×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1321
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1322
        // workspace and of the scope hash.
13230×
        for sub in &claim.subrepos {
13240×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
13250×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
13260×
            }
13270×
            note(
13280×
                &mut sink,
13290×
                format!(
1330
                    "fetching subrepo {} at {} for {}",
1331
                    sub.repo,
13320×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1333
                    sub.path
1334
                ),
1335
            );
13360×
            let sub_lock = repo_lock(&sub.repo);
13370×
            let asked = Instant::now();
13380×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
13390×
            if asked.elapsed().as_secs() >= 2 {
13400×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
13410×
            }
13420×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
13430×
            let sub_heads: Vec<ChangeHash> =
13440×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
13450×
            let dir = scratch.join("tree").join(&sub.path);
13460×
            std::fs::create_dir_all(&dir)?;
13470×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
13480×
            drop(sub_guard);
13490×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1350
        }
13510×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1352
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1353
        // against the blob its receipt names, then put at its path. Not part
1354
        // of the scope: they are the run's, not the repository's.
13550×
        let mut input_blobs = Vec::new();
13560×
        for (index, i) in claim.inputs.iter().enumerate() {
13570×
            let what = format!("input {} from {}", i.artifact, i.from);
13580×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
13590×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
13600×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
13610×
            input_blobs.push(blob);
1362
        }
1363
        // The syscall tier runs on the tree itself; a microVM gets an image.
13640×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
13650×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1366
        // The syscall and WASM tiers see the job's files as a directory;
1367
        // the MicroVM tier as an ext4 image.
13680×
        let dir_tier = syscall_tier || wasm_tier;
13690×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1370
        // Disk mounts that name a cache start from a kept disk (#28): a
1371
        // microVM takes an image already in place as it is, the syscall tier
1372
        // a directory (#70). Taken before the workspace is imaged: the
1373
        // sources the disk was built from give unchanged files their old
1374
        // times back (#52).
13750×
        let asked = Instant::now();
13760×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
13770×
        if asked.elapsed().as_secs() >= 2 {
13780×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
13790×
        }
13800×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
13810×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
13820×
        let cache_ctx =
13830×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
13840×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
13850×
        let mut built_from: Option<crate::cache::Sources> = None;
13860×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
13870×
            let Some(name) = &m.cache else { continue };
13880×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
13890×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
13900×
                Some(t) => {
13910×
                    if built_from.is_none() {
13920×
                        built_from = t.sources;
13930×
                    }
13940×
                    t.how
1395
                }
13960×
                None => format!("cache {name}: none kept yet, an empty disk"),
1397
            };
13980×
            note(&mut sink, format!("{} ({})", how, m.target));
1399
            // What the job reads is seen when the disk is pruned (#72).
14000×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
14010×
                note(&mut sink, format!("cache {name}: {e:#}"));
14020×
            }
14030×
            cached.push((i, key, how));
1404
        }
1405
        // What the job reads or writes on its cache from now on is what it
1406
        // used; the rest may be pruned before the cache is kept (#72).
14070×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
14080×
        let sources = if cached.is_empty() {
14090×
            crate::cache::Sources::new()
1410
        } else {
14110×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
14120×
            if built_from.is_some() {
14130×
                note(
14140×
                    &mut sink,
14150×
                    format!(
14160×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
14170×
                        sources.len()
14180×
                    ),
14190×
                );
14200×
            }
14210×
            sources
1422
        };
1423
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1424
        // over the cache, before the same exec runs again; the receipt
1425
        // lists it among the job's inputs.
14260×
        if let Some(blob) = &claim.checkpoint {
14270×
            if dir_tier {
14280×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
14290×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
14300×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
14310×
                }
14320×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
14330×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
14340×
                note(
14350×
                    &mut sink,
14360×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
14370×
                );
14380×
                input_blobs.push(Repo::blob_ref(&bytes).0);
14390×
            } else {
14400×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
14410×
            }
14420×
        }
14430×
        if !dir_tier {
14440×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
14450×
            std::fs::remove_dir_all(scratch.join("tree"))?;
14460×
        }
14470×
        preparing.take();
1448
        // Cancelled while it was being prepared: no sandbox.
14490×
        if microvm::Sink::cancelled(&mut sink) {
14500×
            return Ok(cancelled());
14510×
        }
14520×
        if wasm_tier {
14530×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
14540×
        } else {
14550×
            note(
14560×
                &mut sink,
14570×
                format!(
1458
                    "{}: {} {}, {} MiB, rootfs {}",
14590×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1460
                    claim.sandbox.cpus,
14610×
                    if syscall_tier { "CPU" } else { "vCPU" },
1462
                    claim.sandbox.memory_mib,
14630×
                    &claim.sandbox.rootfs[..12]
1464
                ),
1465
            );
1466
        }
14670×
        let timeout = Duration::from_secs(claim.timeout_s);
1468
        // Where the time goes (oxygenflow#35): what came before the
1469
        // sandbox, the sandbox, and what comes after.
14700×
        let prepare_ms = started.elapsed().as_millis() as u64;
14710×
        let sandbox_started = Instant::now();
14720×
        let mut outcome = if wasm_tier {
14730×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
14740×
        } else if syscall_tier {
14750×
            let group = format!("job-{}", claim.job_id);
14760×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1477
        } else {
14780×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1479
        };
14800×
        let run_ms = sandbox_started.elapsed().as_millis() as u64;
14810×
        if outcome.cancelled {
1482
            // Handed back as the runner leaves: its checkpoints first, for
1483
            // the next attempt (oxygenflow#77).
14840×
            if leaving().is_some() && !job.checkpoints.is_empty() {
14850×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
14860×
            }
14870×
            return Ok(cancelled());
14880×
        }
1489
        // The receipt says what a cached disk started from.
14900×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
14910×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
14920×
        for (i, key, how) in &cached {
14930×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
14940×
        }
1495
        // A passing job's artifacts, read from its disks and uploaded; a
1496
        // declared artifact that cannot be kept fails the job. A failing
1497
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1498
        // its receipt, and one it cannot keep is only noted.
14990×
        let mut outputs = vec![];
15000×
        let mut output_error = None;
15010×
        let passed = outcome.exit_code == Some(0);
15020×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
15030×
        for o in wanted {
15040×
            if o.kind == flow_core::OutputKind::Report {
15050×
                let read = if dir_tier {
15060×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15070×
                    crate::outputs::read_report_dir(&dir, &inner)
1508
                } else {
15090×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15100×
                    crate::outputs::read_report(&image, &inner, &scratch)
1511
                };
15120×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
15130×
                match kept {
15140×
                    Ok((blob, files, bytes)) => {
15150×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15160×
                        let hex = blob.to_hex();
15170×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
15180×
                        if passed {
15190×
                            outputs.push(blob.0);
15200×
                        }
1521
                    }
15220×
                    Err(e) if passed => {
15230×
                        output_error = Some(format!("report {}: {e:#}", o.name));
15240×
                        break;
1525
                    }
15260×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1527
                }
15280×
                continue;
15290×
            }
15300×
            let read = if dir_tier {
15310×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15320×
                crate::outputs::read_dir_file(&dir, &inner)
1533
            } else {
15340×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15350×
                crate::outputs::read(&image, &inner, &scratch)
1536
            };
15370×
            let kept = read.and_then(|bytes| {
15380×
                let blob = Repo::blob_ref(&bytes);
15390×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
15400×
                if named != blob.to_hex() {
15410×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
15420×
                }
15430×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15440×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
15450×
                Ok(blob.0)
15460×
            });
15470×
            match kept {
15480×
                Ok(b) if passed => outputs.push(b),
15490×
                Ok(_) => {}
15500×
                Err(e) if passed => {
15510×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
15520×
                    break;
1553
                }
15540×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1555
            }
1556
        }
15570×
        if let Some(e) = &output_error {
15580×
            note(&mut sink, e.clone());
15590×
        }
15600×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
15610×
            job_name: claim.job.name.clone(),
15620×
            pipeline_hash: hex32(&claim.pipeline_hash),
15630×
            scope_tree_hash: scope_hash,
15640×
            inputs: input_blobs.clone(),
15650×
            environment: outcome.environment.hash(),
15660×
            outputs,
15670×
            exit_code: code as u32,
15680×
            duration_ms: outcome.duration_ms,
15690×
        });
15700×
        let signed_receipt = match &receipt {
15710×
            Some(r) => {
15720×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
15730×
                if cfg.keyless {
15740×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
15750×
                        Ok(k) => signed = k,
15760×
                        Err(e) => {
15770×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1578
                        }
1579
                    }
15800×
                }
15810×
                Some(hex::encode(signed.encode()))
1582
            }
15830×
            None => None,
1584
        };
1585
        // Measured before a cached disk leaves the scratch directory.
15860×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1587
        // A passing job's cached disks are pruned and kept (#72); a
1588
        // failing job's are thrown away, so nothing it wrote reaches a
1589
        // later job.
15900×
        let kept = passed && output_error.is_none();
15910×
        for (i, key, _) in &cached {
15920×
            let disk = crate::cache::disk_path(form, &scratch, *i);
15930×
            let m = disk_mounts[*i];
15940×
            let prune = crate::cache::Prune {
15950×
                started: cache_started,
15960×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
15970×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1598
            };
15990×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
16000×
                Ok(Some(line)) => note(&mut sink, line),
16010×
                Ok(None) => {}
16020×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1603
            }
1604
        }
16050×
        let total_ms = started.elapsed().as_millis() as u64;
16060×
        let mut phases: std::collections::BTreeMap<String, u64> =
16070×
            [("prepare", prepare_ms), ("run", run_ms), ("finish", total_ms.saturating_sub(prepare_ms + run_ms))]
16080×
                .into_iter()
16090×
                .map(|(k, v)| (k.to_string(), v))
16100×
                .collect();
16110×
        if let Some(ms) = image_ms {
16120×
            phases.insert("image".into(), ms);
16130×
        }
1614
        Ok(Finish {
16150×
            phases,
16160×
            exit_code: outcome.exit_code,
16170×
            duration_ms: total_ms,
16180×
            receipt,
16190×
            signed_receipt,
16200×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1621
            // What the job took (oxygenflow#41): its disks are sparse files
1622
            // in the scratch directory, so their blocks now are their peak.
16230×
            peak_disk_mib,
16240×
            peak_memory_mib: outcome.peak_memory_mib,
1625
        })
1626
    })();
16270×
    let _ = workspace::remove_tree(&scratch);
16280×
    sink.flush();
16290×
    result
16300×
}
1631
1632
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1633
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1634
/// the claim, so the runner vouches only for what it fetched.
1635
/// Upload a report's files, then its manifest under the report's name, and
1636
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1637
/// the manifest's blob, the file count and their total size.
16380×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
16390×
    let mut listed = Vec::with_capacity(files.len());
16400×
    let mut total = 0u64;
16410×
    for (path, bytes) in files {
16420×
        let blob = Repo::blob_ref(bytes).to_hex();
16430×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
16440×
        if named != blob {
16450×
            bail!("the hub kept {path} as {named}, not {blob}");
16460×
        }
16470×
        total += bytes.len() as u64;
16480×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1649
    }
16500×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
16510×
    let blob = Repo::blob_ref(&manifest);
16520×
    let named = hub.artifact(job, name, &manifest)?;
16530×
    if named != blob.to_hex() {
16540×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
16550×
    }
16560×
    Ok((blob, files.len(), total))
16570×
}
1658
16590×
fn sign_receipt(
16600×
    repo: &Repo,
16610×
    heads: &[ChangeHash],
16620×
    cfg: &RunnerConfig,
16630×
    key: &RunnerKey,
16640×
    claim: &Claim,
16650×
    receipt: &Receipt,
16660×
) -> Result<oxy_core::receipt::SignedReceipt> {
16670×
    let state = state_of(heads);
16680×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16690×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
16700×
}
1671
1672
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1673
/// just before signing, so the certificate covers the moment the hub
1674
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1675
/// receipt signed: nothing long-lived signs.
16760×
fn sign_keyless(
16770×
    repo: &Repo,
16780×
    heads: &[ChangeHash],
16790×
    cfg: &RunnerConfig,
16800×
    hub: &Hub,
16810×
    claim: &Claim,
16820×
    receipt: &Receipt,
16830×
) -> Result<oxy_core::receipt::SignedReceipt> {
16840×
    let sk = oxy_core::identity::SecretKey::generate();
16850×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
16860×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
16870×
    let id = sk.identity(&name, "", now);
16880×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
16890×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
16900×
    let state = state_of(heads);
16910×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16920×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
16930×
}
1694
1695
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
16960×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1697
    use oxy_core::hash::{hash_object, ObjectType};
16980×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
16990×
}
1700
17010×
fn hex32(s: &str) -> [u8; 32] {
17020×
    let mut out = [0; 32];
17030×
    if let Ok(v) = hex::decode(s) {
17040×
        if v.len() == 32 {
17050×
            out.copy_from_slice(&v);
17060×
        }
17070×
    }
17080×
    out
17090×
}
1710
1711
/// Whether a network error is worth another try: DNS, a refused or reset
1712
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1713
/// hub restarts (oxygenhub#111).
17148×
fn transient(msg: &str) -> bool {
17158×
    let m = msg.to_lowercase();
17168×
    [
17178×
        "dns failed",
17188×
        "name resolution",
17198×
        "connection refused",
17208×
        "connection reset",
17218×
        "timed out",
17228×
        "timeout",
17238×
        "http 502",
17248×
        "http 503",
17258×
        "http 504",
17268×
        "broken pipe",
17278×
        "unexpected eof",
17288×
    ]
17298×
    .iter()
173047×
    .any(|k| m.contains(k))
17318×
}
1732
1733
/// Run `f` again after a transient network error, waiting `waits` between
1734
/// tries (about a minute in all), and give up on any other error at once.
17353×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
17363×
    let mut tries = waits.iter();
1737
    loop {
17387×
        match f() {
17391×
            Ok(v) => return Ok(v),
17406×
            Err(e) => match tries.next() {
17415×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
17422×
                _ => return Err(e),
1743
            },
1744
        }
1745
    }
17463×
}
1747
1748
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1749
const FETCH_WAITS: [Duration; 5] =
1750
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1751
1752
/// The runner's copy of a repository, fetched up to date with the job's token.
17530×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
17540×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
17550×
}
1756
1757
/// The runner's copy of `repo`, cloned or fetched with `token`.
17580×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
17590×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
17600×
    let set_remote = |repo: &mut Repo| -> Result<()> {
17610×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
17620×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
17630×
        if let Some(ca) = &cfg.ca {
17640×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
17650×
        }
17660×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
17670×
    };
17680×
    if dir.join(".oxy").is_dir() {
17690×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
17700×
        set_remote(&mut repo)?;
17710×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
17720×
        return Ok(repo);
17730×
    }
1774
    // First job for this repository: clone with the job's token, which goes
1775
    // through the process environment, so one clone at a time.
17760×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
17770×
    std::env::set_var("OXY_TOKEN", token);
17780×
    if let Some(ca) = &cfg.ca {
17790×
        std::env::set_var("OXY_CA", ca);
17800×
    }
17810×
    let cloned = with_retries(&FETCH_WAITS, || {
17820×
        let _ = std::fs::remove_dir_all(&dir);
17830×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
17840×
    });
17850×
    std::env::remove_var("OXY_TOKEN");
17860×
    std::env::remove_var("OXY_CA");
17870×
    let mut repo = cloned.map_err(|e| {
17880×
        let _ = std::fs::remove_dir_all(&dir);
17890×
        anyhow::anyhow!("clone {}: {e}", clone_url)
17900×
    })?;
17910×
    set_remote(&mut repo)?;
17920×
    Ok(repo)
17930×
}
1794
1795
#[cfg(test)]
1796
mod tests {
1797
1798
    /// #98: register keeps a copy of the CA in the home, by absolute path,
1799
    /// and keeping the home's own copy again is a no-op.
1800
    #[test]
18011×
    fn the_ca_is_kept_in_the_home_by_absolute_path() {
18021×
        let home = tempfile::tempdir().unwrap();
18031×
        let elsewhere = tempfile::tempdir().unwrap();
18041×
        let given = elsewhere.path().join("ca.pem");
18051×
        std::fs::write(&given, "PEM").unwrap();
18061×
        let kept = super::keep_ca(home.path(), &given).unwrap();
18071×
        assert!(kept.is_absolute() && kept.ends_with(crate::home::CA_PEM), "{kept:?}");
18081×
        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "PEM");
18091×
        std::fs::remove_file(&given).unwrap();
18101×
        assert_eq!(super::keep_ca(home.path(), &kept).unwrap(), kept, "the home's copy again");
18111×
        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "PEM");
18121×
    }
1813
1814
    #[test]
18151×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
18161×
        let dir = tempfile::tempdir().unwrap();
18171×
        let bytes = b"the reviewed plan";
18181×
        let blob = Repo::blob_ref(bytes).to_hex();
18191×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
18206×
            artifact: "tfplan".into(),
18216×
            from: "plan".into(),
18226×
            path: path.into(),
18236×
            blob: blob.into(),
18246×
        };
18251×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
18261×
        assert_eq!(hex::encode(got), blob);
18271×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
18281×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
18291×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
18301×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
18314×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
18324×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1833
        }
18341×
    }
1835
1836
    use super::*;
1837
1838
    #[test]
18391×
    fn a_runner_names_what_stops_a_sandbox() {
18401×
        let dir = tempfile::tempdir().unwrap();
18411×
        let home = Home::locate(Some(dir.path())).unwrap();
18421×
        let bytes = b"not really ext4";
18431×
        let hash = blake3::hash(bytes).to_hex().to_string();
18441×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18451×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1846
        }))
18471×
        .unwrap();
18486×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
18491×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
18501×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
18511×
        sb.rootfs = hash.clone();
18521×
        assert_eq!(problem(&sb, Some(4096)), None);
18531×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
18541×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
18551×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
18561×
        sb.arch = Some("aarch64".into());
18571×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
18581×
        sb.arch = None;
18591×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
18601×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
18611×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
18621×
    }
1863
1864
    #[test]
18651×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1866
        // An image fetched or imported with no recorded architecture, built
1867
        // for riscv64: the runner reads its shell, records it, and declines
1868
        // instead of running it and failing (spec §11.2, §11.5).
18691×
        let dir = tempfile::tempdir().unwrap();
18701×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
18711×
        let tree = dir.path().join("tree");
18721×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
18731×
        let mut elf = vec![0u8; 64];
18741×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
18751×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
18761×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
18771×
        let img = dir.path().join("rootfs.ext4");
18781×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
18791×
        if !made.is_ok_and(|s| s.success()) {
18800×
            eprintln!("mkfs.ext4 not found: skipped");
18810×
            return;
18821×
        }
18831×
        let hash = crate::home::hash_file(&img).unwrap();
18841×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
18851×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
18861×
        assert!(!home.image_manifest(&hash).exists());
18871×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18881×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1889
        }))
18901×
        .unwrap();
18911×
        assert_eq!(
18921×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
18931×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1894
        );
18951×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1896
        // Learned: recorded once, and reported with the runner's claims.
18971×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
18981×
        assert_eq!(manifest["arch"], "riscv64");
18991×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
19001×
    }
1901
1902
    #[test]
19031×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
19041×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
19051×
        assert!(transient("HTTP 503: the hub is restarting"));
19061×
        assert!(!transient("HTTP 404: no such repository"));
19071×
        let mut n = 0;
19083×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
19093×
            n += 1;
19103×
            if n < 3 {
19112×
                Err(anyhow::anyhow!("connection refused"))
1912
            } else {
19131×
                Ok(7)
1914
            }
19153×
        });
19161×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
19171×
        let mut m = 0;
19181×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
19191×
            m += 1;
19201×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
19211×
        });
19221×
        assert!(got.is_err());
19231×
        assert_eq!(m, 1, "a refusal is not tried again");
19241×
        let mut k = 0;
19253×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
19263×
            k += 1;
19273×
            Err(anyhow::anyhow!("timed out"))
19283×
        });
19291×
        assert!(got.is_err());
19301×
        assert_eq!(k, 3, "gives up after the last wait");
19311×
    }
1932
1933
    /// A hub that answers each request with the next of `codes`, counting them.
19349×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
19359×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
19369×
    }
1937
1938
    /// A hub at `listener` answering each request with the next of `codes`.
193911×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1940
        use std::io::{Read, Write};
194111×
        let addr = listener.local_addr().unwrap();
194211×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
194311×
        let count = seen.clone();
194411×
        std::thread::spawn(move || {
194522×
            for code in codes {
194622×
                let (mut s, _) = listener.accept().unwrap();
1947
                // Read the whole request (headers, then Content-Length bytes
1948
                // of body) before answering: closing early would reset the
1949
                // connection while the client is still sending.
195022×
                let mut req = Vec::new();
195122×
                let mut buf = [0u8; 8192];
1952
                loop {
195331×
                    let n = s.read(&mut buf).unwrap_or(0);
195431×
                    if n == 0 {
19550×
                        break;
195631×
                    }
195731×
                    req.extend_from_slice(&buf[..n]);
195831×
                    let text = String::from_utf8_lossy(&req);
195931×
                    if let Some(end) = text.find("\r\n\r\n") {
196031×
                        let len = text[..end]
196131×
                            .lines()
1962244×
                            .find_map(|l| {
1963244×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1964244×
                            })
196531×
                            .unwrap_or(0);
196631×
                        if req.len() >= end + 4 + len {
196722×
                            break;
19689×
                        }
19690×
                    }
1970
                }
197122×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
197222×
                let reason = if code == 204 { "No Content" } else { "Error" };
197322×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1974
            }
197510×
        });
197611×
        (format!("http://{addr}"), seen)
197711×
    }
1978
1979
    /// A hub that answers one request with `body` (status 200) and hands
1980
    /// back what it was sent.
19811×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1982
        use std::io::{Read, Write};
19831×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19841×
        let addr = listener.local_addr().unwrap();
19851×
        let (tx, rx) = std::sync::mpsc::channel();
19861×
        std::thread::spawn(move || {
19871×
            let (mut s, _) = listener.accept().unwrap();
19881×
            let mut req = Vec::new();
19891×
            let mut buf = [0u8; 65536];
1990
            loop {
19911×
                let n = s.read(&mut buf).unwrap_or(0);
19921×
                if n == 0 {
19930×
                    break;
19941×
                }
19951×
                req.extend_from_slice(&buf[..n]);
19961×
                let text = String::from_utf8_lossy(&req);
19971×
                if let Some(end) = text.find("\r\n\r\n") {
19981×
                    let len = text[..end]
19991×
                        .lines()
20007×
                        .find_map(|l| {
20017×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
20027×
                        })
20031×
                        .unwrap_or(0);
20041×
                    if req.len() >= end + 4 + len {
20051×
                        break;
20060×
                    }
20070×
                }
2008
            }
20091×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
20101×
            let _ = write!(
20111×
                s,
2012
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
20131×
                body.len()
2014
            );
20151×
        });
20161×
        (format!("http://{addr}"), rx)
20171×
    }
2018
2019
    #[test]
20201×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
2021
        use std::os::unix::fs::PermissionsExt;
20221×
        let dir = tempfile::tempdir().unwrap();
20231×
        let home = Home::locate(Some(dir.path())).unwrap();
20241×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
20251×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
20261×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
20271×
        let req = sent.recv().unwrap();
20281×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
20291×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
20301×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
20311×
        let key = home.runner_key("plex").unwrap();
20321×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
20331×
        let path = dir.path().join(crate::home::RUNNER_TOML);
20341×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
2035
        // The runner then starts from runner.toml.
20361×
        let again = Home::locate(Some(dir.path())).unwrap();
20371×
        let cfg = again.config.runner.unwrap();
20381×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
20391×
        assert_eq!(cfg.labels, ["gpu"]);
20401×
    }
2041
2042
    /// A hub that answers certify with a certificate `sign_as` signs for
2043
    /// `cert_key`, and publishes `published` as its key: two requests.
20443×
    fn fake_certify_hub(
20453×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
20463×
        cert_key: oxy_core::identity::Identity,
20473×
        published: oxy_core::identity::Identity,
20483×
    ) -> String {
2049
        use std::io::{Read, Write};
20503×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20513×
        let addr = listener.local_addr().unwrap();
20523×
        std::thread::spawn(move || {
20533×
            for _ in 0..2 {
20546×
                let Ok((mut s, _)) = listener.accept() else { return };
20556×
                let mut req = Vec::new();
20566×
                let mut buf = [0u8; 65536];
2057
                loop {
20586×
                    let n = s.read(&mut buf).unwrap_or(0);
20596×
                    if n == 0 {
20600×
                        break;
20616×
                    }
20626×
                    req.extend_from_slice(&buf[..n]);
20636×
                    let text = String::from_utf8_lossy(&req);
20646×
                    if let Some(end) = text.find("\r\n\r\n") {
20656×
                        let len = text[..end]
20666×
                            .lines()
206739×
                            .find_map(|l| {
206839×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
206939×
                            })
20706×
                            .unwrap_or(0);
20716×
                        if req.len() >= end + 4 + len {
20726×
                            break;
20730×
                        }
20740×
                    }
2075
                }
20766×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
20776×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
20783×
                    let cert = oxy_core::cert::SignedCertificate::sign(
20793×
                        oxy_core::cert::Certificate {
20803×
                            key: cert_key.clone(),
20813×
                            issuer: sign_as.0.hash(),
20823×
                            subject: "repo:andy/demo:bookmark:main".into(),
20833×
                            claims: vec![],
20843×
                            scope: oxy_core::identity::Scope::SEAL,
20853×
                            not_before: 1,
20863×
                            expires: 600_001,
20873×
                            grant: None,
20883×
                        },
20893×
                        &sign_as.0,
20903×
                        &sign_as.1,
2091
                    );
20923×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
2093
                } else {
20943×
                    published.encode()
2095
                };
20966×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
20976×
                let _ = s.write_all(&body);
2098
            }
20993×
        });
21003×
        format!("http://{addr}")
21013×
    }
2102
2103
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2104
    /// is for its fresh key and signed by the key the hub publishes.
2105
    #[test]
21061×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2107
        use oxy_core::identity::SecretKey;
21081×
        let hub_sk = SecretKey::generate();
21091×
        let hub_id = hub_sk.identity("hub", "", 1);
21101×
        let sk = SecretKey::generate();
21111×
        let id = sk.identity("earth-1 job 7", "", 1);
21121×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2113
21141×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
21151×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
21161×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2117
21181×
        let mallory_sk = SecretKey::generate();
21191×
        let mallory = mallory_sk.identity("mallory", "", 1);
21201×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
21211×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
21221×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2123
21241×
        let other = SecretKey::generate().identity("other", "", 1);
21251×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
21261×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
21271×
        assert!(e.contains("another key"), "{e}");
21281×
    }
2129
213016×
    fn hub_at(base: String) -> Hub {
213116×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
213216×
    }
2133
2134
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2135
    /// hub attests; a peer or a proxy cannot change what is installed.
2136
    #[test]
21371×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
21381×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
21392×
        let serve = |bytes: Vec<u8>| {
21402×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
21412×
            let addr = listener.local_addr().unwrap();
21422×
            std::thread::spawn(move || {
2143
                use std::io::{Read, Write};
21442×
                let (mut s, _) = listener.accept().unwrap();
21452×
                let mut buf = [0u8; 4096];
21462×
                let _ = s.read(&mut buf);
21472×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
21482×
                let _ = s.write_all(&bytes);
21492×
            });
21502×
            format!("http://{addr}")
21512×
        };
21521×
        let offer = flow_core::api::UpdateOffer {
21531×
            version: "0.3.2".into(),
21541×
            asset: "flow-linux-x86_64".into(),
21551×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
21561×
            blake3: blake3::hash(&body).to_hex().to_string(),
21571×
            size: body.len() as u64,
21581×
            ..Default::default()
21591×
        };
21601×
        let dir = tempfile::tempdir().unwrap();
21611×
        let to = dir.path().join("flow-0.3.2");
21621×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
21631×
        assert_eq!(std::fs::read(&to).unwrap(), body);
21641×
        std::fs::remove_file(&to).unwrap();
21651×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
21661×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
21671×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
21681×
    }
2169
2170
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2171
    /// through server errors, and a refusal ends the trying at once.
2172
    #[test]
21731×
    fn a_result_is_reported_until_the_hub_takes_it() {
21741×
        let f = Finish {
21751×
            exit_code: Some(0),
21761×
            duration_ms: 1,
21771×
            receipt: None,
21781×
            signed_receipt: None,
21791×
            error: None,
21801×
            peak_disk_mib: None,
21811×
            peak_memory_mib: None,
21821×
            phases: Default::default(),
21831×
        };
21841×
        let quick = Duration::from_millis(10);
21851×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
21861×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
21871×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
21881×
        let (base, seen) = fake_hub(vec![409]);
21891×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
21901×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21911×
    }
2192
2193
    #[test]
21941×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
21951×
        let quick = [Duration::from_millis(10); 3];
21961×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
21971×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
21981×
        assert!(r.is_none());
21991×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2200
22011×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
22021×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
22031×
        assert!(e.contains("HTTP 500"), "{e}");
22041×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2205
22061×
        let (base, seen) = fake_hub(vec![401]);
22071×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
22081×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
22091×
    }
2210
2211
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2212
2213
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2214
    /// cancelled, having sent what the job said so far, and the job is
2215
    /// handed back to the hub.
2216
    #[test]
22171×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2218
        use microvm::Sink;
22191×
        let leaving = std::sync::Mutex::new(None);
22201×
        let (base, seen) = fake_hub(vec![204, 204]);
22211×
        let hub = hub_at(base);
22221×
        let mut sink = LogSink {
22231×
            hub: &hub,
22241×
            job: 7,
22251×
            buf: Vec::new(),
22261×
            last: Instant::now(),
22271×
            gone: false,
22281×
            leaving: &leaving,
22291×
            started: Instant::now(),
22301×
            expected: None,
22311×
        };
22321×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
22331×
        assert!(!sink.cancelled());
22341×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
22351×
        assert!(sink.cancelled());
22361×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
22371×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
22381×
        hub.release(7, "off Wi-Fi").unwrap();
22391×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
22401×
    }
2241
2242
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2243
    /// it runs on; one that will not, or whose time is unknown, is handed
2244
    /// back at once, and any job still running when the notice is up.
2245
    #[test]
22461×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2247
        use microvm::Sink;
22481×
        let (base, _) = fake_hub(vec![204; 8]);
22491×
        let hub = hub_at(base);
22501×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
22511×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
22524×
            hub: &hub,
2253
            job: 1,
22544×
            buf: Vec::new(),
22554×
            last: Instant::now(),
2256
            gone: false,
22574×
            leaving: &leaving,
22584×
            started: Instant::now() - Duration::from_secs(ran),
22594×
            expected: expected.map(Duration::from_secs),
22604×
        };
22611×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
22621×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
22631×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
22641×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
22651×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
22661×
    }
2267
2268
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2269
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2270
    #[test]
22711×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2272
        use microvm::Sink;
22732×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
22741×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
22751×
        let (base, seen) = fake_hub(vec![204]);
22761×
        let hub = hub_at(base);
22771×
        let mut sink = LogSink {
22781×
            hub: &hub,
22791×
            job: 1,
22801×
            buf: Vec::new(),
22811×
            last: quiet,
22821×
            gone: false,
22831×
            leaving: &NOT_LEAVING,
22841×
            started: Instant::now(),
22851×
            expected: None,
22861×
        };
22871×
        assert!(!sink.cancelled());
22881×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
22891×
        assert_eq!(n(&seen), 1);
2290
22911×
        let (base, seen) = fake_hub(vec![409]);
22921×
        let hub = hub_at(base);
22931×
        let mut sink = LogSink {
22941×
            hub: &hub,
22951×
            job: 1,
22961×
            buf: Vec::new(),
22971×
            last: quiet,
22981×
            gone: false,
22991×
            leaving: &NOT_LEAVING,
23001×
            started: Instant::now(),
23011×
            expected: None,
23021×
        };
23031×
        assert!(sink.cancelled());
23041×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
23051×
        sink.flush();
23061×
        assert!(sink.cancelled());
23071×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
23081×
    }
2309
2310
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2311
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2312
    /// no lines.
2313
    #[test]
23141×
    fn a_job_outlasts_a_hub_restart() {
23152×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2316
        // A port nobody listens on yet: the hub is restarting.
23171×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23181×
        let base = format!("http://127.0.0.1:{port}");
23191×
        let hub = hub_at(base.clone());
2320
2321
        // Log lines sent while it is away are kept, and go when it is back.
23221×
        let mut sink = LogSink {
23231×
            hub: &hub,
23241×
            job: 1,
23251×
            buf: Vec::new(),
23261×
            last: Instant::now(),
23271×
            gone: false,
23281×
            leaving: &NOT_LEAVING,
23291×
            started: Instant::now(),
23301×
            expected: None,
23311×
        };
2332450×
        for i in 0..450 {
2333450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2334450×
        }
23351×
        sink.send();
23361×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
23371×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
23381×
        sink.send();
23391×
        assert!(sink.buf.is_empty() && !sink.gone);
23401×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2341
2342
        // An upload waits for the hub to come back, through refused
2343
        // connections and server errors alike.
23441×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23451×
        let url = format!("http://127.0.0.1:{port}/x");
23461×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
23471×
        let later = std::thread::spawn(move || {
23481×
            std::thread::sleep(Duration::from_millis(150));
23491×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
23501×
        });
23511×
        let quick = [Duration::from_millis(50); 20];
23525×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
23531×
        assert_eq!(r.status(), 204);
23541×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2355
        // Without `connection`, a hub that cannot be reached ends it at once.
23561×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23571×
        let url = format!("http://127.0.0.1:{port}/x");
23581×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
23591×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
23601×
    }
2361
2362
    /// oxygenflow#50: the first stop drains (the second, not called here,
2363
    /// exits at once).
2364
    #[test]
23651×
    fn a_stop_drains_the_runner() {
23661×
        assert!(!stopping());
23671×
        on_stop(libc::SIGTERM);
23681×
        assert!(stopping(), "told to stop, it claims nothing more");
2369
        // An embedded runner starts afresh, and stop() drains it the same way.
23701×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23711×
        stop();
23721×
        assert!(stopping());
23731×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23741×
    }
2375
2376
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2377
    #[test]
23781×
    fn unsent_log_lines_are_bounded() {
23791×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23801×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
23811×
        let mut sink = LogSink {
23821×
            hub: &hub,
23831×
            job: 1,
23841×
            buf: Vec::new(),
23851×
            last: Instant::now(),
23861×
            gone: false,
23871×
            leaving: &NOT_LEAVING,
23881×
            started: Instant::now(),
23891×
            expected: None,
23901×
        };
239150010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
23921×
        sink.send();
23931×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
23941×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
23951×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
23961×
    }
2397
2398
    #[test]
23991×
    fn the_budget_admits_jobs_that_fit() {
24001×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
24017×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
24021×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
24031×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
24041×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
24051×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
24061×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
24071×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
24081×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
24091×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
24101×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
24111×
    }
2412
2413
    #[test]
24141×
    fn a_claim_never_asks_for_more_memory_than_the_host_has_free() {
24151×
        assert_eq!(claim_memory(None, Some(6541)), Some(6541), "idle: the host's free memory, not unlimited");
24161×
        assert_eq!(claim_memory(Some(16_384), Some(6541)), Some(6541));
24171×
        assert_eq!(claim_memory(Some(4096), Some(6541)), Some(4096), "the budget when it is smaller");
24181×
        assert_eq!(claim_memory(None, None), None, "nothing known: no limit, as before");
24191×
        assert_eq!(claim_memory(Some(4096), None), Some(4096));
24201×
    }
2421
}