OXYGENHUB

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

823 of 1823 lines run, 94 of 420 functions · run #206 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×
    }
510×
}
52
53
pub struct Hub {
54
    base: String,
55
    token: String,
56
    agent: ureq::Agent,
57
}
58
59
impl Hub {
600×
    pub fn new(cfg: &RunnerConfig) -> Result<Hub> {
610×
        let tls = oxy_core::protocol::tls_client_config(cfg.ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
620×
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
630×
        Ok(Hub { base: cfg.hub.trim_end_matches('/').to_string(), token: cfg.token.clone(), agent })
640×
    }
65
66
    /// POST to the hub. A server error (5xx) means nothing was committed,
67
    /// so it is tried again after 1, 2 and 4 seconds before giving up: a
68
    /// busy hub costs a job a few seconds, not its log lines or its claim.
698×
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
708×
        self.post_with(path, body, &RETRY_DELAYS)
718×
    }
72
7311×
    fn post_with(&self, path: &str, body: &impl serde::Serialize, delays: &[Duration]) -> Result<Option<ureq::Response>> {
7411×
        let url = format!("{}/api/v1{path}", self.base);
7516×
        let r = retrying(&url, delays, false, || {
7616×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
7716×
        })?;
786×
        Ok(if r.status() == 204 { None } else { Some(r) })
7911×
    }
80
81
    /// POST what a job leaves behind (oxygenflow#49): through a hub that is
82
    /// away for a few minutes, as while a deploy restarts it, so a job's
83
    /// declines and uploads outlast it.
841×
    fn post_patiently(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
851×
        let url = format!("{}/api/v1{path}", self.base);
861×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
871×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
881×
        })?;
891×
        Ok(if r.status() == 204 { None } else { Some(r) })
901×
    }
91
920×
    pub fn claim(&self, req: &ClaimRequest) -> Result<Option<Claim>> {
930×
        match self.post("/flow/claim", req)? {
940×
            Some(r) => Ok(Some(r.into_json()?)),
950×
            None => Ok(None),
96
        }
970×
    }
98
99
    /// Hand job `job` back, saying why this runner will not run it.
1000×
    pub fn decline(&self, job: i64, reason: &str) -> Result<()> {
1010×
        self.post_patiently(&format!("/flow/jobs/{job}/decline"), &Decline { reason: reason.into() })?;
1020×
        Ok(())
1030×
    }
104
105
    /// Hand back a job this runner holds as it leaves (oxygenflow#76): the
106
    /// hub queues it again ahead of new work for another runner.
1071×
    pub fn release(&self, job: i64, reason: &str) -> Result<()> {
1081×
        self.post_patiently(&format!("/flow/jobs/{job}/release"), &Decline { reason: reason.into() })?;
1091×
        Ok(())
1101×
    }
111
112
    /// Say this runner is there while it claims nothing: its slots are full,
113
    /// or it is draining (oxygenhub#243). Once, no retries: the next comes
114
    /// soon. A hub without the endpoint (404) is not an error.
115
    /// A ten-minute certificate for `identity`, asked with a job's token
116
    /// (keyless, oxygenhub#241), and the identity of the hub's key that
117
    /// issued it, from `/.well-known/oxyhub-key`.
1183×
    pub fn certify(
1193×
        &self,
1203×
        job_token: &str,
1213×
        identity: &oxy_core::identity::Identity,
1223×
        proof: &oxy_core::identity::Signature,
1233×
    ) -> Result<(oxy_core::cert::SignedCertificate, oxy_core::identity::Identity)> {
124
        use oxy_core::dsse::{base64, base64_decode};
1253×
        let body = serde_json::json!({
1263×
            "identity": base64(&identity.encode()),
1273×
            "proof": base64(&oxy_core::cbor::encode(&proof.to_value())),
1283×
            "scope": "seal",
129
        });
1303×
        let url = format!("{}/api/v1/keyless/certify", self.base);
1313×
        let r = self
1323×
            .agent
1333×
            .post(&url)
1343×
            .set("Authorization", &format!("Bearer {job_token}"))
1353×
            .send_json(body)
1363×
            .map_err(|e| anyhow::anyhow!("asking the hub to certify the key: {e}"))?;
1373×
        let v: serde_json::Value = r.into_json()?;
1383×
        let cert = base64_decode(v["certificate"].as_str().unwrap_or(""))
1393×
            .context("the hub's answer has no certificate")
1403×
            .and_then(|b| oxy_core::cert::SignedCertificate::decode(&b).map_err(|e| anyhow::anyhow!("{e}")))?;
1413×
        let mut bytes = Vec::new();
1423×
        std::io::Read::read_to_end(
1433×
            &mut self.agent.get(&format!("{}/.well-known/oxyhub-key", self.base)).call()?.into_reader(),
1443×
            &mut bytes,
1450×
        )?;
1463×
        let issuer = oxy_core::identity::Identity::decode(&bytes)?;
1473×
        if issuer.hash() != cert.cert.issuer || cert.verify(&issuer).is_err() {
1481×
            bail!("the certificate is not signed by the hub's published key");
1492×
        }
1502×
        if cert.cert.key_id() != identity.hash() {
1511×
            bail!("the hub certified another key");
1521×
        }
1531×
        Ok((cert, issuer))
1543×
    }
155
1560×
    pub fn heartbeat(&self) -> Result<()> {
1570×
        match self.post_with("/flow/runners/heartbeat", &serde_json::json!({}), &[]) {
1580×
            Ok(_) => Ok(()),
1590×
            Err(e) if format!("{e:#}").contains("404") => Ok(()),
1600×
            Err(e) => Err(e),
161
        }
1620×
    }
163
164
    /// The update policy for this runner and the build it should run
165
    /// (oxygenhub#322); `None` from a hub without runner updates.
1660×
    pub fn update_answer(&self) -> Result<Option<flow_core::api::UpdateAnswer>> {
1670×
        let url = format!("{}/api/v1/flow/runner/update", self.base);
1680×
        match self.agent.get(&url).set("Authorization", &format!("Bearer {}", self.token)).call() {
1690×
            Ok(r) => Ok(Some(r.into_json()?)),
1700×
            Err(ureq::Error::Status(404, _)) => Ok(None),
1710×
            Err(e) => Err(anyhow::anyhow!("{url}: {e}")),
172
        }
1730×
    }
174
175
    /// Tell the hub what this runner did about its update.
1760×
    pub fn report_update(&self, note: &str) -> Result<()> {
1770×
        self.post_with("/flow/runner/update", &flow_core::api::UpdateReport { note: note.to_string() }, &[])?;
1780×
        Ok(())
1790×
    }
180
181
    /// Download an offered build to `to`, refusing it unless its BLAKE3
182
    /// is the one the hub attests and it is the size it said.
1832×
    pub fn download_build(&self, offer: &flow_core::api::UpdateOffer, to: &Path) -> Result<()> {
184
        use std::io::{Read, Write};
1852×
        let url = format!("{}{}", self.base, offer.url);
1862×
        let r = self.agent.get(&url).timeout(Duration::from_secs(1800)).call().map_err(|e| anyhow::anyhow!("{url}: {e}"))?;
1872×
        let part = to.with_extension("partial");
1882×
        let mut out = std::fs::File::create(&part).with_context(|| format!("writing {}", part.display()))?;
1892×
        let (mut hasher, mut n, mut buf) = (blake3::Hasher::new(), 0u64, vec![0u8; 1 << 16]);
1902×
        let mut body = r.into_reader().take(offer.size + 1);
191
        loop {
1924×
            let k = body.read(&mut buf)?;
1934×
            if k == 0 {
1942×
                break;
1952×
            }
1962×
            hasher.update(&buf[..k]);
1972×
            out.write_all(&buf[..k])?;
1982×
            n += k as u64;
199
        }
2002×
        drop(out);
2012×
        let got = hasher.finalize().to_hex().to_string();
2022×
        if n != offer.size || got != offer.blake3 {
2031×
            let _ = std::fs::remove_file(&part);
2041×
            bail!("{} does not match what the hub attests ({n} bytes, BLAKE3 {}…)", offer.asset, &got[..12]);
2051×
        }
2061×
        std::fs::rename(&part, to)?;
2071×
        Ok(())
2082×
    }
209
2108×
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
2118×
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
2125×
        Ok(())
2138×
    }
214
215
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
216
    /// a blob of the job's repository and answers with its ObjectRef.
2170×
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
2180×
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
2190×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2200×
            self.agent
2210×
                .post(&url)
2220×
                .timeout(Duration::from_secs(600))
2230×
                .set("Authorization", &format!("Bearer {}", self.token))
2240×
                .set("Content-Type", "application/octet-stream")
2250×
                .send_bytes(bytes)
2260×
                .map_err(Box::new)
2270×
        })?;
2280×
        let v: serde_json::Value = r.into_json()?;
2290×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2300×
    }
231
232
    /// Keep a checkpoint of job `job` (oxygenflow#77) as its runner hands
233
    /// it back: the hub answers with its blob, which the next attempt's
234
    /// claim names.
2350×
    pub fn save_checkpoint(&self, job: i64, bytes: &[u8]) -> Result<String> {
2360×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2370×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2380×
            self.agent
2390×
                .post(&url)
2400×
                .timeout(Duration::from_secs(600))
2410×
                .set("Authorization", &format!("Bearer {}", self.token))
2420×
                .set("Content-Type", "application/octet-stream")
2430×
                .send_bytes(bytes)
2440×
                .map_err(Box::new)
2450×
        })?;
2460×
        let v: serde_json::Value = r.into_json()?;
2470×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2480×
    }
249
250
    /// The checkpoint an earlier attempt of job `job` saved (oxygenflow#77),
251
    /// which the caller checks against the blob its claim names.
2520×
    pub fn checkpoint(&self, job: i64) -> Result<Vec<u8>> {
2530×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2540×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2550×
            self.agent
2560×
                .get(&url)
2570×
                .timeout(Duration::from_secs(600))
2580×
                .set("Authorization", &format!("Bearer {}", self.token))
2590×
                .call()
2600×
                .map_err(Box::new)
2610×
        })?;
2620×
        let mut bytes = Vec::new();
