OXYGENHUB

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

845 of 1895 lines run, 96 of 431 functions · run #217 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 a build with it does (oxygenflow#75).
5623×
    if crate::wasm::AVAILABLE {
5633×
        have.push("wasm".to_string());
5643×
    } else {
5650×
        missing.push("wasm: this build has no WASM tier".to_string());
5660×
    }
5673×
    if have.is_empty() {
5680×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5693×
    }
5703×
    Ok((have, missing))
5713×
}
572
573
/// Fetch `claim`'s image from the hub when this home lacks it
574
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
575
/// leaves it missing, and the preflight declines the job as before.
5760×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) -> Option<u64> {
5770×
    let hash = &claim.sandbox.rootfs;
5780×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5790×
        return None;
5800×
    }
5810×
    let note = |text: String| {
5820×
        eprintln!("job {}: {text}", claim.job_id);
5830×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5840×
    };
585
    // One fetch of an image at a time: two jobs wanting it wait for one.
586
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5870×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5880×
    if home.rootfs(hash).is_file() {
5890×
        return None;
5900×
    }
5910×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5920×
        Ok(c) => c,
5930×
        Err(e) => {
5940×
            note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12]));
5950×
            return None;
596
        }
597
    };
5980×
    let fetching = Instant::now();
5990×
    let fetched = match swarm {
6000×
        Some(sw) => {
6010×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
6020×
            sw.fetch(home, hash)
603
        }
604
        None => {
6050×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
6060×
            client.fetch(home, hash)
607
        }
608
    };
6090×
    let took = fetching.elapsed().as_millis() as u64;
6100×
    match fetched {
6110×
        Ok(Some(m)) => note(format!(
612
            "image {}: fetched {} chunks, {}{} in {:.1} s",
6130×
            &hash[..12],
614
            m.chunks,
6150×
            crate::images::human(m.bytes),
6160×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
6170×
            m.elapsed.as_secs_f64()
618
        )),
6190×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
6200×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
621
    }
6220×
    Some(took)
6230×
}
624
625
/// Why this runner cannot run `claim` now (spec §11.5), checked before
626
/// anything is fetched: the tier, the architecture, the image and the
627
/// memory. The hub chose it from what the runner last said, which may be
628
/// out of date.
6290×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6300×
    let sb = &claim.sandbox;
6310×
    match sb.runtime {
632
        flow_core::Runtime::Microvm => {
6330×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6340×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6350×
            }
6360×
            if home.config.microvm.is_none() {
6370×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6380×
            }
639
        }
640
        flow_core::Runtime::Syscall => {
6410×
            if let Err(e) = crate::syscall::available() {
6420×
                return Some(format!("the syscall tier cannot run here: {e}"));
6430×
            }
644
        }
645
        // No image and no architecture: only the memory matters.
646
        flow_core::Runtime::Wasm => {
6470×
            return available_memory_mib()
6480×
                .filter(|free| *free < u64::from(sb.memory_mib))
6490×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
650
        }
651
    }
6520×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6530×
}
654
655
/// What stops `sb` running on this home's images, on a machine of
656
/// architecture `here` with `free_mib` of memory free.
6578×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6588×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6591×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6607×
    }
6617×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6627×
    let image = home.rootfs(&sb.rootfs);
6637×
    if !image.is_file() {
6641×
        return Some(format!("rootfs {short} is not on this runner"));
6656×
    }
6666×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6672×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6684×
    }
6694×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6701×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6713×
    }
6723×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6731×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6742×
    }
6752×
    None
6768×
}
677
678
/// The memory to claim with: the budget's room, never more than the host
679
/// has free now. An idle runner's budget is unlimited (a lone job may use
680
/// it all), so without this it was offered sandboxes it then declined for
681
/// want of memory, one after another, having fetched their images first
682
/// (an 8 GiB job on a 7 GB machine).
6835×
fn claim_memory(room: Option<u32>, host_free_mib: Option<u64>) -> Option<u32> {
6845×
    match (room, host_free_mib) {
6852×
        (Some(r), Some(h)) => Some(r.min(u32::try_from(h).unwrap_or(u32::MAX))),
6861×
        (None, Some(h)) => Some(u32::try_from(h).unwrap_or(u32::MAX)),
6872×
        (room, None) => room,
688
    }
6895×
}
690
691
/// `MemAvailable` from /proc/meminfo, in MiB.
6920×
fn available_memory_mib() -> Option<u64> {
6930×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6940×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6950×
    Some(kib / 1024)
6960×
}
697
6980×
pub fn serve(home: &Home) -> Result<()> {
6990×
    drain_on_stop();
7000×
    crate::update::note_runner(&home.root);
701
    // `flow runner update` swapped a new build in and asks this one to
702
    // leave with the notice it gave (#85).
703
    #[cfg(unix)]
7040×
    {
7050×
        let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
7060×
        unsafe { libc::signal(libc::SIGUSR1, handler) };
7070×
    }
7080×
    if let Some(p) = crate::update::pending(&home.root) {
709
        // On trial: a build that does not reach the hub in time goes back.
7100×
        let root = home.root.clone();
7110×
        std::thread::spawn(move || {
7120×
            std::thread::sleep(crate::update::PROVE_WITHIN);
7130×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
7140×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
7150×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
7160×
                    std::process::exit(1);
7170×
                }
7180×
            }
7190×
        });
7200×
    }
7210×
    let served = serve_until_drained(home);
7220×
    crate::update::forget_runner(&home.root);
723
    // Left for a new build: on Windows, end as a failure, so a Task
724
    // Scheduler task set to restart on failure starts it (systemd's
725
    // Restart=always starts it after a clean exit).
7260×
    if cfg!(windows) && served.is_ok() && LEFT_FOR_UPDATE.load(std::sync::atomic::Ordering::SeqCst) {
7270×
        eprintln!("flow runner: left for the new build; exiting 75 so it is started");
7280×
        std::process::exit(75);
7290×
    }
7300×
    served
7310×
}
732
733
/// Set once the runner leaves for a new build.
734
static LEFT_FOR_UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
735
736
/// Set by SIGUSR1: a new build is in place; leave for it.
737
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
738
739
#[cfg(unix)]
7400×
extern "C" fn on_update(_: libc::c_int) {
7410×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
7420×
}
743
744
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
745
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
746
/// it holds are done and reported. It may be started again afterwards.
7470×
pub fn serve_embedded(home: &Home) -> Result<()> {
7480×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
7490×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
7500×
    serve_until_drained(home)
7510×
}
752
753
/// A departure ([`leave_within`]): why, and when the runner must be gone.
754
#[derive(Clone, Debug)]
755
struct Leave {
756
    reason: String,
757
    by: Instant,
758
}
759
760
/// Set once the runner is leaving: a job whose expected rest fits before
761
/// the deadline finishes; the others are stopped and handed back
762
/// (oxygenflow#76).
763
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
764
7650×
fn leaving() -> Option<String> {
7660×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7670×
}
768
769
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
770
/// more, stop the jobs it holds and hand them back to the hub, which queues
771
/// them ahead of new work for another runner (oxygenflow#76), then return.
772
/// For a departure with no time to finish: a phone off the allowed network.
7730×
pub fn leave(reason: &str) {
7740×
    leave_within(reason, Duration::ZERO);
7750×
}
776
777
/// [`leave`], with `notice`: a job the hub expects to finish within it
778
/// (the claim's `expected_ms`, less the time it has run) finishes and is
779
/// reported; the others, and any still running when the notice is up, are
780
/// handed back. For a phone taken off charge, a spot reclaim.
7810×
pub fn leave_within(reason: &str, notice: Duration) {
7820×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7830×
    stop();
7840×
}
785
786
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
787
/// more, finish and report what it holds, then return (oxygenflow#76's
788
/// drain, for a phone taken off charge or off the allowed network).
7891×
pub fn stop() {
7901×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7911×
}
792
7930×
fn serve_until_drained(home: &Home) -> Result<()> {
7940×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
795
    // A runner offers only what it can run: a machine without KVM claims
796
    // nothing rather than taking MicroVM jobs and failing them (#36).
7970×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7980×
    for why in &missing {
7990×
        eprintln!("flow runner: not offering {why}");
8000×
    }
8010×
    let hub = Hub::new(&cfg)?;
8020×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
8030×
    let budget = Budget::of(&cfg);
8040×
    let key = home.runner_key(&name)?;
805
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
806
    // peers still runs jobs, fetching images from the hub alone.
8070×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
8080×
        eprintln!("flow runner: not joining the swarm: {e:#}");
8090×
        None
8100×
    });