2630×
        std::io::Read::read_to_end(&mut std::io::Read::take(r.into_reader(), crate::checkpoint::MAX_BYTES as u64 + 1), &mut bytes)?;
2640×
        Ok(bytes)
2650×
    }
266
267
    /// Input `index` of job `job` (oxygenflow#58): the bytes of the
268
    /// producing job's artifact, which the caller checks against the blob the
269
    /// claim names.
2700×
    pub fn input(&self, job: i64, index: usize) -> Result<Vec<u8>> {
2710×
        let url = format!("{}/api/v1/flow/jobs/{job}/inputs/{index}", self.base);
2720×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2730×
            self.agent
2740×
                .get(&url)
2750×
                .timeout(Duration::from_secs(600))
2760×
                .set("Authorization", &format!("Bearer {}", self.token))
2770×
                .call()
2780×
                .map_err(Box::new)
2790×
        })?;
2800×
        let mut bytes = Vec::new();
2810×
        let mut reader = r.into_reader();
2820×
        std::io::Read::read_to_end(&mut std::io::Read::take(&mut reader, MAX_INPUT_BYTES as u64 + 1), &mut bytes)?;
2830×
        if bytes.len() > MAX_INPUT_BYTES {
2840×
            bail!("larger than {} MiB", MAX_INPUT_BYTES >> 20);
2850×
        }
2860×
        Ok(bytes)
2870×
    }
288
289
    /// Upload file `path` of report `name` of job `job` (oxygenhub#127);
290
    /// the hub keeps it as a blob and answers with its ObjectRef. The
291
    /// report's manifest follows through [`Hub::artifact`].
2920×
    pub fn report_file(&self, job: i64, name: &str, path: &str, bytes: &[u8]) -> Result<String> {
2930×
        let url = format!("{}/api/v1/flow/jobs/{job}/reports/{name}/files", self.base);
2940×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2950×
            self.agent
2960×
                .post(&url)
2970×
                .timeout(Duration::from_secs(600))
2980×
                .set("Authorization", &format!("Bearer {}", self.token))
2990×
                .set("Content-Type", "application/octet-stream")
3000×
                .set("X-Flow-Report-Path", path)
3010×
                .send_bytes(bytes)
3020×
                .map_err(Box::new)
3030×
        })?;
3040×
        let v: serde_json::Value = r.into_json()?;
3050×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
3060×
    }
307
308
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
309
    /// cannot be reached or fails (5xx), try again after `first_wait`,
310
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
311
    /// already, say) is final. A result lost here leaves the job running
312
    /// on the hub until its time limit.
3132×
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
3142×
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
3152×
        let deadline = std::time::Instant::now() + patience;
3162×
        let mut wait = first_wait;
317
        loop {
3186×
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
3191×
                Ok(_) => return Ok(()),
3205×
                Err(ureq::Error::Status(code, r)) if code < 500 => {
3211×
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
322
                }
3234×
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
3240×
                Err(e) => e.to_string(),
325
            };
3264×
            if std::time::Instant::now() + wait > deadline {
3270×
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
3284×
            }
3294×
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
3304×
            std::thread::sleep(wait);
3314×
            wait = (wait * 2).min(Duration::from_secs(60));
332
        }
3332×
    }
334
}
335
336
/// How long a runner keeps trying to report a job's end.
337
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
338
339
/// Where a job's result waits until the hub has it, so a runner that
340
/// restarts still reports it.
3410×
fn pending_path(home: &Home, job: i64) -> PathBuf {
3420×
    home.root.join("pending").join(format!("{job}.json"))
3430×
}
344
345
/// Report `f`, keeping it on disk until the hub has it.
3460×
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
3470×
    let path = pending_path(home, job);
3480×
    let kept = std::fs::create_dir_all(path.parent().unwrap())
3490×
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
3500×
        .is_ok();
3510×
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
3520×
        Ok(()) => {}
3530×
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
354
    }
3550×
    if kept {
3560×
        let _ = std::fs::remove_file(&path);
3570×
    }
3580×
}
359
360
/// Results a previous run of the runner could not report, to send again.
3610×
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
3620×
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
3630×
        return Vec::new();
364
    };
3650×
    dir.filter_map(|e| {
3660×
        let p = e.ok()?.path();
3670×
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
3680×
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
3690×
        Some((job, f))
3700×
    })
3710×
    .collect()
3720×
}
373
374
/// `flow runner register`: exchange a one-time registration token from
375
/// the hub for this runner's credential, binding the runner's signing key,
376
/// and keep hub, credential and name in runner.toml.
3771×
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
3781×
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
3790×
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
3801×
    }
3811×
    let key = home.runner_key(name)?;
3821×
    let hub = hub.trim_end_matches('/').to_string();
3831×
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
3841×
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
3851×
    let req = Register {
3861×
        token: token.trim().to_string(),
3871×
        name: name.to_string(),
3881×
        identity: hex::encode(key.identity.encode()),
3891×
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
3901×
    };
3911×
    let url = format!("{hub}/api/v1/flow/runners/register");
3921×
    let got: Registered = match agent.post(&url).send_json(&req) {
3931×
        Ok(r) => r.into_json()?,
3940×
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
3950×
        Err(e) => bail!("{url}: {e}"),
396
    };
3971×
    let mut text = format!(
398
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
399
        got.credential, got.name
400
    );
4011×
    if let Some(ca) = &ca {
4020×
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
4031×
    }
4041×
    if !labels.is_empty() {
4051×
        text.push_str(&format!("labels = {labels:?}\n"));
4061×
    }
4071×
    let path = home.root.join(crate::home::RUNNER_TOML);
408
    {
409
        use std::io::Write;
4101×
        let tmp = path.with_extension("toml.tmp");
4111×
        let mut f = crate::portable::private(std::fs::OpenOptions::new().write(true).create(true).truncate(true)).open(&tmp)?;
4121×
        f.write_all(text.as_bytes())?;
4131×
        f.sync_all()?;
4141×
        std::fs::rename(&tmp, &path)?;
415
    }
4161×
    Ok(got)
4171×
}
418
419
/// Waits before trying a hub request again after a server error.
420
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
421
422
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
423
/// all, longer than a hub takes to restart.
424
/// Check an input's bytes against the blob the producing job's receipt
425
/// names, then write them at its path under `tree` (the workspace's `/src`).
4266×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
4276×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
428
    else {
4294×
        bail!("path {:?} is not a clean path under /src", i.path);
430
    };
4312×
    let blob = Repo::blob_ref(bytes);
4322×
    if blob.to_hex() != i.blob {
4331×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
4341×
    }
4351×
    let dest = tree.join(rel);
4361×
    if let Some(dir) = dest.parent() {
4371×
        std::fs::create_dir_all(dir)?;
4380×
    }
4391×
    std::fs::write(&dest, bytes)?;
4401×
    Ok(blob.0)
4416×
}
442
443
/// The largest input a job takes: the hub's artifact limit.
444
pub const MAX_INPUT_BYTES: usize = 512 << 20;
445
446
const PATIENT_DELAYS: [Duration; 15] = {
447
    let mut d = [Duration::from_secs(15); 15];
448
    d[0] = Duration::from_secs(1);
449
    d[1] = Duration::from_secs(2);
450
    d[2] = Duration::from_secs(4);
451
    d[3] = Duration::from_secs(8);
452
    d
453
};
454
455
/// Send a request until the hub answers, waiting `delays` in turn after a
456
/// server error (5xx: nothing was committed) and, when `connection`, after
457
/// the hub could not be reached at all. A refusal (4xx) is final, as a
458
/// [`Refused`] the caller can look at.
45914×
fn retrying(
46014×
    url: &str,
46114×
    delays: &[Duration],
46214×
    connection: bool,
46314×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
46414×
) -> Result<ureq::Response> {
46514×
    let mut delays = delays.iter();
466
    loop {
46723×
        let why = match send().map_err(|e| *e) {
4688×
            Ok(r) => return Ok(r),
4699×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4702×
                let text = r.into_string().unwrap_or_default();
4712×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
472
            }
4737×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4743×
            Err(e) if connection => e.to_string(),
4753×
            Err(e) => bail!("{url}: {e}"),
476
        };
47710×
        match delays.next() {
4789×
            Some(d) => std::thread::sleep(*d),
4791×
            None => bail!("{url}: {why}"),
480
        }
481
    }
48214×
}
483
484
/// What the runner may run at once (flow.toml `[runner]`): at most
485
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
486
#[derive(Debug, Default, PartialEq, Eq)]
487
pub struct Budget {
488
    pub max_jobs: usize,
489
    pub memory_mib: Option<u32>,
490
    pub cpus: Option<u32>,
491
}
492
493
/// What is in use now.
494
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
495
pub struct Used {
496
    pub jobs: usize,
497
    pub memory_mib: u32,
498
    pub cpus: u32,
499
}
500
501
impl Budget {
5020×
    pub fn of(cfg: &RunnerConfig) -> Budget {
5030×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
5040×
    }
505
506
    /// The room to ask the hub for, or `None` when no job more can start.
507
    /// A lone job may use the whole budget even if it asks for more, so a
508
    /// large sandbox is never starved.
5097×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
5107×
        if used.jobs >= self.max_jobs {
5112×
            return None;
5125×
        }
5135×
        if used.jobs == 0 {
5142×
            return Some((None, None));
5153×
        }
5163×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
5173×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
5183×
        if mem == Some(0) || cpus == Some(0) {
5191×
            return None;
5202×
        }
5212×
        Some((mem, cpus))
5227×
    }
523
}
524
525
/// The isolation tiers this machine can honour now (spec §11.1): the
526
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
527
/// flow.toml pins Firecracker; the syscall tier when this binary may use
528
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
529
/// `Err` says why there are none; the reasons for missing tiers come back
530
/// with the ones there are.
5313×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
5323×
    let mut have = Vec::new();
5333×
    let mut missing = Vec::new();
5343×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
5353×
    match (kvm, home.config.microvm.is_some()) {
5363×
        _ if !cfg!(target_os = "linux") => missing.push("microvm: the tier runs only on Linux (Firecracker and KVM)".to_string()),
5370×
        (Ok(_), true) => have.push("microvm".to_string()),
5380×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
5393×
        (Err(e), _) => missing.push(format!(
540
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
541
        )),
542
    }