8110×
    eprintln!(
812
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
813
        cfg.hub,
814
        budget.max_jobs,
8150×
        runtimes.join(", "),
8160×
        key.identity.hash().to_hex()
817
    );
8180×
    if let Some(addr) = &cfg.metrics {
8190×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
8200×
    }
821
    // The manifests of images held here that the hub keeps none of, so
822
    // peers in this runner's site can fetch them without anyone pushing
823
    // them (oxygenflow#94): at start and every ten minutes, which also
824
    // catches an image imported while it runs. Only a runner that serves
825
    // its peers has anything to offer.
8260×
    if swarm.is_some() {
8270×
        let (root, cfg) = (home.root.clone(), cfg.clone());
8280×
        std::thread::spawn(move || loop {
8290×
            let offered = Home::locate(Some(&root))
8300×
                .and_then(|home| crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref())?.offer_held(&home));
8310×
            match offered {
8320×
                Ok(0) => {}
8330×
                Ok(n) => eprintln!("flow runner: sent the hub the manifests of {n} image(s) only runners hold"),
8340×
                Err(e) => eprintln!("flow runner: offering held images: {e:#}"),
835
            }
8360×
            std::thread::sleep(Duration::from_secs(600));
837
        });
8380×
    }
8390×
    let used = std::sync::Mutex::new(Used::default());
8400×
    let mut idle = Duration::from_secs(2);
8410×
    let pending = report_pending(home);
842
    // The jobs held now, told to the hub at each claim so it can end the
843
    // ones this runner lost: a job is held from its claim until its result
844
    // is reported.
8450×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
8460×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
8470×
    std::thread::scope(|scope| {
8480×
        for (job, f) in pending {
8490×
            let (hub, held) = (&hub, &held);
8500×
            scope.spawn(move || {
8510×
                eprintln!("job {job}: reporting the result kept from before the restart");
8520×
                report_finish(home, hub, job, &f);
8530×
                held.lock().unwrap().remove(&job);
8540×
            });
855
        }
856
        // The speed (spec §11.1): measured now, and again every 15 minutes
857
        // while no job runs, so a job never shares the CPU with it.
8580×
        let measure = || {
8590×
            let (speed, ms) = crate::facts::bench();
8600×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
8610×
            speed
8620×
        };
8630×
        let mut speed = measure();
8640×
        let mut benched = Instant::now();
8650×
        let mut said_draining = false;
866
        // When the hub last heard from us (oxygenhub#243): a claim, or a
867
        // heartbeat while there is no room to claim.
8680×
        let mut heard = Instant::now();
8690×
        let beat = |heard: &mut Instant| {
8700×
            if heard.elapsed() >= HUB_HEARTBEAT {
8710×
                if let Err(e) = hub.heartbeat() {
8720×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8730×
                }
8740×
                *heard = Instant::now();
8750×
            }
8760×
        };
8770×
        let mut on_trial = crate::update::pending(&home.root).is_some();
878
        // Runner updates (oxygenhub#322): asked of the hub once it has
879
        // answered a claim, then every 15 minutes.
8800×
        let mut update_asked: Option<Instant> = None;
8810×
        let mut update_said = String::new();
882
        loop {
8830×
            if !stopping() && crate::update::drain_requested(&home.root) {
8840×
                eprintln!("flow runner {name}: asked to drain (flow runner drain)");
8850×
                stop();
8860×
            }
8870×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) || crate::update::requested(&home.root) {
8880×
                let p = crate::update::pending(&home.root);
8890×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8900×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8910×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8920×
                LEFT_FOR_UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
8930×
                leave_within(&format!("updating to {to}"), notice);
8940×
            }
895
            // Draining (oxygenflow#50): told to stop, claim nothing more and
896
            // stop once every job held is done and reported.
8970×
            if stopping() {
8980×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8990×
                if jobs == 0 && holding == 0 {
9000×
                    eprintln!("flow runner {name}: drained, stopping");
9010×
                    break;
9020×
                }
9030×
                if !said_draining {
9040×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
9050×
                    said_draining = true;
9060×
                }
9070×
                beat(&mut heard);
9080×
                std::thread::sleep(Duration::from_millis(500));
9090×
                continue;
9100×
            }
9110×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
9120×
                speed = measure();
9130×
                benched = Instant::now();
9140×
            }
9150×
            let room = budget.room(*used.lock().unwrap());
9160×
            let Some((free_memory_mib, free_cpus)) = room else {
9170×
                beat(&mut heard);
9180×
                std::thread::sleep(Duration::from_millis(500));
9190×
                continue;
920
            };
9210×
            heard = Instant::now();
9220×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
9230×
            let req = ClaimRequest {
9240×
                runner: name.clone(),
9250×
                runtimes: runtimes.clone(),
9260×
                free_memory_mib: claim_memory(free_memory_mib, available_memory_mib()),
9270×
                free_cpus,
9280×
                info: Some(RunnerInfo {
9290×
                    version: env!("OXY_VERSION_LONG").into(),
9300×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
9310×
                }),
932
                // Read each time: an image imported while the runner runs counts.
9330×
                images: Some(home.images()),
9340×
                image_archs: Some(home.image_archs()),
9350×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
936
                fetches_images: true,
9370×
                facts: Some(crate::facts::now(home, Some(speed))),
9380×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
9390×
                caches: Some(cache_times.keys().cloned().collect()),
9400×
                cache_times: Some(cache_times),
941
            };
9420×
            let answer = hub.claim(&req);
9430×
            if on_trial && answer.is_ok() {
9440×
                crate::update::proven(&home.root);
9450×
                on_trial = false;
9460×
            }
9470×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
9480×
                update_asked = Some(Instant::now());
9490×
                if let Some(note) = crate::update::take_note(&home.root) {
9500×
                    let _ = hub.report_update(&note);
9510×
                }
9520×
                consider_update(home, &hub, swarm.as_ref(), &mut update_said);
9530×
            }
9540×
            match answer {
9550×
                Ok(Some(claim)) => {
9560×
                    idle = Duration::from_secs(2);
9570×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9580×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
9590×
                    {
9600×
                        let mut u = used.lock().unwrap();
9610×
                        u.jobs += 1;
9620×
                        u.memory_mib += mem;
9630×
                        u.cpus += cpus;
9640×
                    }
9650×
                    held.lock().unwrap().insert(claim.job_id);
9660×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
9670×
                    scope.spawn(move || {
9680×
                        let id = claim.job_id;
9690×
                        let image_ms = fetch_image(home, hub, cfg, swarm, &claim);
9700×
                        if let Some(why) = preflight(home, &claim) {
9710×
                            eprintln!("job {id}: declined: {why}");
9720×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9730×
                            if let Err(e) = hub.decline(id, &why) {
9740×
                                eprintln!("job {id}: decline: {e:#}");
9750×
                            }
9760×
                            held.lock().unwrap().remove(&id);
9770×
                            let mut u = used.lock().unwrap();
9780×
                            u.jobs -= 1;
9790×
                            u.memory_mib -= mem;
9800×
                            u.cpus -= cpus;
9810×
                            return;
9820×
                        }
9830×
                        eprintln!(
984
                            "job {id}: {} {} on {}",
985
                            claim.repo,
986
                            claim.job.name,
9870×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
988
                        );
9890×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9900×
                        let finish = run_claim(home, hub, cfg, key, &claim, image_ms).unwrap_or_else(|e| Finish {
9910×
                            exit_code: None,
992
                            duration_ms: 0,
9930×
                            receipt: None,
9940×
                            signed_receipt: None,
9950×
                            error: Some(format!("{e:#}")),
9960×
                            peak_disk_mib: None,
9970×
                            peak_memory_mib: None,
9980×
                            phases: Default::default(),
9990×
                        });
10000×
                        eprintln!(
1001
                            "job {id}: exit {:?}{}",
1002
                            finish.exit_code,
10030×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
1004
                        );
10050×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
10060×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
10070×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
10080×
                        match leaving() {
1009
                            // Stopped as the runner leaves: another runner takes it.
10100×
                            Some(why) if cancelled => {
10110×
                                eprintln!("job {id}: handed back: {why}");
10120×
                                if let Err(e) = hub.release(id, &why) {
10130×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
10140×
                                }
1015
                            }
10160×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
10170×
                            _ => {}
1018
                        }
10190×
                        held.lock().unwrap().remove(&id);
10200×
                        let mut u = used.lock().unwrap();
10210×
                        u.jobs -= 1;
10220×
                        u.memory_mib -= mem;
10230×
                        u.cpus -= cpus;
10240×
                    });
1025
                }
10260×
                Ok(None) => std::thread::sleep(idle),
10270×
                Err(e) => {
10280×
                    eprintln!("claim: {e:#}");
10290×
                    std::thread::sleep(idle);
10300×
                    idle = (idle * 2).min(Duration::from_secs(60));
10310×
                }
1032
            }
1033
        }
10340×
        Ok(())
10350×
    })
10360×
}
1037
1038
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
1039
/// happened goes to its log, and a failure only means the next attempt
1040
/// starts again.
1041
#[allow(clippy::too_many_arguments)]
10420×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
10430×
    if !dir_tier {
10440×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
10450×
        return;
10460×
    }
10470×
    let dirs: Vec<(String, PathBuf)> = job
10480×
        .checkpoints
10490×
        .iter()
10500×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
10510×
        .collect();
10520×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
10530×
        Ok((blob, n)) => {
10540×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
1055
        }
10560×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
1057
    }
10580×
}
1059
1060
/// How many times the runner was told to stop (SIGTERM or SIGINT).
1061
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1062
10631×
extern "C" fn on_stop(_: libc::c_int) {
1064
    // A second stop means now: only async-signal-safe calls here.
10651×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
10660×
        unsafe { libc::_exit(143) };
10671×
    }
10681×
}
1069
1070
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
1071
/// so restarting a runner never kills the job it runs: the unit's
1072
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
10730×
fn drain_on_stop() {
10740×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10750×
    unsafe {
10760×
        libc::signal(libc::SIGTERM, handler);
10770×
        libc::signal(libc::SIGINT, handler);
10780×
    }
10790×
}
1080
10813×
fn stopping() -> bool {
10823×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10833×
}
1084
1085
/// Batches records to the hub every second (or every 200 lines). A quiet
1086
/// job's sink still asks the hub every few seconds whether the job runs,
1087
/// with an empty batch; once the hub answers 409 the job is not wanted.
1088
struct LogSink<'a> {
1089
    hub: &'a Hub,
1090
    job: i64,
1091
    buf: Vec<Record>,
1092
    last: Instant,
1093
    gone: bool,
1094
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1095
    /// handed back, unless its expected rest fits the notice.
1096
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1097
    /// When the job started, and how long the hub expects it to take.
1098
    started: Instant,
1099
    expected: Option<Duration>,
1100
}
1101
1102
/// The most log lines sent at once, as a busy job's sink flushes them.
1103
const BATCH: usize = 200;
1104
1105
/// The most log lines kept while the hub cannot be reached.
1106
const MAX_UNSENT: usize = 50_000;
1107
1108
/// How often a quiet job asks whether it was cancelled.
1109
const HEARTBEAT: Duration = Duration::from_secs(5);
1110
1111
impl microvm::Sink for LogSink<'_> {
11121×
    fn record(&mut self, r: Record) {
11131×
        self.push(r)
11141×
    }
1115
111610×
    fn cancelled(&mut self) -> bool {
111710×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
111810×
        if let Some(l) = leave {
1119
            // Finished if what is left of it fits the notice; else handed
1120
            // back as the runner leaves, what the job said so far first.
11215×
            let now = Instant::now();
11225×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
11235×
            if !fits || now >= l.by {
11244×
                self.flush();
11254×
                return true;
11261×
            }
11275×
        }
11286×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
11292×
            self.send();
11304×
        }
11316×
        self.gone
113210×
    }
1133
}
1134
1135
impl LogSink<'_> {
11361×
    fn push(&mut self, mut r: Record) {
11371×
        if self.gone {
11381×
            return;
11390×
        }
11400×
        if r.text.len() > MAX_RECORD_TEXT {
11410×
            let mut cut = MAX_RECORD_TEXT;
11420×
            while !r.text.is_char_boundary(cut) {
11430×
                cut -= 1;
11440×
            }
11450×
            r.text.truncate(cut);
11460×
        }
11470×
        self.buf.push(r);
11480×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
11490×
            self.flush();
11500×
        }
11511×
    }
1152
11535×
    fn flush(&mut self) {
11545×
        if !self.buf.is_empty() {
11551×
            self.send();
11564×
        }
11575×
        self.last = Instant::now();
11585×
    }
1159
1160
    /// Send what is buffered, even nothing, in batches of at most
1161
    /// `BATCH` lines.
11626×
    fn send(&mut self) {
1163
        loop {
11648×
            if self.gone {
11650×
                return;
11668×
            }
11678×
            let n = self.buf.len().min(BATCH);
11688×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
11698×
            match self.hub.log(self.job, batch.clone()) {
11705×
                Ok(()) => {}
11713×
                Err(e) if job_gone(&e) => self.gone = true,
11722×
                Err(e) => {
1173
                    // The hub is away (a restart, say): keep the lines for
1174
                    // the next batch, up to a bound, so the log loses none
1175
                    // (oxygenflow#49).
11762×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11772×
                    let mut kept = batch;
11782×
                    kept.append(&mut self.buf);
11792×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11802×
                    if over > 0 {
11811×
                        kept.drain(..over);
11821×
                        kept.insert(
11831×
                            0,
11841×
                            Record {
11851×
                                t: 0,
11861×
                                stream: "flow".into(),
11871×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11881×
                            },
11891×
                        );
11901×
                    }
11912×
                    self.buf = kept;
11922×
                    break;
1193
                }
1194
            }
11956×
            if self.buf.is_empty() {
11964×
                break;
11972×
            }
1198
        }
11996×
        self.last = Instant::now();
12006×
    }
1201
}
1202
1203
/// How often a runner with no room to claim tells the hub it is there:
1204
/// well inside the hub's 90 s before it shows a runner offline.
1205
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1206
1207
/// How often a runner asks the hub whether it should run another build.
1208
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1209
1210
/// Notice a runner gives itself to leave for an update the hub offered.
1211
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1212
1213
/// Ask the hub for this runner's update, and act on it: download the build
1214
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1215
/// install it, or for a dry run say what would happen. What it did goes to
1216
/// the hub once per outcome (`said`).
12170×
fn consider_update(home: &Home, hub: &Hub, swarm: Option<&crate::swarm::Swarm>, said: &mut String) {
12180×
    let answer = match hub.update_answer() {
12190×
        Ok(Some(a)) => a,
12200×
        Ok(None) => return,
12210×
        Err(e) => {
12220×
            eprintln!("flow runner: asking for an update: {e:#}");
12230×
            return;
1224
        }
1225
    };
12260×
    let Some(offer) = answer.offer else { return };
12270×
    let mut say = |note: String| {
12280×
        if *said != note {
12290×
            eprintln!("flow runner: {note}");
12300×
            if let Err(e) = hub.report_update(&note) {
12310×
                eprintln!("flow runner: telling the hub: {e:#}");
12320×
            }
12330×
            *said = note;
12340×
        }
12350×
    };
12360×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
12370×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
12380×
    }
12390×
    let dir = home.root.join("updates");
12400×
    let file = dir.join(format!("flow-{}", offer.version));
12410×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
12420×
    if !fresh {
12430×
        if let Err(e) =
12440×
            std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| fetch_build(home, hub, swarm, &offer, &file))
1245
        {
12460×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
12470×
        }
12480×
    }
12490×
    let exe = match std::env::current_exe() {
12500×
        Ok(e) => e,
12510×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1252
    };
12530×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
12540×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
12550×
        Ok(done) => {
12560×
            let _ = std::fs::remove_file(&file);
12570×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1258
        }
12590×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1260
    }