5433×
    match crate::syscall::available() {
5440×
        Ok(()) => have.push("syscall".to_string()),
5453×
        Err(e) => missing.push(format!("syscall: {e}")),
546
    }
547
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5483×
    have.push("wasm".to_string());
5493×
    if have.is_empty() {
5500×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5513×
    }
5523×
    Ok((have, missing))
5533×
}
554
555
/// Fetch `claim`'s image from the hub when this home lacks it
556
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
557
/// leaves it missing, and the preflight declines the job as before.
5580×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) {
5590×
    let hash = &claim.sandbox.rootfs;
5600×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5610×
        return;
5620×
    }
5630×
    let note = |text: String| {
5640×
        eprintln!("job {}: {text}", claim.job_id);
5650×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5660×
    };
567
    // One fetch of an image at a time: two jobs wanting it wait for one.
568
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5690×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5700×
    if home.rootfs(hash).is_file() {
5710×
        return;
5720×
    }
5730×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5740×
        Ok(c) => c,
5750×
        Err(e) => return note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12])),
576
    };
5770×
    let fetched = match swarm {
5780×
        Some(sw) => {
5790×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5800×
            sw.fetch(home, hash)
581
        }
582
        None => {
5830×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
5840×
            client.fetch(home, hash)
585
        }
586
    };
5870×
    match fetched {
5880×
        Ok(Some(m)) => note(format!(
589
            "image {}: fetched {} chunks, {}{} in {:.1} s",
5900×
            &hash[..12],
591
            m.chunks,
5920×
            crate::images::human(m.bytes),
5930×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
5940×
            m.elapsed.as_secs_f64()
595
        )),
5960×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
5970×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
598
    }
5990×
}
600
601
/// Why this runner cannot run `claim` now (spec §11.5), checked before
602
/// anything is fetched: the tier, the architecture, the image and the
603
/// memory. The hub chose it from what the runner last said, which may be
604
/// out of date.
6050×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6060×
    let sb = &claim.sandbox;
6070×
    match sb.runtime {
608
        flow_core::Runtime::Microvm => {
6090×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6100×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6110×
            }
6120×
            if home.config.microvm.is_none() {
6130×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6140×
            }
615
        }
616
        flow_core::Runtime::Syscall => {
6170×
            if let Err(e) = crate::syscall::available() {
6180×
                return Some(format!("the syscall tier cannot run here: {e}"));
6190×
            }
620
        }
621
        // No image and no architecture: only the memory matters.
622
        flow_core::Runtime::Wasm => {
6230×
            return available_memory_mib()
6240×
                .filter(|free| *free < u64::from(sb.memory_mib))
6250×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
626
        }
627
    }
6280×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6290×
}
630
631
/// What stops `sb` running on this home's images, on a machine of
632
/// architecture `here` with `free_mib` of memory free.
6338×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6348×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6351×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6367×
    }
6377×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6387×
    let image = home.rootfs(&sb.rootfs);
6397×
    if !image.is_file() {
6401×
        return Some(format!("rootfs {short} is not on this runner"));
6416×
    }
6426×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6432×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6444×
    }
6454×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6461×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6473×
    }
6483×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6491×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6502×
    }
6512×
    None
6528×
}
653
654
/// The memory to claim with: the budget's room, never more than the host
655
/// has free now. An idle runner's budget is unlimited (a lone job may use
656
/// it all), so without this it was offered sandboxes it then declined for
657
/// want of memory, one after another, having fetched their images first
658
/// (an 8 GiB job on a 7 GB machine).
6595×
fn claim_memory(room: Option<u32>, host_free_mib: Option<u64>) -> Option<u32> {
6605×
    match (room, host_free_mib) {
6612×
        (Some(r), Some(h)) => Some(r.min(u32::try_from(h).unwrap_or(u32::MAX))),
6621×
        (None, Some(h)) => Some(u32::try_from(h).unwrap_or(u32::MAX)),
6632×
        (room, None) => room,
664
    }
6655×
}
666
667
/// `MemAvailable` from /proc/meminfo, in MiB.
6680×
fn available_memory_mib() -> Option<u64> {
6690×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6700×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6710×
    Some(kib / 1024)
6720×
}
673
6740×
pub fn serve(home: &Home) -> Result<()> {
6750×
    drain_on_stop();
6760×
    crate::update::note_runner(&home.root);
677
    // `flow runner update` swapped a new build in and asks this one to
678
    // leave with the notice it gave (#85).
679
    #[cfg(unix)]
6800×
    {
6810×
        let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
6820×
        unsafe { libc::signal(libc::SIGUSR1, handler) };
6830×
    }
6840×
    if let Some(p) = crate::update::pending(&home.root) {
685
        // On trial: a build that does not reach the hub in time goes back.
6860×
        let root = home.root.clone();
6870×
        std::thread::spawn(move || {
6880×
            std::thread::sleep(crate::update::PROVE_WITHIN);
6890×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
6900×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
6910×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
6920×
                    std::process::exit(1);
6930×
                }
6940×
            }
6950×
        });
6960×
    }
6970×
    let served = serve_until_drained(home);
6980×
    crate::update::forget_runner(&home.root);
699
    // Left for a new build: on Windows, end as a failure, so a Task
700
    // Scheduler task set to restart on failure starts it (systemd's
701
    // Restart=always starts it after a clean exit).
7020×
    if cfg!(windows) && served.is_ok() && LEFT_FOR_UPDATE.load(std::sync::atomic::Ordering::SeqCst) {
7030×
        eprintln!("flow runner: left for the new build; exiting 75 so it is started");
7040×
        std::process::exit(75);
7050×
    }
7060×
    served
7070×
}
708
709
/// Set once the runner leaves for a new build.
710
static LEFT_FOR_UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
711
712
/// Set by SIGUSR1: a new build is in place; leave for it.
713
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
714
715
#[cfg(unix)]
7160×
extern "C" fn on_update(_: libc::c_int) {
7170×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
7180×
}
719
720
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
721
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
722
/// it holds are done and reported. It may be started again afterwards.
7230×
pub fn serve_embedded(home: &Home) -> Result<()> {
7240×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
7250×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
7260×
    serve_until_drained(home)
7270×
}
728
729
/// A departure ([`leave_within`]): why, and when the runner must be gone.
730
#[derive(Clone, Debug)]
731
struct Leave {
732
    reason: String,
733
    by: Instant,
734
}
735
736
/// Set once the runner is leaving: a job whose expected rest fits before
737
/// the deadline finishes; the others are stopped and handed back
738
/// (oxygenflow#76).
739
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
740
7410×
fn leaving() -> Option<String> {
7420×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7430×
}
744
745
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
746
/// more, stop the jobs it holds and hand them back to the hub, which queues
747
/// them ahead of new work for another runner (oxygenflow#76), then return.
748
/// For a departure with no time to finish: a phone off the allowed network.
7490×
pub fn leave(reason: &str) {
7500×
    leave_within(reason, Duration::ZERO);
7510×
}
752
753
/// [`leave`], with `notice`: a job the hub expects to finish within it
754
/// (the claim's `expected_ms`, less the time it has run) finishes and is
755
/// reported; the others, and any still running when the notice is up, are
756
/// handed back. For a phone taken off charge, a spot reclaim.
7570×
pub fn leave_within(reason: &str, notice: Duration) {
7580×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7590×
    stop();
7600×
}
761
762
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
763
/// more, finish and report what it holds, then return (oxygenflow#76's
764
/// drain, for a phone taken off charge or off the allowed network).
7651×
pub fn stop() {
7661×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7671×
}
768
7690×
fn serve_until_drained(home: &Home) -> Result<()> {
7700×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
771
    // A runner offers only what it can run: a machine without KVM claims
772
    // nothing rather than taking MicroVM jobs and failing them (#36).
7730×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7740×
    for why in &missing {
7750×
        eprintln!("flow runner: not offering {why}");
7760×
    }
7770×
    let hub = Hub::new(&cfg)?;
7780×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
7790×
    let budget = Budget::of(&cfg);
7800×
    let key = home.runner_key(&name)?;
781
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
782
    // peers still runs jobs, fetching images from the hub alone.
7830×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
7840×
        eprintln!("flow runner: not joining the swarm: {e:#}");
7850×
        None
7860×
    });
7870×
    eprintln!(
788
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
789
        cfg.hub,
790
        budget.max_jobs,
7910×
        runtimes.join(", "),
7920×
        key.identity.hash().to_hex()
793
    );
7940×
    if let Some(addr) = &cfg.metrics {
7950×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
7960×
    }
797
    // The manifests of images held here that the hub keeps none of, so
798
    // peers in this runner's site can fetch them without anyone pushing
799
    // them (oxygenflow#94): at start and every ten minutes, which also
800
    // catches an image imported while it runs. Only a runner that serves
801
    // its peers has anything to offer.
8020×
    if swarm.is_some() {
8030×
        let (root, cfg) = (home.root.clone(), cfg.clone());
8040×
        std::thread::spawn(move || loop {
8050×
            let offered = Home::locate(Some(&root))
8060×
                .and_then(|home| crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref())?.offer_held(&home));
8070×
            match offered {
8080×
                Ok(0) => {}
8090×
                Ok(n) => eprintln!("flow runner: sent the hub the manifests of {n} image(s) only runners hold"),
8100×
                Err(e) => eprintln!("flow runner: offering held images: {e:#}"),
811
            }
8120×
            std::thread::sleep(Duration::from_secs(600));
813
        });
8140×
    }
8150×
    let used = std::sync::Mutex::new(Used::default());
8160×
    let mut idle = Duration::from_secs(2);
8170×
    let pending = report_pending(home);
818
    // The jobs held now, told to the hub at each claim so it can end the
819
    // ones this runner lost: a job is held from its claim until its result
820
    // is reported.