12610×
}
1262
1263
/// Fetch an offered build to `file`: through the swarm when this runner is
1264
/// in one (oxygenflow#84), as an image named by the build's BLAKE3, which
1265
/// the hub chunks when it first offers it, so runners of a site fetch it
1266
/// from each other and the hub serves it about once per site; over HTTP
1267
/// otherwise, or when the swarm cannot get it. Either way it must be the
1268
/// size and BLAKE3 the hub attests.
12690×
fn fetch_build(
12700×
    home: &Home,
12710×
    hub: &Hub,
12720×
    swarm: Option<&crate::swarm::Swarm>,
12730×
    offer: &flow_core::api::UpdateOffer,
12740×
    file: &Path,
12750×
) -> Result<()> {
12760×
    if let Some(sw) = swarm.filter(|_| jet::images::is_hash(&offer.blake3)) {
12770×
        match sw.fetch(home, &offer.blake3) {
12780×
            Ok(Some(m)) => {
12790×
                let image = home.rootfs(&offer.blake3);
12800×
                match crate::update::copy_checked(&image, file, offer.size, &offer.blake3) {
1281
                    Ok(()) => {
12820×
                        eprintln!(
1283
                            "flow runner: fetched flow {} through the swarm: {} chunks, {} ({} from peers)",
1284
                            offer.version,
1285
                            m.chunks,
12860×
                            crate::images::human(m.bytes),
12870×
                            crate::images::human(m.peer_bytes)
1288
                        );
12890×
                        return Ok(());
1290
                    }
12910×
                    Err(e) => eprintln!("flow runner: flow {} from the swarm: {e:#}; fetching it over HTTP", offer.version),
1292
                }
1293
            }
12940×
            Ok(None) => eprintln!("flow runner: the hub has not shared flow {} with the swarm yet; fetching it over HTTP", offer.version),
12950×
            Err(e) => eprintln!("flow runner: flow {} through the swarm: {e:#}; fetching it over HTTP", offer.version),
1296
        }
12970×
    }
12980×
    hub.download_build(offer, file)
12990×
}
1300
1301
/// Held while a job takes its cache disks and images its workspace (see
1302
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1303
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1304
1305
/// Held while the first clone of any repository passes its token through
1306
/// the process environment.
1307
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1308
1309
/// One lock per cached repository: fetches into it, and exports from it,
1310
/// never overlap, while jobs of other repositories go on. A slow repository
1311
/// (one kept in a bucket, say) once held every job on the runner waiting
1312
/// behind a single global lock.
13130×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1314
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1315
        std::sync::OnceLock::new();
13160×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
13170×
    locks.entry(name.to_string()).or_default().clone()
13180×
}
1319
1320
/// Seconds, to one decimal place, for the job's log.
13210×
fn secs(d: std::time::Duration) -> String {
13220×
    format!("{:.1} s", d.as_secs_f64())
13230×
}
1324
1325
/// `image_ms`: how long fetching its image took, when the runner lacked it.
13260×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim, image_ms: Option<u64>) -> Result<Finish> {
13270×
    let started = Instant::now();
13280×
    let mut sink = LogSink {
13290×
        hub,
13300×
        job: claim.job_id,
13310×
        buf: Vec::new(),
13320×
        last: Instant::now(),
13330×
        gone: false,
13340×
        leaving: &LEAVING,
13350×
        started: Instant::now(),
13360×
        expected: claim.expected_ms.map(Duration::from_millis),
13370×
    };
13380×
    let note =
13390×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
13400×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
13410×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1342
    // Preparing a workspace: fetches into a cached repository, and exports
1343
    // from it, are one job at a time per repository (`repo_lock`); taking
1344
    // cache disks and imaging the workspace are one job at a time on the
1345
    // runner (`PREPARE`); a first clone, whose token goes through the process
1346
    // environment, one at a time (`CLONE`).
13470×
    let main_lock = repo_lock(&claim.repo);
13480×
    let asked = Instant::now();
13490×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
13500×
    if asked.elapsed().as_secs() >= 2 {
13510×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
13520×
    }
13530×
    let fetching = Instant::now();
13540×
    let repo = cached_repo(home, cfg, claim)?;
13550×
    let fetched = fetching.elapsed();
13560×
    let mut preparing = None;
13570×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
13580×
    let _ = std::fs::remove_dir_all(&scratch);
13590×
    std::fs::create_dir_all(scratch.join("tree"))?;
13600×
    let result = (|| -> Result<Finish> {
13610×
        let exporting = Instant::now();
13620×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
13630×
        main_guard.take();
13640×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1365
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1366
        // workspace and of the scope hash.
13670×
        for sub in &claim.subrepos {
13680×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
13690×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
13700×
            }
13710×
            note(
13720×
                &mut sink,
13730×
                format!(
1374
                    "fetching subrepo {} at {} for {}",
1375
                    sub.repo,
13760×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1377
                    sub.path
1378
                ),
1379
            );
13800×
            let sub_lock = repo_lock(&sub.repo);
13810×
            let asked = Instant::now();
13820×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
13830×
            if asked.elapsed().as_secs() >= 2 {
13840×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
13850×
            }
13860×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
13870×
            let sub_heads: Vec<ChangeHash> =
13880×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
13890×
            let dir = scratch.join("tree").join(&sub.path);
13900×
            std::fs::create_dir_all(&dir)?;
13910×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
13920×
            drop(sub_guard);
13930×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1394
        }
13950×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1396
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1397
        // against the blob its receipt names, then put at its path. Not part
1398
        // of the scope: they are the run's, not the repository's.
13990×
        let mut input_blobs = Vec::new();
14000×
        for (index, i) in claim.inputs.iter().enumerate() {
14010×
            let what = format!("input {} from {}", i.artifact, i.from);
14020×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
14030×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
14040×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
14050×
            input_blobs.push(blob);
1406
        }
1407
        // The syscall tier runs on the tree itself; a microVM gets an image.
14080×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
14090×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1410
        // The syscall and WASM tiers see the job's files as a directory;
1411
        // the MicroVM tier as an ext4 image.
14120×
        let dir_tier = syscall_tier || wasm_tier;
14130×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1414
        // Disk mounts that name a cache start from a kept disk (#28): a
1415
        // microVM takes an image already in place as it is, the syscall tier
1416
        // a directory (#70). Taken before the workspace is imaged: the
1417
        // sources the disk was built from give unchanged files their old
1418
        // times back (#52).
14190×
        let asked = Instant::now();
14200×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
14210×
        if asked.elapsed().as_secs() >= 2 {
14220×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
14230×
        }
14240×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
14250×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
14260×
        let cache_ctx =
14270×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
14280×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
14290×
        let mut built_from: Option<crate::cache::Sources> = None;
14300×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
14310×
            let Some(name) = &m.cache else { continue };
14320×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
14330×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
14340×
                Some(t) => {
14350×
                    if built_from.is_none() {
14360×
                        built_from = t.sources;
14370×
                    }
14380×
                    t.how
1439
                }
14400×
                None => format!("cache {name}: none kept yet, an empty disk"),
1441
            };
14420×
            note(&mut sink, format!("{} ({})", how, m.target));
1443
            // What the job reads is seen when the disk is pruned (#72).
14440×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
14450×
                note(&mut sink, format!("cache {name}: {e:#}"));
14460×
            }
14470×
            cached.push((i, key, how));
1448
        }
1449
        // What the job reads or writes on its cache from now on is what it
1450
        // used; the rest may be pruned before the cache is kept (#72).
14510×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
14520×
        let sources = if cached.is_empty() {
14530×
            crate::cache::Sources::new()
1454
        } else {
14550×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
14560×
            if built_from.is_some() {
14570×
                note(
14580×
                    &mut sink,
14590×
                    format!(
14600×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
14610×
                        sources.len()
14620×
                    ),
14630×
                );
14640×
            }
14650×
            sources
1466
        };
1467
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1468
        // over the cache, before the same exec runs again; the receipt
1469
        // lists it among the job's inputs.
14700×
        if let Some(blob) = &claim.checkpoint {
14710×
            if dir_tier {
14720×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
14730×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
14740×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
14750×
                }
14760×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
14770×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
14780×
                note(
14790×
                    &mut sink,
14800×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
14810×
                );
14820×
                input_blobs.push(Repo::blob_ref(&bytes).0);
14830×
            } else {
14840×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
14850×
            }