8210×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
8220×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
8230×
    std::thread::scope(|scope| {
8240×
        for (job, f) in pending {
8250×
            let (hub, held) = (&hub, &held);
8260×
            scope.spawn(move || {
8270×
                eprintln!("job {job}: reporting the result kept from before the restart");
8280×
                report_finish(home, hub, job, &f);
8290×
                held.lock().unwrap().remove(&job);
8300×
            });
831
        }
832
        // The speed (spec §11.1): measured now, and again every 15 minutes
833
        // while no job runs, so a job never shares the CPU with it.
8340×
        let measure = || {
8350×
            let (speed, ms) = crate::facts::bench();
8360×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
8370×
            speed
8380×
        };
8390×
        let mut speed = measure();
8400×
        let mut benched = Instant::now();
8410×
        let mut said_draining = false;
842
        // When the hub last heard from us (oxygenhub#243): a claim, or a
843
        // heartbeat while there is no room to claim.
8440×
        let mut heard = Instant::now();
8450×
        let beat = |heard: &mut Instant| {
8460×
            if heard.elapsed() >= HUB_HEARTBEAT {
8470×
                if let Err(e) = hub.heartbeat() {
8480×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8490×
                }
8500×
                *heard = Instant::now();
8510×
            }
8520×
        };
8530×
        let mut on_trial = crate::update::pending(&home.root).is_some();
854
        // Runner updates (oxygenhub#322): asked of the hub once it has
855
        // answered a claim, then every 15 minutes.
8560×
        let mut update_asked: Option<Instant> = None;
8570×
        let mut update_said = String::new();
858
        loop {
8590×
            if !stopping() && crate::update::drain_requested(&home.root) {
8600×
                eprintln!("flow runner {name}: asked to drain (flow runner drain)");
8610×
                stop();
8620×
            }
8630×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) || crate::update::requested(&home.root) {
8640×
                let p = crate::update::pending(&home.root);
8650×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8660×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8670×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8680×
                LEFT_FOR_UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
8690×
                leave_within(&format!("updating to {to}"), notice);
8700×
            }
871
            // Draining (oxygenflow#50): told to stop, claim nothing more and
872
            // stop once every job held is done and reported.
8730×
            if stopping() {
8740×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8750×
                if jobs == 0 && holding == 0 {
8760×
                    eprintln!("flow runner {name}: drained, stopping");
8770×
                    break;
8780×
                }
8790×
                if !said_draining {
8800×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
8810×
                    said_draining = true;
8820×
                }
8830×
                beat(&mut heard);
8840×
                std::thread::sleep(Duration::from_millis(500));
8850×
                continue;
8860×
            }
8870×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
8880×
                speed = measure();
8890×
                benched = Instant::now();
8900×
            }
8910×
            let room = budget.room(*used.lock().unwrap());
8920×
            let Some((free_memory_mib, free_cpus)) = room else {
8930×
                beat(&mut heard);
8940×
                std::thread::sleep(Duration::from_millis(500));
8950×
                continue;
896
            };
8970×
            heard = Instant::now();
8980×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
8990×
            let req = ClaimRequest {
9000×
                runner: name.clone(),
9010×
                runtimes: runtimes.clone(),
9020×
                free_memory_mib: claim_memory(free_memory_mib, available_memory_mib()),
9030×
                free_cpus,
9040×
                info: Some(RunnerInfo {
9050×
                    version: env!("OXY_VERSION_LONG").into(),
9060×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
9070×
                }),
908
                // Read each time: an image imported while the runner runs counts.
9090×
                images: Some(home.images()),
9100×
                image_archs: Some(home.image_archs()),
9110×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
912
                fetches_images: true,
9130×
                facts: Some(crate::facts::now(home, Some(speed))),
9140×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
9150×
                caches: Some(cache_times.keys().cloned().collect()),
9160×
                cache_times: Some(cache_times),
917
            };
9180×
            let answer = hub.claim(&req);
9190×
            if on_trial && answer.is_ok() {
9200×
                crate::update::proven(&home.root);
9210×
                on_trial = false;
9220×
            }
9230×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
9240×
                update_asked = Some(Instant::now());
9250×
                if let Some(note) = crate::update::take_note(&home.root) {
9260×
                    let _ = hub.report_update(&note);
9270×
                }
9280×
                consider_update(home, &hub, &mut update_said);
9290×
            }
9300×
            match answer {
9310×
                Ok(Some(claim)) => {
9320×
                    idle = Duration::from_secs(2);
9330×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9340×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
9350×
                    {
9360×
                        let mut u = used.lock().unwrap();
9370×
                        u.jobs += 1;
9380×
                        u.memory_mib += mem;
9390×
                        u.cpus += cpus;
9400×
                    }
9410×
                    held.lock().unwrap().insert(claim.job_id);
9420×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
9430×
                    scope.spawn(move || {
9440×
                        let id = claim.job_id;
9450×
                        fetch_image(home, hub, cfg, swarm, &claim);
9460×
                        if let Some(why) = preflight(home, &claim) {
9470×
                            eprintln!("job {id}: declined: {why}");
9480×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9490×
                            if let Err(e) = hub.decline(id, &why) {
9500×
                                eprintln!("job {id}: decline: {e:#}");
9510×
                            }
9520×
                            held.lock().unwrap().remove(&id);
9530×
                            let mut u = used.lock().unwrap();
9540×
                            u.jobs -= 1;
9550×
                            u.memory_mib -= mem;
9560×
                            u.cpus -= cpus;
9570×
                            return;
9580×
                        }
9590×
                        eprintln!(
960
                            "job {id}: {} {} on {}",
961
                            claim.repo,
962
                            claim.job.name,
9630×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
964
                        );
9650×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9660×
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
9670×
                            exit_code: None,
968
                            duration_ms: 0,
9690×
                            receipt: None,
9700×
                            signed_receipt: None,
9710×
                            error: Some(format!("{e:#}")),
9720×
                            peak_disk_mib: None,
9730×
                            peak_memory_mib: None,
9740×
                        });
9750×
                        eprintln!(
976
                            "job {id}: exit {:?}{}",
977
                            finish.exit_code,
9780×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
979
                        );
9800×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
9810×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
9820×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
9830×
                        match leaving() {
984
                            // Stopped as the runner leaves: another runner takes it.
9850×
                            Some(why) if cancelled => {
9860×
                                eprintln!("job {id}: handed back: {why}");
9870×
                                if let Err(e) = hub.release(id, &why) {
9880×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
9890×
                                }
990
                            }
9910×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
9920×
                            _ => {}
993
                        }
9940×
                        held.lock().unwrap().remove(&id);
9950×
                        let mut u = used.lock().unwrap();
9960×
                        u.jobs -= 1;
9970×
                        u.memory_mib -= mem;
9980×
                        u.cpus -= cpus;
9990×
                    });
1000
                }
10010×
                Ok(None) => std::thread::sleep(idle),
10020×
                Err(e) => {
10030×
                    eprintln!("claim: {e:#}");
10040×
                    std::thread::sleep(idle);
10050×
                    idle = (idle * 2).min(Duration::from_secs(60));
10060×
                }
1007
            }
1008
        }
10090×
        Ok(())
10100×
    })
10110×
}
1012
1013
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
1014
/// happened goes to its log, and a failure only means the next attempt
1015
/// starts again.
1016
#[allow(clippy::too_many_arguments)]
10170×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
10180×
    if !dir_tier {
10190×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
10200×
        return;
10210×
    }
10220×
    let dirs: Vec<(String, PathBuf)> = job
10230×
        .checkpoints
10240×
        .iter()
10250×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
10260×
        .collect();
10270×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
10280×
        Ok((blob, n)) => {
10290×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
1030
        }
10310×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
1032
    }
10330×
}
1034
1035
/// How many times the runner was told to stop (SIGTERM or SIGINT).
1036
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1037
10381×
extern "C" fn on_stop(_: libc::c_int) {
1039
    // A second stop means now: only async-signal-safe calls here.
10401×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
10410×
        unsafe { libc::_exit(143) };
10421×
    }
10431×
}
1044
1045
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
1046
/// so restarting a runner never kills the job it runs: the unit's
1047
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
10480×
fn drain_on_stop() {
10490×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10500×
    unsafe {
10510×
        libc::signal(libc::SIGTERM, handler);
10520×
        libc::signal(libc::SIGINT, handler);
10530×
    }
10540×
}
1055
10563×
fn stopping() -> bool {
10573×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10583×
}
1059
1060
/// Batches records to the hub every second (or every 200 lines). A quiet
1061
/// job's sink still asks the hub every few seconds whether the job runs,
1062
/// with an empty batch; once the hub answers 409 the job is not wanted.
1063
struct LogSink<'a> {
1064
    hub: &'a Hub,
1065
    job: i64,
1066
    buf: Vec<Record>,
1067
    last: Instant,
1068
    gone: bool,
1069
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1070
    /// handed back, unless its expected rest fits the notice.
1071
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1072
    /// When the job started, and how long the hub expects it to take.
1073
    started: Instant,
1074
    expected: Option<Duration>,
1075
}
1076
1077
/// The most log lines sent at once, as a busy job's sink flushes them.
1078
const BATCH: usize = 200;
1079
1080
/// The most log lines kept while the hub cannot be reached.
1081
const MAX_UNSENT: usize = 50_000;
1082
1083
/// How often a quiet job asks whether it was cancelled.
1084
const HEARTBEAT: Duration = Duration::from_secs(5);
1085
1086
impl microvm::Sink for LogSink<'_> {
10871×
    fn record(&mut self, r: Record) {
10881×
        self.push(r)
10891×
    }
1090
109110×
    fn cancelled(&mut self) -> bool {
109210×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
109310×
        if let Some(l) = leave {
1094
            // Finished if what is left of it fits the notice; else handed
1095
            // back as the runner leaves, what the job said so far first.
10965×
            let now = Instant::now();
10975×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
10985×
            if !fits || now >= l.by {
10994×
                self.flush();
11004×
                return true;
11011×
            }
11025×
        }
11036×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
11042×
            self.send();
11054×
        }
11066×
        self.gone
110710×
    }