14860×
        }
14870×
        if !dir_tier {
14880×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
14890×
            std::fs::remove_dir_all(scratch.join("tree"))?;
14900×
        }
14910×
        preparing.take();
1492
        // Cancelled while it was being prepared: no sandbox.
14930×
        if microvm::Sink::cancelled(&mut sink) {
14940×
            return Ok(cancelled());
14950×
        }
14960×
        if wasm_tier {
14970×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
14980×
        } else {
14990×
            note(
15000×
                &mut sink,
15010×
                format!(
1502
                    "{}: {} {}, {} MiB, rootfs {}",
15030×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1504
                    claim.sandbox.cpus,
15050×
                    if syscall_tier { "CPU" } else { "vCPU" },
1506
                    claim.sandbox.memory_mib,
15070×
                    &claim.sandbox.rootfs[..12]
1508
                ),
1509
            );
1510
        }
15110×
        let timeout = Duration::from_secs(claim.timeout_s);
1512
        // Where the time goes (oxygenflow#35): what came before the
1513
        // sandbox, the sandbox, and what comes after.
15140×
        let prepare_ms = started.elapsed().as_millis() as u64;
15150×
        let sandbox_started = Instant::now();
15160×
        let mut outcome = if wasm_tier {
15170×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
15180×
        } else if syscall_tier {
15190×
            let group = format!("job-{}", claim.job_id);
15200×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1521
        } else {
15220×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1523
        };
15240×
        let run_ms = sandbox_started.elapsed().as_millis() as u64;
15250×
        if outcome.cancelled {
1526
            // Handed back as the runner leaves: its checkpoints first, for
1527
            // the next attempt (oxygenflow#77).
15280×
            if leaving().is_some() && !job.checkpoints.is_empty() {
15290×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
15300×
            }
15310×
            return Ok(cancelled());
15320×
        }
1533
        // The receipt says what a cached disk started from.
15340×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
15350×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
15360×
        for (i, key, how) in &cached {
15370×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
15380×
        }
1539
        // A passing job's artifacts, read from its disks and uploaded; a
1540
        // declared artifact that cannot be kept fails the job. A failing
1541
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1542
        // its receipt, and one it cannot keep is only noted.
15430×
        let mut outputs = vec![];
15440×
        let mut output_error = None;
15450×
        let passed = outcome.exit_code == Some(0);
15460×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
15470×
        for o in wanted {
15480×
            if o.kind == flow_core::OutputKind::Report {
15490×
                let read = if dir_tier {
15500×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15510×
                    crate::outputs::read_report_dir(&dir, &inner)
1552
                } else {
15530×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15540×
                    crate::outputs::read_report(&image, &inner, &scratch)
1555
                };
15560×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
15570×
                match kept {
15580×
                    Ok((blob, files, bytes)) => {
15590×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15600×
                        let hex = blob.to_hex();
15610×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
15620×
                        if passed {
15630×
                            outputs.push(blob.0);
15640×
                        }
1565
                    }
15660×
                    Err(e) if passed => {
15670×
                        output_error = Some(format!("report {}: {e:#}", o.name));
15680×
                        break;
1569
                    }
15700×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1571
                }
15720×
                continue;
15730×
            }
15740×
            let read = if dir_tier {
15750×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15760×
                crate::outputs::read_dir_file(&dir, &inner)
1577
            } else {
15780×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15790×
                crate::outputs::read(&image, &inner, &scratch)
1580
            };
15810×
            let kept = read.and_then(|bytes| {
15820×
                let blob = Repo::blob_ref(&bytes);
15830×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
15840×
                if named != blob.to_hex() {
15850×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
15860×
                }
15870×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15880×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
15890×
                Ok(blob.0)
15900×
            });
15910×
            match kept {
15920×
                Ok(b) if passed => outputs.push(b),
15930×
                Ok(_) => {}
15940×
                Err(e) if passed => {
15950×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
15960×
                    break;
1597
                }
15980×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1599
            }
1600
        }
16010×
        if let Some(e) = &output_error {
16020×
            note(&mut sink, e.clone());
16030×
        }
16040×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
16050×
            job_name: claim.job.name.clone(),
16060×
            pipeline_hash: hex32(&claim.pipeline_hash),
16070×
            scope_tree_hash: scope_hash,
16080×
            inputs: input_blobs.clone(),
16090×
            environment: outcome.environment.hash(),
16100×
            outputs,
16110×
            exit_code: code as u32,
16120×
            duration_ms: outcome.duration_ms,
16130×
        });
16140×
        let signed_receipt = match &receipt {
16150×
            Some(r) => {
16160×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
16170×
                if cfg.keyless {
16180×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
16190×
                        Ok(k) => signed = k,
16200×
                        Err(e) => {
16210×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1622
                        }
1623
                    }
16240×
                }
16250×
                Some(hex::encode(signed.encode()))
1626
            }
16270×
            None => None,
1628
        };
1629
        // Measured before a cached disk leaves the scratch directory.
16300×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1631
        // A passing job's cached disks are pruned and kept (#72); a
1632
        // failing job's are thrown away, so nothing it wrote reaches a
1633
        // later job.
16340×
        let kept = passed && output_error.is_none();
16350×
        for (i, key, _) in &cached {
16360×
            let disk = crate::cache::disk_path(form, &scratch, *i);
16370×
            let m = disk_mounts[*i];
16380×
            let prune = crate::cache::Prune {
16390×
                started: cache_started,
16400×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
16410×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1642
            };
16430×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
16440×
                Ok(Some(line)) => note(&mut sink, line),
16450×
                Ok(None) => {}
16460×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1647
            }
1648
        }
16490×
        let total_ms = started.elapsed().as_millis() as u64;
16500×
        let mut phases: std::collections::BTreeMap<String, u64> =
16510×
            [("prepare", prepare_ms), ("run", run_ms), ("finish", total_ms.saturating_sub(prepare_ms + run_ms))]
16520×
                .into_iter()
16530×
                .map(|(k, v)| (k.to_string(), v))
16540×
                .collect();
16550×
        if let Some(ms) = image_ms {
16560×
            phases.insert("image".into(), ms);
16570×
        }
1658
        Ok(Finish {
16590×
            phases,
16600×
            exit_code: outcome.exit_code,
16610×
            duration_ms: total_ms,
16620×
            receipt,
16630×
            signed_receipt,
16640×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1665
            // What the job took (oxygenflow#41): its disks are sparse files
1666
            // in the scratch directory, so their blocks now are their peak.
16670×
            peak_disk_mib,
16680×
            peak_memory_mib: outcome.peak_memory_mib,
1669
        })
1670
    })();
16710×
    let _ = workspace::remove_tree(&scratch);
16720×
    sink.flush();
16730×
    result
16740×
}
1675
1676
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1677
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1678
/// the claim, so the runner vouches only for what it fetched.
1679
/// Upload a report's files, then its manifest under the report's name, and
1680
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1681
/// the manifest's blob, the file count and their total size.
16820×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
16830×
    let mut listed = Vec::with_capacity(files.len());
16840×
    let mut total = 0u64;
16850×
    for (path, bytes) in files {
16860×
        let blob = Repo::blob_ref(bytes).to_hex();
16870×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
16880×
        if named != blob {
16890×
            bail!("the hub kept {path} as {named}, not {blob}");
16900×
        }
16910×
        total += bytes.len() as u64;
16920×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1693
    }
16940×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
16950×
    let blob = Repo::blob_ref(&manifest);
16960×
    let named = hub.artifact(job, name, &manifest)?;
16970×
    if named != blob.to_hex() {
16980×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
16990×
    }
17000×
    Ok((blob, files.len(), total))