1108
}
1109
1110
impl LogSink<'_> {
11111×
    fn push(&mut self, mut r: Record) {
11121×
        if self.gone {
11131×
            return;
11140×
        }
11150×
        if r.text.len() > MAX_RECORD_TEXT {
11160×
            let mut cut = MAX_RECORD_TEXT;
11170×
            while !r.text.is_char_boundary(cut) {
11180×
                cut -= 1;
11190×
            }
11200×
            r.text.truncate(cut);
11210×
        }
11220×
        self.buf.push(r);
11230×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
11240×
            self.flush();
11250×
        }
11261×
    }
1127
11285×
    fn flush(&mut self) {
11295×
        if !self.buf.is_empty() {
11301×
            self.send();
11314×
        }
11325×
        self.last = Instant::now();
11335×
    }
1134
1135
    /// Send what is buffered, even nothing, in batches of at most
1136
    /// `BATCH` lines.
11376×
    fn send(&mut self) {
1138
        loop {
11398×
            if self.gone {
11400×
                return;
11418×
            }
11428×
            let n = self.buf.len().min(BATCH);
11438×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
11448×
            match self.hub.log(self.job, batch.clone()) {
11455×
                Ok(()) => {}
11463×
                Err(e) if job_gone(&e) => self.gone = true,
11472×
                Err(e) => {
1148
                    // The hub is away (a restart, say): keep the lines for
1149
                    // the next batch, up to a bound, so the log loses none
1150
                    // (oxygenflow#49).
11512×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11522×
                    let mut kept = batch;
11532×
                    kept.append(&mut self.buf);
11542×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11552×
                    if over > 0 {
11561×
                        kept.drain(..over);
11571×
                        kept.insert(
11581×
                            0,
11591×
                            Record {
11601×
                                t: 0,
11611×
                                stream: "flow".into(),
11621×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11631×
                            },
11641×
                        );
11651×
                    }
11662×
                    self.buf = kept;
11672×
                    break;
1168
                }
1169
            }
11706×
            if self.buf.is_empty() {
11714×
                break;
11722×
            }
1173
        }
11746×
        self.last = Instant::now();
11756×
    }
1176
}
1177
1178
/// How often a runner with no room to claim tells the hub it is there:
1179
/// well inside the hub's 90 s before it shows a runner offline.
1180
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1181
1182
/// How often a runner asks the hub whether it should run another build.
1183
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1184
1185
/// Notice a runner gives itself to leave for an update the hub offered.
1186
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1187
1188
/// Ask the hub for this runner's update, and act on it: download the build
1189
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1190
/// install it, or for a dry run say what would happen. What it did goes to
1191
/// the hub once per outcome (`said`).
11920×
fn consider_update(home: &Home, hub: &Hub, said: &mut String) {
11930×
    let answer = match hub.update_answer() {
11940×
        Ok(Some(a)) => a,
11950×
        Ok(None) => return,
11960×
        Err(e) => {
11970×
            eprintln!("flow runner: asking for an update: {e:#}");
11980×
            return;
1199
        }
1200
    };
12010×
    let Some(offer) = answer.offer else { return };
12020×
    let mut say = |note: String| {
12030×
        if *said != note {
12040×
            eprintln!("flow runner: {note}");
12050×
            if let Err(e) = hub.report_update(&note) {
12060×
                eprintln!("flow runner: telling the hub: {e:#}");
12070×
            }
12080×
            *said = note;
12090×
        }
12100×
    };
12110×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
12120×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
12130×
    }
12140×
    let dir = home.root.join("updates");
12150×
    let file = dir.join(format!("flow-{}", offer.version));
12160×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
12170×
    if !fresh {
12180×
        if let Err(e) = std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| hub.download_build(&offer, &file)) {
12190×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
12200×
        }
12210×
    }
12220×
    let exe = match std::env::current_exe() {
12230×
        Ok(e) => e,
12240×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1225
    };
12260×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
12270×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
12280×
        Ok(done) => {
12290×
            let _ = std::fs::remove_file(&file);
12300×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1231
        }
12320×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1233
    }
12340×
}
1235
1236
/// Held while a job takes its cache disks and images its workspace (see
1237
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1238
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1239
1240
/// Held while the first clone of any repository passes its token through
1241
/// the process environment.
1242
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1243
1244
/// One lock per cached repository: fetches into it, and exports from it,
1245
/// never overlap, while jobs of other repositories go on. A slow repository
1246
/// (one kept in a bucket, say) once held every job on the runner waiting
1247
/// behind a single global lock.
12480×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1249
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1250
        std::sync::OnceLock::new();
12510×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
12520×
    locks.entry(name.to_string()).or_default().clone()
12530×
}
1254
1255
/// Seconds, to one decimal place, for the job's log.
12560×
fn secs(d: std::time::Duration) -> String {
12570×
    format!("{:.1} s", d.as_secs_f64())
12580×
}
1259
12600×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
12610×
    let started = Instant::now();
12620×
    let mut sink = LogSink {
12630×
        hub,
12640×
        job: claim.job_id,
12650×
        buf: Vec::new(),
12660×
        last: Instant::now(),
12670×
        gone: false,
12680×
        leaving: &LEAVING,
12690×
        started: Instant::now(),
12700×
        expected: claim.expected_ms.map(Duration::from_millis),
12710×
    };
12720×
    let note =
12730×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
12740×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
12750×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1276
    // Preparing a workspace: fetches into a cached repository, and exports
1277
    // from it, are one job at a time per repository (`repo_lock`); taking
1278
    // cache disks and imaging the workspace are one job at a time on the
1279
    // runner (`PREPARE`); a first clone, whose token goes through the process
1280
    // environment, one at a time (`CLONE`).
12810×
    let main_lock = repo_lock(&claim.repo);
12820×
    let asked = Instant::now();
12830×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
12840×
    if asked.elapsed().as_secs() >= 2 {
12850×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
12860×
    }
12870×
    let fetching = Instant::now();
12880×
    let repo = cached_repo(home, cfg, claim)?;
12890×
    let fetched = fetching.elapsed();
12900×
    let mut preparing = None;
12910×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
12920×
    let _ = std::fs::remove_dir_all(&scratch);
12930×
    std::fs::create_dir_all(scratch.join("tree"))?;
12940×
    let result = (|| -> Result<Finish> {
12950×
        let exporting = Instant::now();
12960×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
12970×
        main_guard.take();
12980×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1299
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1300
        // workspace and of the scope hash.
13010×
        for sub in &claim.subrepos {
13020×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
13030×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
13040×
            }
13050×
            note(
13060×
                &mut sink,
13070×
                format!(
1308
                    "fetching subrepo {} at {} for {}",
1309
                    sub.repo,
13100×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1311
                    sub.path
1312
                ),
1313
            );
13140×
            let sub_lock = repo_lock(&sub.repo);
13150×
            let asked = Instant::now();
13160×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
13170×
            if asked.elapsed().as_secs() >= 2 {
13180×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
13190×
            }
13200×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
13210×
            let sub_heads: Vec<ChangeHash> =
13220×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
13230×
            let dir = scratch.join("tree").join(&sub.path);
13240×
            std::fs::create_dir_all(&dir)?;
13250×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
13260×
            drop(sub_guard);
13270×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1328
        }
13290×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1330
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1331
        // against the blob its receipt names, then put at its path. Not part
1332
        // of the scope: they are the run's, not the repository's.
13330×
        let mut input_blobs = Vec::new();
13340×
        for (index, i) in claim.inputs.iter().enumerate() {
13350×
            let what = format!("input {} from {}", i.artifact, i.from);
13360×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
13370×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
13380×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
13390×
            input_blobs.push(blob);
1340
        }
1341
        // The syscall tier runs on the tree itself; a microVM gets an image.
13420×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
13430×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1344
        // The syscall and WASM tiers see the job's files as a directory;
1345
        // the MicroVM tier as an ext4 image.
13460×
        let dir_tier = syscall_tier || wasm_tier;
13470×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1348
        // Disk mounts that name a cache start from a kept disk (#28): a
1349
        // microVM takes an image already in place as it is, the syscall tier
1350
        // a directory (#70). Taken before the workspace is imaged: the
1351
        // sources the disk was built from give unchanged files their old
1352
        // times back (#52).
13530×
        let asked = Instant::now();
13540×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
13550×
        if asked.elapsed().as_secs() >= 2 {
13560×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
13570×
        }
13580×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
13590×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
13600×
        let cache_ctx =
13610×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
13620×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
13630×
        let mut built_from: Option<crate::cache::Sources> = None;
13640×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
13650×
            let Some(name) = &m.cache else { continue };
13660×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
13670×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
13680×
                Some(t) => {
13690×
                    if built_from.is_none() {
13700×
                        built_from = t.sources;
13710×
                    }
13720×
                    t.how
1373
                }
13740×
                None => format!("cache {name}: none kept yet, an empty disk"),
1375
            };
13760×
            note(&mut sink, format!("{} ({})", how, m.target));
1377
            // What the job reads is seen when the disk is pruned (#72).
13780×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
13790×
                note(&mut sink, format!("cache {name}: {e:#}"));
13800×
            }
13810×
            cached.push((i, key, how));
1382
        }
1383
        // What the job reads or writes on its cache from now on is what it
1384
        // used; the rest may be pruned before the cache is kept (#72).
13850×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
13860×
        let sources = if cached.is_empty() {
13870×
            crate::cache::Sources::new()
1388
        } else {
13890×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
13900×
            if built_from.is_some() {
13910×
                note(
13920×
                    &mut sink,
13930×
                    format!(
13940×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
13950×
                        sources.len()
13960×
                    ),
13970×
                );
13980×
            }
13990×
            sources
1400
        };
1401
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1402
        // over the cache, before the same exec runs again; the receipt
1403
        // lists it among the job's inputs.
14040×
        if let Some(blob) = &claim.checkpoint {
14050×
            if dir_tier {
14060×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
14070×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
14080×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
14090×
                }
14100×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
14110×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
14120×
                note(
14130×
                    &mut sink,
14140×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
14150×
                );
14160×
                input_blobs.push(Repo::blob_ref(&bytes).0);
14170×
            } else {
14180×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
14190×
            }
14200×
        }
14210×
        if !dir_tier {
14220×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
14230×
            std::fs::remove_dir_all(scratch.join("tree"))?;
14240×
        }
14250×
        preparing.take();
1426
        // Cancelled while it was being prepared: no sandbox.