17010×
}
1702
17030×
fn sign_receipt(
17040×
    repo: &Repo,
17050×
    heads: &[ChangeHash],
17060×
    cfg: &RunnerConfig,
17070×
    key: &RunnerKey,
17080×
    claim: &Claim,
17090×
    receipt: &Receipt,
17100×
) -> Result<oxy_core::receipt::SignedReceipt> {
17110×
    let state = state_of(heads);
17120×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
17130×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
17140×
}
1715
1716
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1717
/// just before signing, so the certificate covers the moment the hub
1718
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1719
/// receipt signed: nothing long-lived signs.
17200×
fn sign_keyless(
17210×
    repo: &Repo,
17220×
    heads: &[ChangeHash],
17230×
    cfg: &RunnerConfig,
17240×
    hub: &Hub,
17250×
    claim: &Claim,
17260×
    receipt: &Receipt,
17270×
) -> Result<oxy_core::receipt::SignedReceipt> {
17280×
    let sk = oxy_core::identity::SecretKey::generate();
17290×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
17300×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
17310×
    let id = sk.identity(&name, "", now);
17320×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
17330×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
17340×
    let state = state_of(heads);
17350×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
17360×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
17370×
}
1738
1739
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
17400×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1741
    use oxy_core::hash::{hash_object, ObjectType};
17420×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
17430×
}
1744
17450×
fn hex32(s: &str) -> [u8; 32] {
17460×
    let mut out = [0; 32];
17470×
    if let Ok(v) = hex::decode(s) {
17480×
        if v.len() == 32 {
17490×
            out.copy_from_slice(&v);
17500×
        }
17510×
    }
17520×
    out
17530×
}
1754
1755
/// Whether a network error is worth another try: DNS, a refused or reset
1756
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1757
/// hub restarts (oxygenhub#111).
17588×
fn transient(msg: &str) -> bool {
17598×
    let m = msg.to_lowercase();
17608×
    [
17618×
        "dns failed",
17628×
        "name resolution",
17638×
        "connection refused",
17648×
        "connection reset",
17658×
        "timed out",
17668×
        "timeout",
17678×
        "http 502",
17688×
        "http 503",
17698×
        "http 504",
17708×
        "broken pipe",
17718×
        "unexpected eof",
17728×
    ]
17738×
    .iter()
177447×
    .any(|k| m.contains(k))
17758×
}
1776
1777
/// Run `f` again after a transient network error, waiting `waits` between
1778
/// tries (about a minute in all), and give up on any other error at once.
17793×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
17803×
    let mut tries = waits.iter();
1781
    loop {
17827×
        match f() {
17831×
            Ok(v) => return Ok(v),
17846×
            Err(e) => match tries.next() {
17855×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
17862×
                _ => return Err(e),
1787
            },
1788
        }
1789
    }
17903×
}
1791
1792
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1793
const FETCH_WAITS: [Duration; 5] =
1794
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1795
1796
/// The runner's copy of a repository, fetched up to date with the job's token.
17970×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
17980×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
17990×
}
1800
1801
/// The runner's copy of `repo`, cloned or fetched with `token`.
18020×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
18030×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
18040×
    let set_remote = |repo: &mut Repo| -> Result<()> {
18050×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
18060×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
18070×
        if let Some(ca) = &cfg.ca {
18080×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
18090×
        }
18100×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
18110×
    };
18120×
    if dir.join(".oxy").is_dir() {
18130×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
18140×
        set_remote(&mut repo)?;
18150×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
18160×
        return Ok(repo);
18170×
    }
1818
    // First job for this repository: clone with the job's token, which goes
1819
    // through the process environment, so one clone at a time.
18200×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
18210×
    std::env::set_var("OXY_TOKEN", token);
18220×
    if let Some(ca) = &cfg.ca {
18230×
        std::env::set_var("OXY_CA", ca);
18240×
    }
18250×
    let cloned = with_retries(&FETCH_WAITS, || {
18260×
        let _ = std::fs::remove_dir_all(&dir);
18270×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
18280×
    });
18290×
    std::env::remove_var("OXY_TOKEN");
18300×
    std::env::remove_var("OXY_CA");
18310×
    let mut repo = cloned.map_err(|e| {
18320×
        let _ = std::fs::remove_dir_all(&dir);
18330×
        anyhow::anyhow!("clone {}: {e}", clone_url)
18340×
    })?;
18350×
    set_remote(&mut repo)?;
18360×
    Ok(repo)
18370×
}
1838
1839
#[cfg(test)]
1840
mod tests {
1841
1842
    /// #98: register keeps a copy of the CA in the home, by absolute path,
1843
    /// and keeping the home's own copy again is a no-op.
1844
    #[test]
18451×
    fn the_ca_is_kept_in_the_home_by_absolute_path() {
18461×
        let home = tempfile::tempdir().unwrap();
18471×
        let elsewhere = tempfile::tempdir().unwrap();
18481×
        let given = elsewhere.path().join("ca.pem");
18491×
        std::fs::write(&given, "PEM").unwrap();
18501×
        let kept = super::keep_ca(home.path(), &given).unwrap();
18511×
        assert!(kept.is_absolute() && kept.ends_with(crate::home::CA_PEM), "{kept:?}");
18521×
        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "PEM");
18531×
        std::fs::remove_file(&given).unwrap();
18541×
        assert_eq!(super::keep_ca(home.path(), &kept).unwrap(), kept, "the home's copy again");
18551×
        assert_eq!(std::fs::read_to_string(&kept).unwrap(), "PEM");
18561×
    }
1857
1858
    #[test]
18591×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
18601×
        let dir = tempfile::tempdir().unwrap();
18611×
        let bytes = b"the reviewed plan";
18621×
        let blob = Repo::blob_ref(bytes).to_hex();
18631×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
18646×
            artifact: "tfplan".into(),
18656×
            from: "plan".into(),
18666×
            path: path.into(),
18676×
            blob: blob.into(),
18686×
        };
18691×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
18701×
        assert_eq!(hex::encode(got), blob);
18711×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
18721×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
18731×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
18741×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
18754×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
18764×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1877
        }
18781×
    }
1879
1880
    use super::*;
1881
1882
    #[test]
18831×
    fn a_runner_names_what_stops_a_sandbox() {
18841×
        let dir = tempfile::tempdir().unwrap();
18851×
        let home = Home::locate(Some(dir.path())).unwrap();
18861×
        let bytes = b"not really ext4";
18871×
        let hash = blake3::hash(bytes).to_hex().to_string();
18881×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18891×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1890
        }))
18911×
        .unwrap();
18926×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
18931×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
18941×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
18951×
        sb.rootfs = hash.clone();
18961×
        assert_eq!(problem(&sb, Some(4096)), None);
18971×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
18981×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
18991×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
19001×
        sb.arch = Some("aarch64".into());
19011×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
19021×
        sb.arch = None;
19031×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
19041×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
19051×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
19061×
    }
1907
1908
    #[test]
19091×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1910
        // An image fetched or imported with no recorded architecture, built
1911
        // for riscv64: the runner reads its shell, records it, and declines
1912
        // instead of running it and failing (spec §11.2, §11.5).
19131×
        let dir = tempfile::tempdir().unwrap();
19141×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
19151×
        let tree = dir.path().join("tree");
19161×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
19171×
        let mut elf = vec![0u8; 64];
19181×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
19191×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
19201×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
19211×
        let img = dir.path().join("rootfs.ext4");
19221×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
19231×
        if !made.is_ok_and(|s| s.success()) {
19240×
            eprintln!("mkfs.ext4 not found: skipped");
19250×
            return;
19261×
        }
19271×
        let hash = crate::home::hash_file(&img).unwrap();
19281×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
19291×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
19301×
        assert!(!home.image_manifest(&hash).exists());
19311×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
19321×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1933
        }))
19341×
        .unwrap();
19351×
        assert_eq!(
19361×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
19371×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1938
        );
19391×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1940
        // Learned: recorded once, and reported with the runner's claims.
19411×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
19421×
        assert_eq!(manifest["arch"], "riscv64");
19431×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
19441×
    }
1945
1946
    #[test]
19471×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
19481×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
19491×
        assert!(transient("HTTP 503: the hub is restarting"));
19501×
        assert!(!transient("HTTP 404: no such repository"));
19511×
        let mut n = 0;
19523×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
19533×
            n += 1;
19543×
            if n < 3 {
19552×
                Err(anyhow::anyhow!("connection refused"))
1956
            } else {
19571×
                Ok(7)
1958
            }
19593×
        });
19601×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
19611×
        let mut m = 0;
19621×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
19631×
            m += 1;
19641×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
19651×
        });