14270×
        if microvm::Sink::cancelled(&mut sink) {
14280×
            return Ok(cancelled());
14290×
        }
14300×
        if wasm_tier {
14310×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
14320×
        } else {
14330×
            note(
14340×
                &mut sink,
14350×
                format!(
1436
                    "{}: {} {}, {} MiB, rootfs {}",
14370×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1438
                    claim.sandbox.cpus,
14390×
                    if syscall_tier { "CPU" } else { "vCPU" },
1440
                    claim.sandbox.memory_mib,
14410×
                    &claim.sandbox.rootfs[..12]
1442
                ),
1443
            );
1444
        }
14450×
        let timeout = Duration::from_secs(claim.timeout_s);
14460×
        let mut outcome = if wasm_tier {
14470×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
14480×
        } else if syscall_tier {
14490×
            let group = format!("job-{}", claim.job_id);
14500×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1451
        } else {
14520×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1453
        };
14540×
        if outcome.cancelled {
1455
            // Handed back as the runner leaves: its checkpoints first, for
1456
            // the next attempt (oxygenflow#77).
14570×
            if leaving().is_some() && !job.checkpoints.is_empty() {
14580×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
14590×
            }
14600×
            return Ok(cancelled());
14610×
        }
1462
        // The receipt says what a cached disk started from.
14630×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
14640×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
14650×
        for (i, key, how) in &cached {
14660×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
14670×
        }
1468
        // A passing job's artifacts, read from its disks and uploaded; a
1469
        // declared artifact that cannot be kept fails the job. A failing
1470
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1471
        // its receipt, and one it cannot keep is only noted.
14720×
        let mut outputs = vec![];
14730×
        let mut output_error = None;
14740×
        let passed = outcome.exit_code == Some(0);
14750×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
14760×
        for o in wanted {
14770×
            if o.kind == flow_core::OutputKind::Report {
14780×
                let read = if dir_tier {
14790×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14800×
                    crate::outputs::read_report_dir(&dir, &inner)
1481
                } else {
14820×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14830×
                    crate::outputs::read_report(&image, &inner, &scratch)
1484
                };
14850×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
14860×
                match kept {
14870×
                    Ok((blob, files, bytes)) => {
14880×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
14890×
                        let hex = blob.to_hex();
14900×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
14910×
                        if passed {
14920×
                            outputs.push(blob.0);
14930×
                        }
1494
                    }
14950×
                    Err(e) if passed => {
14960×
                        output_error = Some(format!("report {}: {e:#}", o.name));
14970×
                        break;
1498
                    }
14990×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1500
                }
15010×
                continue;
15020×
            }
15030×
            let read = if dir_tier {
15040×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
15050×
                crate::outputs::read_dir_file(&dir, &inner)
1506
            } else {
15070×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
15080×
                crate::outputs::read(&image, &inner, &scratch)
1509
            };
15100×
            let kept = read.and_then(|bytes| {
15110×
                let blob = Repo::blob_ref(&bytes);
15120×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
15130×
                if named != blob.to_hex() {
15140×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
15150×
                }
15160×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
15170×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
15180×
                Ok(blob.0)
15190×
            });
15200×
            match kept {
15210×
                Ok(b) if passed => outputs.push(b),
15220×
                Ok(_) => {}
15230×
                Err(e) if passed => {
15240×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
15250×
                    break;
1526
                }
15270×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1528
            }
1529
        }
15300×
        if let Some(e) = &output_error {
15310×
            note(&mut sink, e.clone());
15320×
        }
15330×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
15340×
            job_name: claim.job.name.clone(),
15350×
            pipeline_hash: hex32(&claim.pipeline_hash),
15360×
            scope_tree_hash: scope_hash,
15370×
            inputs: input_blobs.clone(),
15380×
            environment: outcome.environment.hash(),
15390×
            outputs,
15400×
            exit_code: code as u32,
15410×
            duration_ms: outcome.duration_ms,
15420×
        });
15430×
        let signed_receipt = match &receipt {
15440×
            Some(r) => {
15450×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
15460×
                if cfg.keyless {
15470×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
15480×
                        Ok(k) => signed = k,
15490×
                        Err(e) => {
15500×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1551
                        }
1552
                    }
15530×
                }
15540×
                Some(hex::encode(signed.encode()))
1555
            }
15560×
            None => None,
1557
        };
1558
        // Measured before a cached disk leaves the scratch directory.
15590×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1560
        // A passing job's cached disks are pruned and kept (#72); a
1561
        // failing job's are thrown away, so nothing it wrote reaches a
1562
        // later job.
15630×
        let kept = passed && output_error.is_none();
15640×
        for (i, key, _) in &cached {
15650×
            let disk = crate::cache::disk_path(form, &scratch, *i);
15660×
            let m = disk_mounts[*i];
15670×
            let prune = crate::cache::Prune {
15680×
                started: cache_started,
15690×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
15700×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1571
            };
15720×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
15730×
                Ok(Some(line)) => note(&mut sink, line),
15740×
                Ok(None) => {}
15750×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1576
            }
1577
        }
1578
        Ok(Finish {
15790×
            exit_code: outcome.exit_code,
15800×
            duration_ms: started.elapsed().as_millis() as u64,
15810×
            receipt,
15820×
            signed_receipt,
15830×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1584
            // What the job took (oxygenflow#41): its disks are sparse files
1585
            // in the scratch directory, so their blocks now are their peak.
15860×
            peak_disk_mib,
15870×
            peak_memory_mib: outcome.peak_memory_mib,
1588
        })
1589
    })();
15900×
    let _ = workspace::remove_tree(&scratch);
15910×
    sink.flush();
15920×
    result
15930×
}
1594
1595
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1596
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1597
/// the claim, so the runner vouches only for what it fetched.
1598
/// Upload a report's files, then its manifest under the report's name, and
1599
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1600
/// the manifest's blob, the file count and their total size.
16010×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
16020×
    let mut listed = Vec::with_capacity(files.len());
16030×
    let mut total = 0u64;
16040×
    for (path, bytes) in files {
16050×
        let blob = Repo::blob_ref(bytes).to_hex();
16060×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
16070×
        if named != blob {
16080×
            bail!("the hub kept {path} as {named}, not {blob}");
16090×
        }
16100×
        total += bytes.len() as u64;
16110×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1612
    }
16130×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
16140×
    let blob = Repo::blob_ref(&manifest);
16150×
    let named = hub.artifact(job, name, &manifest)?;
16160×
    if named != blob.to_hex() {
16170×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
16180×
    }
16190×
    Ok((blob, files.len(), total))
16200×
}
1621
16220×
fn sign_receipt(
16230×
    repo: &Repo,
16240×
    heads: &[ChangeHash],
16250×
    cfg: &RunnerConfig,
16260×
    key: &RunnerKey,
16270×
    claim: &Claim,
16280×
    receipt: &Receipt,
16290×
) -> Result<oxy_core::receipt::SignedReceipt> {
16300×
    let state = state_of(heads);
16310×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16320×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
16330×
}
1634
1635
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1636
/// just before signing, so the certificate covers the moment the hub
1637
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1638
/// receipt signed: nothing long-lived signs.
16390×
fn sign_keyless(
16400×
    repo: &Repo,
16410×
    heads: &[ChangeHash],
16420×
    cfg: &RunnerConfig,
16430×
    hub: &Hub,
16440×
    claim: &Claim,
16450×
    receipt: &Receipt,
16460×
) -> Result<oxy_core::receipt::SignedReceipt> {
16470×
    let sk = oxy_core::identity::SecretKey::generate();
16480×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
16490×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
16500×
    let id = sk.identity(&name, "", now);
16510×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
16520×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
16530×
    let state = state_of(heads);
16540×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16550×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
16560×
}
1657
1658
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
16590×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1660
    use oxy_core::hash::{hash_object, ObjectType};
16610×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
16620×
}
1663
16640×
fn hex32(s: &str) -> [u8; 32] {
16650×
    let mut out = [0; 32];
16660×
    if let Ok(v) = hex::decode(s) {
16670×
        if v.len() == 32 {
16680×
            out.copy_from_slice(&v);
16690×
        }
16700×
    }
16710×
    out
16720×
}
1673
1674
/// Whether a network error is worth another try: DNS, a refused or reset
1675
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1676
/// hub restarts (oxygenhub#111).
16778×
fn transient(msg: &str) -> bool {
16788×
    let m = msg.to_lowercase();
16798×
    [
16808×
        "dns failed",
16818×
        "name resolution",
16828×
        "connection refused",
16838×
        "connection reset",
16848×
        "timed out",
16858×
        "timeout",
16868×
        "http 502",
16878×
        "http 503",
16888×
        "http 504",
16898×
        "broken pipe",
16908×
        "unexpected eof",
16918×
    ]
16928×
    .iter()
169347×
    .any(|k| m.contains(k))
16948×
}
1695
1696
/// Run `f` again after a transient network error, waiting `waits` between
1697
/// tries (about a minute in all), and give up on any other error at once.
16983×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
16993×
    let mut tries = waits.iter();
1700
    loop {
17017×
        match f() {
17021×
            Ok(v) => return Ok(v),
17036×
            Err(e) => match tries.next() {
17045×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
17052×
                _ => return Err(e),
1706
            },
1707
        }
1708
    }
17093×
}
1710
1711
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1712
const FETCH_WAITS: [Duration; 5] =
1713
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1714
1715
/// The runner's copy of a repository, fetched up to date with the job's token.
17160×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
17170×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
17180×
}
1719
1720
/// The runner's copy of `repo`, cloned or fetched with `token`.
17210×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
17220×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
17230×
    let set_remote = |repo: &mut Repo| -> Result<()> {
17240×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
17250×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
17260×
        if let Some(ca) = &cfg.ca {
17270×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
17280×
        }
17290×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
17300×
    };
17310×
    if dir.join(".oxy").is_dir() {
17320×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
17330×
        set_remote(&mut repo)?;
17340×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
17350×
        return Ok(repo);
17360×
    }
1737
    // First job for this repository: clone with the job's token, which goes
1738
    // through the process environment, so one clone at a time.