19661×
        assert!(got.is_err());
19671×
        assert_eq!(m, 1, "a refusal is not tried again");
19681×
        let mut k = 0;
19693×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
19703×
            k += 1;
19713×
            Err(anyhow::anyhow!("timed out"))
19723×
        });
19731×
        assert!(got.is_err());
19741×
        assert_eq!(k, 3, "gives up after the last wait");
19751×
    }
1976
1977
    /// A hub that answers each request with the next of `codes`, counting them.
19789×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
19799×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
19809×
    }
1981
1982
    /// A hub at `listener` answering each request with the next of `codes`.
198311×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1984
        use std::io::{Read, Write};
198511×
        let addr = listener.local_addr().unwrap();
198611×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
198711×
        let count = seen.clone();
198811×
        std::thread::spawn(move || {
198923×
            for code in codes {
199023×
                let (mut s, _) = listener.accept().unwrap();
1991
                // Read the whole request (headers, then Content-Length bytes
1992
                // of body) before answering: closing early would reset the
1993
                // connection while the client is still sending.
199423×
                let mut req = Vec::new();
199523×
                let mut buf = [0u8; 8192];
1996
                loop {
199738×
                    let n = s.read(&mut buf).unwrap_or(0);
199838×
                    if n == 0 {
19990×
                        break;
200038×
                    }
200138×
                    req.extend_from_slice(&buf[..n]);
200238×
                    let text = String::from_utf8_lossy(&req);
200338×
                    if let Some(end) = text.find("\r\n\r\n") {
200438×
                        let len = text[..end]
200538×
                            .lines()
2006296×
                            .find_map(|l| {
2007296×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
2008296×
                            })
200938×
                            .unwrap_or(0);
201038×
                        if req.len() >= end + 4 + len {
201123×
                            break;
201215×
                        }
20130×
                    }
2014
                }
201523×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
201623×
                let reason = if code == 204 { "No Content" } else { "Error" };
201723×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
2018
            }
201911×
        });
202011×
        (format!("http://{addr}"), seen)
202111×
    }
2022
2023
    /// A hub that answers one request with `body` (status 200) and hands
2024
    /// back what it was sent.
20251×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
2026
        use std::io::{Read, Write};
20271×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20281×
        let addr = listener.local_addr().unwrap();
20291×
        let (tx, rx) = std::sync::mpsc::channel();
20301×
        std::thread::spawn(move || {
20311×
            let (mut s, _) = listener.accept().unwrap();
20321×
            let mut req = Vec::new();
20331×
            let mut buf = [0u8; 65536];
2034
            loop {
20351×
                let n = s.read(&mut buf).unwrap_or(0);
20361×
                if n == 0 {
20370×
                    break;
20381×
                }
20391×
                req.extend_from_slice(&buf[..n]);
20401×
                let text = String::from_utf8_lossy(&req);
20411×
                if let Some(end) = text.find("\r\n\r\n") {
20421×
                    let len = text[..end]
20431×
                        .lines()
20447×
                        .find_map(|l| {
20457×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
20467×
                        })
20471×
                        .unwrap_or(0);
20481×
                    if req.len() >= end + 4 + len {
20491×
                        break;
20500×
                    }
20510×
                }
2052
            }
20531×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
20541×
            let _ = write!(
20551×
                s,
2056
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
20571×
                body.len()
2058
            );
20591×
        });
20601×
        (format!("http://{addr}"), rx)
20611×
    }
2062
2063
    #[test]
20641×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
2065
        use std::os::unix::fs::PermissionsExt;
20661×
        let dir = tempfile::tempdir().unwrap();
20671×
        let home = Home::locate(Some(dir.path())).unwrap();
20681×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
20691×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
20701×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
20711×
        let req = sent.recv().unwrap();
20721×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
20731×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
20741×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
20751×
        let key = home.runner_key("plex").unwrap();
20761×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
20771×
        let path = dir.path().join(crate::home::RUNNER_TOML);
20781×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
2079
        // The runner then starts from runner.toml.
20801×
        let again = Home::locate(Some(dir.path())).unwrap();
20811×
        let cfg = again.config.runner.unwrap();
20821×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
20831×
        assert_eq!(cfg.labels, ["gpu"]);
20841×
    }
2085
2086
    /// A hub that answers certify with a certificate `sign_as` signs for
2087
    /// `cert_key`, and publishes `published` as its key: two requests.
20883×
    fn fake_certify_hub(
20893×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
20903×
        cert_key: oxy_core::identity::Identity,
20913×
        published: oxy_core::identity::Identity,
20923×
    ) -> String {
2093
        use std::io::{Read, Write};
20943×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20953×
        let addr = listener.local_addr().unwrap();
20963×
        std::thread::spawn(move || {
20973×
            for _ in 0..2 {
20986×
                let Ok((mut s, _)) = listener.accept() else { return };
20996×
                let mut req = Vec::new();
21006×
                let mut buf = [0u8; 65536];
2101
                loop {
21027×
                    let n = s.read(&mut buf).unwrap_or(0);
21037×
                    if n == 0 {
21040×
                        break;
21057×
                    }
21067×
                    req.extend_from_slice(&buf[..n]);
21077×
                    let text = String::from_utf8_lossy(&req);
21087×
                    if let Some(end) = text.find("\r\n\r\n") {
21097×
                        let len = text[..end]
21107×
                            .lines()
211147×
                            .find_map(|l| {
211247×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
211347×
                            })
21147×
                            .unwrap_or(0);
21157×
                        if req.len() >= end + 4 + len {
21166×
                            break;
21171×
                        }
21180×
                    }
2119
                }
21206×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
21216×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
21223×
                    let cert = oxy_core::cert::SignedCertificate::sign(
21233×
                        oxy_core::cert::Certificate {
21243×
                            key: cert_key.clone(),
21253×
                            issuer: sign_as.0.hash(),
21263×
                            subject: "repo:andy/demo:bookmark:main".into(),
21273×
                            claims: vec![],
21283×
                            scope: oxy_core::identity::Scope::SEAL,
21293×
                            not_before: 1,
21303×
                            expires: 600_001,
21313×
                            grant: None,
21323×
                        },
21333×
                        &sign_as.0,
21343×
                        &sign_as.1,
2135
                    );
21363×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
2137
                } else {
21383×
                    published.encode()
2139
                };
21406×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
21416×
                let _ = s.write_all(&body);
2142
            }
21433×
        });
21443×
        format!("http://{addr}")
21453×
    }
2146
2147
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2148
    /// is for its fresh key and signed by the key the hub publishes.
2149
    #[test]
21501×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2151
        use oxy_core::identity::SecretKey;
21521×
        let hub_sk = SecretKey::generate();
21531×
        let hub_id = hub_sk.identity("hub", "", 1);
21541×
        let sk = SecretKey::generate();
21551×
        let id = sk.identity("earth-1 job 7", "", 1);
21561×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2157
21581×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
21591×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
21601×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2161
21621×
        let mallory_sk = SecretKey::generate();
21631×
        let mallory = mallory_sk.identity("mallory", "", 1);
21641×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
21651×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
21661×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2167
21681×
        let other = SecretKey::generate().identity("other", "", 1);
21691×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
21701×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
21711×
        assert!(e.contains("another key"), "{e}");
21721×
    }
2173
217416×
    fn hub_at(base: String) -> Hub {
217516×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
217616×
    }
2177
2178
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2179
    /// hub attests; a peer or a proxy cannot change what is installed.
2180
    #[test]
21811×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
21821×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
21832×
        let serve = |bytes: Vec<u8>| {
21842×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
21852×
            let addr = listener.local_addr().unwrap();
21862×
            std::thread::spawn(move || {
2187
                use std::io::{Read, Write};
21882×
                let (mut s, _) = listener.accept().unwrap();
21892×
                let mut buf = [0u8; 4096];
21902×
                let _ = s.read(&mut buf);
21912×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
21922×
                let _ = s.write_all(&bytes);
21932×
            });
21942×
            format!("http://{addr}")
21952×
        };
21961×
        let offer = flow_core::api::UpdateOffer {
21971×
            version: "0.3.2".into(),
21981×
            asset: "flow-linux-x86_64".into(),
21991×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
22001×
            blake3: blake3::hash(&body).to_hex().to_string(),
22011×
            size: body.len() as u64,
22021×
            ..Default::default()
22031×
        };