17390×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
17400×
    std::env::set_var("OXY_TOKEN", token);
17410×
    if let Some(ca) = &cfg.ca {
17420×
        std::env::set_var("OXY_CA", ca);
17430×
    }
17440×
    let cloned = with_retries(&FETCH_WAITS, || {
17450×
        let _ = std::fs::remove_dir_all(&dir);
17460×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
17470×
    });
17480×
    std::env::remove_var("OXY_TOKEN");
17490×
    std::env::remove_var("OXY_CA");
17500×
    let mut repo = cloned.map_err(|e| {
17510×
        let _ = std::fs::remove_dir_all(&dir);
17520×
        anyhow::anyhow!("clone {}: {e}", clone_url)
17530×
    })?;
17540×
    set_remote(&mut repo)?;
17550×
    Ok(repo)
17560×
}
1757
1758
#[cfg(test)]
1759
mod tests {
1760
1761
    #[test]
17621×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
17631×
        let dir = tempfile::tempdir().unwrap();
17641×
        let bytes = b"the reviewed plan";
17651×
        let blob = Repo::blob_ref(bytes).to_hex();
17661×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
17676×
            artifact: "tfplan".into(),
17686×
            from: "plan".into(),
17696×
            path: path.into(),
17706×
            blob: blob.into(),
17716×
        };
17721×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
17731×
        assert_eq!(hex::encode(got), blob);
17741×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
17751×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
17761×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
17771×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
17784×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
17794×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1780
        }
17811×
    }
1782
1783
    use super::*;
1784
1785
    #[test]
17861×
    fn a_runner_names_what_stops_a_sandbox() {
17871×
        let dir = tempfile::tempdir().unwrap();
17881×
        let home = Home::locate(Some(dir.path())).unwrap();
17891×
        let bytes = b"not really ext4";
17901×
        let hash = blake3::hash(bytes).to_hex().to_string();
17911×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
17921×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1793
        }))
17941×
        .unwrap();
17956×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
17961×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
17971×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
17981×
        sb.rootfs = hash.clone();
17991×
        assert_eq!(problem(&sb, Some(4096)), None);
18001×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
18011×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
18021×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
18031×
        sb.arch = Some("aarch64".into());
18041×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
18051×
        sb.arch = None;
18061×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
18071×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
18081×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
18091×
    }
1810
1811
    #[test]
18121×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1813
        // An image fetched or imported with no recorded architecture, built
1814
        // for riscv64: the runner reads its shell, records it, and declines
1815
        // instead of running it and failing (spec §11.2, §11.5).
18161×
        let dir = tempfile::tempdir().unwrap();
18171×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
18181×
        let tree = dir.path().join("tree");
18191×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
18201×
        let mut elf = vec![0u8; 64];
18211×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
18221×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
18231×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
18241×
        let img = dir.path().join("rootfs.ext4");
18251×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
18261×
        if !made.is_ok_and(|s| s.success()) {
18270×
            eprintln!("mkfs.ext4 not found: skipped");
18280×
            return;
18291×
        }
18301×
        let hash = crate::home::hash_file(&img).unwrap();
18311×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
18321×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
18331×
        assert!(!home.image_manifest(&hash).exists());
18341×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
18351×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1836
        }))
18371×
        .unwrap();
18381×
        assert_eq!(
18391×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
18401×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1841
        );
18421×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1843
        // Learned: recorded once, and reported with the runner's claims.
18441×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
18451×
        assert_eq!(manifest["arch"], "riscv64");
18461×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
18471×
    }
1848
1849
    #[test]
18501×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
18511×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
18521×
        assert!(transient("HTTP 503: the hub is restarting"));
18531×
        assert!(!transient("HTTP 404: no such repository"));
18541×
        let mut n = 0;
18553×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
18563×
            n += 1;
18573×
            if n < 3 {
18582×
                Err(anyhow::anyhow!("connection refused"))
1859
            } else {
18601×
                Ok(7)
1861
            }
18623×
        });
18631×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
18641×
        let mut m = 0;
18651×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
18661×
            m += 1;
18671×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
18681×
        });
18691×
        assert!(got.is_err());
18701×
        assert_eq!(m, 1, "a refusal is not tried again");
18711×
        let mut k = 0;
18723×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
18733×
            k += 1;
18743×
            Err(anyhow::anyhow!("timed out"))
18753×
        });
18761×
        assert!(got.is_err());
18771×
        assert_eq!(k, 3, "gives up after the last wait");
18781×
    }
1879
1880
    /// A hub that answers each request with the next of `codes`, counting them.
18819×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
18829×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
18839×
    }
1884
1885
    /// A hub at `listener` answering each request with the next of `codes`.
188611×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1887
        use std::io::{Read, Write};
188811×
        let addr = listener.local_addr().unwrap();
188911×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
189011×
        let count = seen.clone();
189111×
        std::thread::spawn(move || {
189222×
            for code in codes {
189322×
                let (mut s, _) = listener.accept().unwrap();
1894
                // Read the whole request (headers, then Content-Length bytes
1895
                // of body) before answering: closing early would reset the
1896
                // connection while the client is still sending.
189722×
                let mut req = Vec::new();
189822×
                let mut buf = [0u8; 8192];
1899
                loop {
190038×
                    let n = s.read(&mut buf).unwrap_or(0);
190138×
                    if n == 0 {
19020×
                        break;
190338×
                    }
190438×
                    req.extend_from_slice(&buf[..n]);
190538×
                    let text = String::from_utf8_lossy(&req);
190638×
                    if let Some(end) = text.find("\r\n\r\n") {
190738×
                        let len = text[..end]
190838×
                            .lines()
1909298×
                            .find_map(|l| {
1910298×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1911298×
                            })
191238×
                            .unwrap_or(0);
191338×
                        if req.len() >= end + 4 + len {
191422×
                            break;
191516×
                        }
19160×
                    }
1917
                }
191822×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
191922×
                let reason = if code == 204 { "No Content" } else { "Error" };
192022×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1921
            }
192210×
        });
192311×
        (format!("http://{addr}"), seen)
192411×
    }
1925
1926
    /// A hub that answers one request with `body` (status 200) and hands
1927
    /// back what it was sent.
19281×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1929
        use std::io::{Read, Write};
19301×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19311×
        let addr = listener.local_addr().unwrap();
19321×
        let (tx, rx) = std::sync::mpsc::channel();
19331×
        std::thread::spawn(move || {
19341×
            let (mut s, _) = listener.accept().unwrap();
19351×
            let mut req = Vec::new();
19361×
            let mut buf = [0u8; 65536];
1937
            loop {
19382×
                let n = s.read(&mut buf).unwrap_or(0);
19392×
                if n == 0 {
19400×
                    break;
19412×
                }
19422×
                req.extend_from_slice(&buf[..n]);
19432×
                let text = String::from_utf8_lossy(&req);
19442×
                if let Some(end) = text.find("\r\n\r\n") {
19452×
                    let len = text[..end]
19462×
                        .lines()
194714×
                        .find_map(|l| {
194814×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
194914×
                        })
19502×
                        .unwrap_or(0);
19512×
                    if req.len() >= end + 4 + len {
19521×
                        break;
19531×
                    }
19540×
                }
1955
            }
19561×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
19571×
            let _ = write!(
19581×
                s,
1959
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
19601×
                body.len()
1961
            );
19621×
        });
19631×
        (format!("http://{addr}"), rx)
19641×
    }
1965
1966
    #[test]
19671×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1968
        use std::os::unix::fs::PermissionsExt;
19691×
        let dir = tempfile::tempdir().unwrap();
19701×
        let home = Home::locate(Some(dir.path())).unwrap();
19711×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
19721×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
19731×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
19741×
        let req = sent.recv().unwrap();
19751×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
19761×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
19771×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
19781×
        let key = home.runner_key("plex").unwrap();
19791×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
19801×
        let path = dir.path().join(crate::home::RUNNER_TOML);
19811×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1982
        // The runner then starts from runner.toml.
19831×
        let again = Home::locate(Some(dir.path())).unwrap();
19841×
        let cfg = again.config.runner.unwrap();
19851×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
19861×
        assert_eq!(cfg.labels, ["gpu"]);
19871×
    }
1988
1989
    /// A hub that answers certify with a certificate `sign_as` signs for
1990
    /// `cert_key`, and publishes `published` as its key: two requests.
19913×
    fn fake_certify_hub(
19923×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
19933×
        cert_key: oxy_core::identity::Identity,
19943×
        published: oxy_core::identity::Identity,
19953×
    ) -> String {
1996
        use std::io::{Read, Write};
19973×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19983×
        let addr = listener.local_addr().unwrap();
19993×
        std::thread::spawn(move || {
20003×
            for _ in 0..2 {
20016×
                let Ok((mut s, _)) = listener.accept() else { return };
20026×
                let mut req = Vec::new();
20036×
                let mut buf = [0u8; 65536];
2004
                loop {
20057×
                    let n = s.read(&mut buf).unwrap_or(0);
20067×
                    if n == 0 {
20070×
                        break;
20087×
                    }
20097×
                    req.extend_from_slice(&buf[..n]);
20107×
                    let text = String::from_utf8_lossy(&req);
20117×
                    if let Some(end) = text.find("\r\n\r\n") {
20127×
                        let len = text[..end]
20137×
                            .lines()
201447×
                            .find_map(|l| {
201547×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
201647×
                            })
20177×
                            .unwrap_or(0);
20187×
                        if req.len() >= end + 4 + len {
20196×
                            break;
20201×
                        }
20210×
                    }
2022
                }
20236×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
20246×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
20253×
                    let cert = oxy_core::cert::SignedCertificate::sign(
20263×
                        oxy_core::cert::Certificate {
20273×
                            key: cert_key.clone(),
20283×
                            issuer: sign_as.0.hash(),
20293×
                            subject: "repo:andy/demo:bookmark:main".into(),
20303×
                            claims: vec![],
20313×
                            scope: oxy_core::identity::Scope::SEAL,
20323×
                            not_before: 1,
20333×
                            expires: 600_001,
20343×
                            grant: None,
20353×
                        },
20363×
                        &sign_as.0,
20373×
                        &sign_as.1,
2038
                    );
20393×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
2040
                } else {
20413×
                    published.encode()
2042
                };
20436×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
20446×
                let _ = s.write_all(&body);
2045
            }
20463×
        });
20473×
        format!("http://{addr}")
20483×
    }
2049
2050
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2051
    /// is for its fresh key and signed by the key the hub publishes.
2052
    #[test]
20531×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2054
        use oxy_core::identity::SecretKey;
20551×
        let hub_sk = SecretKey::generate();
20561×
        let hub_id = hub_sk.identity("hub", "", 1);
20571×
        let sk = SecretKey::generate();
20581×
        let id = sk.identity("earth-1 job 7", "", 1);
20591×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2060
20611×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
20621×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
20631×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2064
20651×
        let mallory_sk = SecretKey::generate();
20661×
        let mallory = mallory_sk.identity("mallory", "", 1);
20671×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
20681×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20691×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2070
20711×
        let other = SecretKey::generate().identity("other", "", 1);
20721×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
20731×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20741×
        assert!(e.contains("another key"), "{e}");
20751×
    }
2076
207716×
    fn hub_at(base: String) -> Hub {
207816×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
207916×
    }
2080
2081
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2082
    /// hub attests; a peer or a proxy cannot change what is installed.
2083
    #[test]
20841×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
20851×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
20862×
        let serve = |bytes: Vec<u8>| {
20872×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20882×
            let addr = listener.local_addr().unwrap();
20892×
            std::thread::spawn(move || {
2090
                use std::io::{Read, Write};
20912×
                let (mut s, _) = listener.accept().unwrap();
20922×
                let mut buf = [0u8; 4096];
20932×
                let _ = s.read(&mut buf);
20942×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
20952×
                let _ = s.write_all(&bytes);
20962×
            });
20972×
            format!("http://{addr}")
20982×
        };
20991×
        let offer = flow_core::api::UpdateOffer {
21001×
            version: "0.3.2".into(),
21011×
            asset: "flow-linux-x86_64".into(),
21021×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
21031×
            blake3: blake3::hash(&body).to_hex().to_string(),
21041×
            size: body.len() as u64,
21051×
            ..Default::default()
21061×
        };
21071×
        let dir = tempfile::tempdir().unwrap();
21081×
        let to = dir.path().join("flow-0.3.2");
21091×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
21101×
        assert_eq!(std::fs::read(&to).unwrap(), body);
21111×
        std::fs::remove_file(&to).unwrap();
21121×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
21131×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
21141×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
21151×
    }
2116
2117
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2118
    /// through server errors, and a refusal ends the trying at once.
2119
    #[test]
21201×
    fn a_result_is_reported_until_the_hub_takes_it() {
21211×
        let f = Finish {
21221×
            exit_code: Some(0),
21231×
            duration_ms: 1,
21241×
            receipt: None,
21251×
            signed_receipt: None,
21261×
            error: None,
21271×
            peak_disk_mib: None,
21281×
            peak_memory_mib: None,
21291×
        };
21301×
        let quick = Duration::from_millis(10);
21311×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
21321×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
21331×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
21341×
        let (base, seen) = fake_hub(vec![409]);
21351×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
21361×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21371×
    }
2138
2139
    #[test]
21401×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
21411×
        let quick = [Duration::from_millis(10); 3];
21421×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
21431×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
21441×
        assert!(r.is_none());
21451×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2146
21471×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
21481×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
21491×
        assert!(e.contains("HTTP 500"), "{e}");
21501×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2151
21521×
        let (base, seen) = fake_hub(vec![401]);
21531×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
21541×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21551×
    }
2156
2157
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2158
2159
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2160
    /// cancelled, having sent what the job said so far, and the job is
2161
    /// handed back to the hub.
2162
    #[test]
21631×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2164
        use microvm::Sink;
21651×
        let leaving = std::sync::Mutex::new(None);
21661×
        let (base, seen) = fake_hub(vec![204, 204]);
21671×
        let hub = hub_at(base);
21681×
        let mut sink = LogSink {
21691×
            hub: &hub,
21701×
            job: 7,
21711×
            buf: Vec::new(),
21721×
            last: Instant::now(),
21731×
            gone: false,
21741×
            leaving: &leaving,
21751×
            started: Instant::now(),
21761×
            expected: None,
21771×
        };
21781×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
21791×
        assert!(!sink.cancelled());
21801×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
21811×
        assert!(sink.cancelled());
21821×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
21831×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
21841×
        hub.release(7, "off Wi-Fi").unwrap();
21851×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
21861×
    }
2187
2188
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2189
    /// it runs on; one that will not, or whose time is unknown, is handed
2190
    /// back at once, and any job still running when the notice is up.
2191
    #[test]
21921×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2193
        use microvm::Sink;
21941×
        let (base, _) = fake_hub(vec![204; 8]);
21951×
        let hub = hub_at(base);
21961×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
21971×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
21984×
            hub: &hub,
2199
            job: 1,
22004×
            buf: Vec::new(),
22014×
            last: Instant::now(),
2202
            gone: false,
22034×
            leaving: &leaving,
22044×
            started: Instant::now() - Duration::from_secs(ran),
22054×
            expected: expected.map(Duration::from_secs),
22064×
        };
22071×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
22081×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
22091×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
22101×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
22111×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
22121×
    }
2213
2214
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2215
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2216
    #[test]
22171×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2218
        use microvm::Sink;
22192×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
22201×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
22211×
        let (base, seen) = fake_hub(vec![204]);
22221×
        let hub = hub_at(base);
22231×
        let mut sink = LogSink {
22241×
            hub: &hub,
22251×
            job: 1,
22261×
            buf: Vec::new(),
22271×
            last: quiet,
22281×
            gone: false,
22291×
            leaving: &NOT_LEAVING,
22301×
            started: Instant::now(),
22311×
            expected: None,
22321×
        };
22331×
        assert!(!sink.cancelled());
22341×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
22351×
        assert_eq!(n(&seen), 1);
2236
22371×
        let (base, seen) = fake_hub(vec![409]);
22381×
        let hub = hub_at(base);
22391×
        let mut sink = LogSink {
22401×
            hub: &hub,
22411×
            job: 1,
22421×
            buf: Vec::new(),
22431×
            last: quiet,
22441×
            gone: false,
22451×
            leaving: &NOT_LEAVING,
22461×
            started: Instant::now(),
22471×
            expected: None,
22481×
        };
22491×
        assert!(sink.cancelled());
22501×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
22511×
        sink.flush();
22521×
        assert!(sink.cancelled());
22531×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
22541×
    }
2255
2256
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2257
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2258
    /// no lines.
2259
    #[test]
22601×
    fn a_job_outlasts_a_hub_restart() {
22612×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2262
        // A port nobody listens on yet: the hub is restarting.
22631×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22641×
        let base = format!("http://127.0.0.1:{port}");
22651×
        let hub = hub_at(base.clone());
2266
2267
        // Log lines sent while it is away are kept, and go when it is back.
22681×
        let mut sink = LogSink {
22691×
            hub: &hub,
22701×
            job: 1,
22711×
            buf: Vec::new(),
22721×
            last: Instant::now(),
22731×
            gone: false,
22741×
            leaving: &NOT_LEAVING,
22751×
            started: Instant::now(),
22761×
            expected: None,
22771×
        };
2278450×
        for i in 0..450 {
2279450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2280450×
        }
22811×
        sink.send();
22821×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
22831×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
22841×
        sink.send();
22851×
        assert!(sink.buf.is_empty() && !sink.gone);
22861×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2287
2288
        // An upload waits for the hub to come back, through refused
2289
        // connections and server errors alike.
22901×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22911×
        let url = format!("http://127.0.0.1:{port}/x");
22921×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
22931×
        let later = std::thread::spawn(move || {
22941×
            std::thread::sleep(Duration::from_millis(150));
22951×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
22961×
        });
22971×
        let quick = [Duration::from_millis(50); 20];
22985×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
22991×
        assert_eq!(r.status(), 204);
23001×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2301
        // Without `connection`, a hub that cannot be reached ends it at once.
23021×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23031×
        let url = format!("http://127.0.0.1:{port}/x");
23041×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
23051×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
23061×
    }
2307
2308
    /// oxygenflow#50: the first stop drains (the second, not called here,
2309
    /// exits at once).
2310
    #[test]
23111×
    fn a_stop_drains_the_runner() {
23121×
        assert!(!stopping());
23131×
        on_stop(libc::SIGTERM);
23141×
        assert!(stopping(), "told to stop, it claims nothing more");
2315
        // An embedded runner starts afresh, and stop() drains it the same way.
23161×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23171×
        stop();
23181×
        assert!(stopping());
23191×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
23201×
    }
2321
2322
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2323
    #[test]
23241×
    fn unsent_log_lines_are_bounded() {
23251×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
23261×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
23271×
        let mut sink = LogSink {
23281×
            hub: &hub,
23291×
            job: 1,
23301×
            buf: Vec::new(),
23311×
            last: Instant::now(),
23321×
            gone: false,
23331×
            leaving: &NOT_LEAVING,
23341×
            started: Instant::now(),
23351×
            expected: None,
23361×
        };
233750010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
23381×
        sink.send();
23391×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
23401×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
23411×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
23421×
    }
2343
2344
    #[test]
23451×
    fn the_budget_admits_jobs_that_fit() {
23461×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
23477×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
23481×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
23491×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
23501×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
23511×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
23521×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
23531×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
23541×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
23551×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
23561×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
23571×
    }
2358
2359
    #[test]
23601×
    fn a_claim_never_asks_for_more_memory_than_the_host_has_free() {
23611×
        assert_eq!(claim_memory(None, Some(6541)), Some(6541), "idle: the host's free memory, not unlimited");
23621×
        assert_eq!(claim_memory(Some(16_384), Some(6541)), Some(6541));
23631×
        assert_eq!(claim_memory(Some(4096), Some(6541)), Some(4096), "the budget when it is smaller");
23641×
        assert_eq!(claim_memory(None, None), None, "nothing known: no limit, as before");
23651×
        assert_eq!(claim_memory(Some(4096), None), Some(4096));
23661×
    }
2367
}