22041×
        let dir = tempfile::tempdir().unwrap();
22051×
        let to = dir.path().join("flow-0.3.2");
22061×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
22071×
        assert_eq!(std::fs::read(&to).unwrap(), body);
22081×
        std::fs::remove_file(&to).unwrap();
22091×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
22101×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
22111×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
22121×
    }
2213
2214
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2215
    /// through server errors, and a refusal ends the trying at once.
2216
    #[test]
22171×
    fn a_result_is_reported_until_the_hub_takes_it() {
22181×
        let f = Finish {
22191×
            exit_code: Some(0),
22201×
            duration_ms: 1,
22211×
            receipt: None,
22221×
            signed_receipt: None,
22231×
            error: None,
22241×
            peak_disk_mib: None,
22251×
            peak_memory_mib: None,
22261×
            phases: Default::default(),
22271×
        };
22281×
        let quick = Duration::from_millis(10);
22291×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
22301×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
22311×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
22321×
        let (base, seen) = fake_hub(vec![409]);
22331×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
22341×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
22351×
    }
2236
2237
    #[test]
22381×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
22391×
        let quick = [Duration::from_millis(10); 3];
22401×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
22411×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
22421×
        assert!(r.is_none());
22431×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2244
22451×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
22461×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
22471×
        assert!(e.contains("HTTP 500"), "{e}");
22481×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2249
22501×
        let (base, seen) = fake_hub(vec![401]);
22511×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
22521×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
22531×
    }
2254
2255
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2256
2257
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2258
    /// cancelled, having sent what the job said so far, and the job is
2259
    /// handed back to the hub.
2260
    #[test]
22611×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2262
        use microvm::Sink;
22631×
        let leaving = std::sync::Mutex::new(None);
22641×
        let (base, seen) = fake_hub(vec![204, 204]);
22651×
        let hub = hub_at(base);
22661×
        let mut sink = LogSink {
22671×
            hub: &hub,
22681×
            job: 7,
22691×
            buf: Vec::new(),
22701×
            last: Instant::now(),
22711×
            gone: false,
22721×
            leaving: &leaving,
22731×
            started: Instant::now(),
22741×
            expected: None,
22751×
        };
22761×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
22771×
        assert!(!sink.cancelled());
22781×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
22791×
        assert!(sink.cancelled());
22801×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
22811×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
22821×
        hub.release(7, "off Wi-Fi").unwrap();
22831×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
22841×
    }
2285
2286
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2287
    /// it runs on; one that will not, or whose time is unknown, is handed
2288
    /// back at once, and any job still running when the notice is up.
2289
    #[test]
22901×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2291
        use microvm::Sink;
22921×
        let (base, _) = fake_hub(vec![204; 8]);
22931×
        let hub = hub_at(base);
22941×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
22951×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
22964×
            hub: &hub,
2297
            job: 1,
22984×
            buf: Vec::new(),
22994×
            last: Instant::now(),
2300
            gone: false,
23014×
            leaving: &leaving,
23024×
            started: Instant::now() - Duration::from_secs(ran),
23034×
            expected: expected.map(Duration::from_secs),
23044×
        };
23051×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
23061×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
23071×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
23081×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
23091×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
23101×
    }
2311
2312
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2313
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2314
    #[test]
23151×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2316
        use microvm::Sink;
23172×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
23181×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
23191×
        let (base, seen) = fake_hub(vec![204]);
23201×
        let hub = hub_at(base);
23211×
        let mut sink = LogSink {
23221×
            hub: &hub,
23231×
            job: 1,
23241×
            buf: Vec::new(),
23251×
            last: quiet,
23261×
            gone: false,
23271×
            leaving: &NOT_LEAVING,
23281×
            started: Instant::now(),
23291×
            expected: None,
23301×
        };
23311×
        assert!(!sink.cancelled());
23321×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
23331×
        assert_eq!(n(&seen), 1);
2334
23351×
        let (base, seen) = fake_hub(vec![409]);
23361×
        let hub = hub_at(base);
23371×
        let mut sink = LogSink {
23381×
            hub: &hub,
23391×
            job: 1,
23401×
            buf: Vec::new(),
23411×
            last: quiet,
23421×
            gone: false,
23431×
            leaving: &NOT_LEAVING,
23441×
            started: Instant::now(),
23451×
            expected: None,
23461×
        };
23471×
        assert!(sink.cancelled());
23481×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
23491×
        sink.flush();
23501×
        assert!(sink.cancelled());
23511×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
23521×
    }
2353
2354
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2355
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2356
    /// no lines.
2357
    #[test]
23581×
    fn a_job_outlasts_a_hub_restart() {
23592×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2360
        // A port nobody listens on yet: the hub is restarting.
23611×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23621×
        let base = format!("http://127.0.0.1:{port}");
23631×
        let hub = hub_at(base.clone());
2364
2365
        // Log lines sent while it is away are kept, and go when it is back.
23661×
        let mut sink = LogSink {
23671×
            hub: &hub,
23681×
            job: 1,
23691×
            buf: Vec::new(),
23701×
            last: Instant::now(),
23711×
            gone: false,
23721×
            leaving: &NOT_LEAVING,
23731×
            started: Instant::now(),
23741×
            expected: None,
23751×
        };
2376450×
        for i in 0..450 {
2377450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2378450×
        }
23791×
        sink.send();
23801×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
23811×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
23821×
        sink.send();
23831×
        assert!(sink.buf.is_empty() && !sink.gone);
23841×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2385
2386
        // An upload waits for the hub to come back, through refused
2387
        // connections and server errors alike.
23881×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23891×
        let url = format!("http://127.0.0.1:{port}/x");
23901×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
23911×
        let later = std::thread::spawn(move || {
23921×
            std::thread::sleep(Duration::from_millis(150));
23931×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
23941×
        });
23951×
        let quick = [Duration::from_millis(50); 20];
23965×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
23971×
        assert_eq!(r.status(), 204);
23981×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2399
        // Without `connection`, a hub that cannot be reached ends it at once.
24001×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
24011×
        let url = format!("http://127.0.0.1:{port}/x");
24021×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
24031×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
24041×
    }
2405
2406
    /// oxygenflow#50: the first stop drains (the second, not called here,
2407
    /// exits at once).
2408
    #[test]
24091×
    fn a_stop_drains_the_runner() {
24101×
        assert!(!stopping());
24111×
        on_stop(libc::SIGTERM);
24121×
        assert!(stopping(), "told to stop, it claims nothing more");
2413
        // An embedded runner starts afresh, and stop() drains it the same way.
24141×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
24151×
        stop();
24161×
        assert!(stopping());
24171×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
24181×
    }
2419
2420
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2421
    #[test]
24221×
    fn unsent_log_lines_are_bounded() {
24231×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
24241×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
24251×
        let mut sink = LogSink {
24261×
            hub: &hub,
24271×
            job: 1,
24281×
            buf: Vec::new(),
24291×
            last: Instant::now(),
24301×
            gone: false,
24311×
            leaving: &NOT_LEAVING,
24321×
            started: Instant::now(),
24331×
            expected: None,
24341×
        };
243550010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
24361×
        sink.send();
24371×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
24381×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
24391×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
24401×
    }
2441
2442
    #[test]
24431×
    fn the_budget_admits_jobs_that_fit() {
24441×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
24457×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
24461×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
24471×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
24481×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
24491×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
24501×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
24511×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
24521×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
24531×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
24541×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
24551×
    }
2456
2457
    #[test]
24581×
    fn a_claim_never_asks_for_more_memory_than_the_host_has_free() {
24591×
        assert_eq!(claim_memory(None, Some(6541)), Some(6541), "idle: the host's free memory, not unlimited");
24601×
        assert_eq!(claim_memory(Some(16_384), Some(6541)), Some(6541));
24611×
        assert_eq!(claim_memory(Some(4096), Some(6541)), Some(4096), "the budget when it is smaller");
24621×
        assert_eq!(claim_memory(None, None), None, "nothing known: no limit, as before");
24631×
        assert_eq!(claim_memory(Some(4096), None), Some(4096));
24641×
    }
2465
}